Azure MS Graph Claim Mapping Policy Powershell - azure

I am a little confused with the MS Graph article[Vague] related to Claim Mapping Policy. I am trying to create claims using PowerShell. used below format to create new claims map getting error
New-MgPolicyClaimMappingPolicy : Property definition has an invalid value.
Help is needed Here!!!
$policymap=[ordered]#{
definition=#(
#"
{
"claimsMappingPolicy" :
{
"claimsSchema":[
{
"source":"user"
"id":"assignedrikes"
"samlclaimtype":"https://aws.amazon.com/SAML/Attributes/Role"
},
{
"source":"user"
"id":"assignedrikes"
"samlclaimtype":"https://aws.amazon.com/SAML/Attributes/RoleSessionName"
}
]
}
}
"#
)
displayname="Test"
isorganizationdefault=$false
}
New-MgPolicyClaimMappingPolicy -BodyParameter $policymap

New claims map getting error New-MgPolicyClaimMappingPolicy
This error may occur if you are using incorrect format samlclaimtype instead of using MgPolicyClaimMappingPolicy, make sure to install Azure AD Preview while running below script.
Please check below few workarounds:
I installed Azure AD Preview module and created claims using below script.
Connect-AzureAD
New-AzureADPolicy -Definition #('
{
"ClaimsMappingPolicy":
{
"Version":1,"IncludeBasicClaimSet":"true",
"ClaimsSchema": [{"Source":"user","ID":"extensionattribute1","SamlClaimType":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/vikram","JwtClaimType":"vikram"}]
}
}') -DisplayName "vikram" -Type "ClaimsMappingPolicy"
Result:
Try to add service principal and check if it is succeeded or not.
For service principal ID, Go to Azure Portal -> Enterprise Applications -> Your Web API -> object ID like below:
Add-AzureADServicePrincipalPolicy -Id <ObjectId of the Web API ServicePrincipal> -RefObjectId <ObjectId of the Policy>
Get-AzureADServicePrincipalPolicy -Id <ObjectId of the Web API ServicePrincipal>
To assign value to that claim, login to Microsoft Graph Explorer with your tenant admin account and run below script. ***This completes the development of your claims mapping successfully. ***
PATCH https://graph.microsoft.com/beta/me
{
"onPremisesExtensionAttributes":
{
"extensionAttribute1": "vedha"
}
}
Now Go to Azure Portal -> Azure Active Directory -> App registrations -> Your App -> Manifest to make your claims to accept as true like below:
Then, Go to Expose an API under manage edit your Application ID URI pattern like https://<yourTenantDomain> instead of default api://<GUID>, and save.
Generate access token and you can see that custom claim you created in the decoded token. To decode the token, you can use jwt.ms website

Related

Unable to get access token. 'AADSTS500011: The resource principal named 'xxx' was not found in the tenant -tenantid

I am trying to get the access token for the Azure function app. I have enabled managed identity for the function app(system assigned). but while fetching the token using the nuget Azure.Identity.
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://xxx.azure-api.net/" + "/.default" }) { }
);
I am getting the error.
The resource principal named 'xxx.azure-api.net' was not found in
the tenant 123
but when run az cli to check the subscription details, the subscription indeed part of the tenant 123 only.
Here is what I have finally done.
I have registered an App in AD. and Exposed the API of that App.
I have assigned System Assigned Managed Identity to the Function.
In the local I am not able to request token because Azure CLI is not given consent.
After deploying the application in Function my Function app can request a token using its identity.
You need to register the application in azure ad and enable the access token. Once that is done the you need to provide RBAC access to your xxx.azurewebsites.net
Follow this article for the step by step documentation Microsoft Document Reference
Unfortunately, the error message is not really helpful. But adding a scope to the app registration solved the problem for me:
In Azure Portal navigate to App Registrations
Find your app, in the left side menu select Manage => Expose an API
Add a scope. I named mine api_access as this was where this error occurred.
In my case I then got an API URI (like api://client-id/scope_name) which I used in my Angular app. Error message was gone.
Also, make sure that in the Enterprise Application you have created, under Manage => Properties, "Assignment required" and "Visible to users" is turned on.

Azure Keyvault - "The operation "List" is not enabled in this key vault's access policy." while creating keyvault programmatically

I am creating azure keyvault using .net core 2.1 with OpenIdConnect with following AccessPolicies
AccessPolicies = new List<AccessPolicyEntry>()
{
new AccessPolicyEntry
{
TenantId = Guid.Parse(tenantId),
ObjectId = objectId,
Permissions = new Permissions
{
Secrets = new List<string> { "all" },
Keys = new string[] { "all" },
Certificates = new string[]{"all" }
}
}
}
using that, now, I can create keyvault but while go to newly created keyvault(in Azure portal) settings blade {Key,Secrete,Certificate} it shows warning
"The operation "List" is not enabled in this key vault's access policy."
Note :- As shown in above code "All permission are given".I can see it in azure portal.
What I have tried :-
I have tried to refer following stack-overflow already question-answer
Azure Keyvault - "Operation "list" is not allowed by vault policy" but all permissions are checked
How do I fix an "Operation 'set' not allowed" error when creating an Azure KeyVault secret programmatically?
according to above stackoverflow answer(s) "need to pass the object ID of the service principal of the Azure AD application instead of object ID of your Azure AD application".
I have tried to find out object ID of the service principal of the azure AD application using following powershell script
Get-AzADServicePrincipal -ServicePrincipalName "<app client ID>"
it gives following result
I have tried to use "Id"(in above screenshot) in objectId of AccessPolicyEntry but it not solved problem.
Question :-
Is any other permission need to set in AccessPolicyEntry?
What should be the objectID in AccessPolicyEntry(currently, I am giving obectId of Azure AD application)?
If needed objectId of service princpal. how can get it programmatically?
Well, I can reproduce your issue on my side.
First, the operation pass the object ID of the service principal instead of object ID of your Azure AD application is completely correct. After giving all the permissions to the service principal in the Access policies, the service principal will have the permissions.
But when you check the keyvault in the portal, you are using your user account which login the azure portal instead of the service principal, it caused the warning.
So if you want to fix the warning, just add your user account in the Access policies via + Add Access Policy button in the portal, or you can specify the object id of your user account in your code with the permissions when creating the keyvault.
Then about your questions:
Is any other permission need to set in AccessPolicyEntry?
No, the permissions are enough.
What should be the objectID in AccessPolicyEntry(currently, I am giving obectId of Azure AD application)?
You should not use the object id of the AD App, your option is to use the object id of the service principal/security group/user account, it depends on your requirement, details here.
If needed objectId of service principal. how can get it programmatically?
You can use the powershell command as you used, or the Azure CLI az ad sp show via the service principal name.
Or if you could use Microsoft Graph SDK for C# along with the filter, something like:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var serviceprincipals = await graphClient.Serviceprincipals
.Request().
.Filter("some condition").
.GetAsync();

Azure AD Extension Property + MS Graph API PATCH = Insufficient privileges to complete the operation

I've been breaking my head over this problem for the past 2 days.
My goal is to allow a user (any regular non-admin Azure AD user) to update the value of an (Azure AD) extension property for his AD 'profile'/account through the Microsoft Graph API.
Consider the following situation:
I'm in control (Global Admin) of some Azure tenant + Azure AD Directory
There's a regular Azure AD User "Joe"
I've created an App registration + Service Principal (either through PS or in the Azure Web UI)
I've created an Azure AD Extension Property using the following Azure AD PS commands:
Connect-AzureAD -TenantId xxx-xxx-xxx
$app = Get-AzureADApplication -ObjectId yyy-yyy-yyy
$app | New-AzureADApplicationExtensionProperty -Name "MyProp" -DataType "String" -TargetObjects "User"
Response:
Name TargetObjects
---- -------------
extension_b63fa5d85b9d43b8b60f982e4bf2ad11_MyProp {User}
I've Admin consented everything on Graph both on Enterprise Application "Graph Explorer" and on my own App Registration, especially Directory.ReadWriteAll and User.ReadWrite.All
I then use the Graph Explorer (or Postman using my own App Registration) logged on as regular user "Joe"
Using the following PATCH request fails:
PATCH https://graph.microsoft.com/v1.0/me/
with body (type application/JSON):
{
"extension_b63fa5d85b9d43b8b60f982e4bf2ad11_MyProp": "test"
}
It fails with the following response:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"request-id": "d0ef63c0-f944-44c4-b90d-413b076b2bca",
"date": "2019-04-11T08:21:48"
}
}
}
I seem to be unable to find out why this happens.
Things to note:
When I log on in Graph Explorer as global admin I am able to update this property successfully
I am also able to update this property for any user using Azure AD PS, logged in as global admin
As soon as I give Joe the Global Admin or User Admin role in Azure AD he is able to update the property too
As "Joe", using the above PATCH request in Graph Explorer (or Postman), I am able to update "mobilephone"
As "Joe", using the above PATCH request in Graph Explorer (or Postman), I am unable to update "city", or "givenname"
What am I doing wrong?

Grant an existing B2C app access to graph API

I have an existing B2C app that I want to give graph access to.
I set this up previously but now want to replicate it but everything i can find is for new apps. I ysed the older graph but i think the article I used has been moved as everything is talking about the new Graph api
Is there a specific article for this, also if anyone has seen an article that describes the process from moving from Azure graph to Microsoft Graph (the new version) for a B2C app that would be great
Thanks
Register the application for the Graph API
In addition to registering the application in the B2C directory,
we must also create an application registration for the graph API.
The three key/id values you will need are the tenantId, ObjectId,
and AppPrincipalId.
To get the tenantId, log into the azure ad b2c directory in the new portal.
https://portal.azure.com/
Be sure you have the correct directory selected after you login
(top right corner).
Click on the help button (a question mark inside a circle) near the
top right corner of the page. In the menu that appears, click the
"Show diagnostics" option. This will display a JSON formatted output in
a new popup/window. Look for the "tenants" array and find the entry
with the display name of the directory you wish to register with the
application. The "id" attribute of that entry is the tenantId.
Example:
{
"clientSessionStartDate": {
//stuff will be here ...
},
//
// more shtuff you don't care about will be here ...
//
"tenants": [
{
"id": "SomeUUIDwithlike36charactersSometime",
"domainName": "yourtenantname.onmicrosoft.com",
"displayName": "displanynameoftenant",
"isSignedInTenant": true
},
// ... snippity lemon
]
// ... snip some more
}
You will also need a unique application Secret and AppPrincipalId to be
generated for the new application.
Also, to set the correct permissions for the application, you will need
its "ObjectId".
The process for registering the application and generating those values
is more complicated, and requires a special module for PowerShell
and the online login module to be downloaded and installed.
Also, be sure you have the latest version of PowerShell installed for
your system, or you will not be able to use the azure module.
Sign-In assistant: https://www.microsoft.com/en-us/download/details.aspx?id=41950
Azure AD PowerShell Module: http://go.microsoft.com/fwlink/p/?linkid=236297
Create the application registration with PowerShell
This next section is an almost verbatim copy-paste fo the documentation.
https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/
After you install the PowerShell module, open PowerShell and connect to
your B2C tenant.
> $msolcred = Get-Credential
After you run Get-Credential, you will be prompted for
a user name and password, Enter the user name and password
of your B2C tenant administrator account.
> Connect-MsolService -credential $msolcred
Before you create your application, you need to generate a new client
secret. Your application will use the client secret to authenticate to
Azure AD and to acquire access tokens. You can generate a valid secret
in PowerShell:
> $bytes = New-Object Byte[] 32
> $rand = [System.Security.Cryptography.RandomNumberGenerator]::Create()
> $rand.GetBytes($bytes)
> $rand.Dispose()
> $newClientSecret = [System.Convert]::ToBase64String($bytes)
> $newClientSecret
The final command should print your new client secret. Copy it somewhere safe. You'll need it later. Now you can create your application by providing the new client secret as a credential for the app:
> New-MsolServicePrincipal -DisplayName "My New B2C Graph API App" -Type password -Value $newClientSecret
Example output:
DisplayName : My New B2C Graph API App
ServicePrincipalNames : {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
ObjectId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AppPrincipalId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
TrustedForDelegation : False
AccountEnabled : True
Addresses : {}
KeyType : Password
KeyId : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
StartDate : 1/1/2017 1:33:09 AM
EndDate : 1/1/2017 1:33:09 AM
Usage : Verify
If you successfully create the application, it should print out
properties of the application like the ones above, but with a mix of alpha-numeric characters. You'll need both
ObjectId and AppPrincipalId, so copy those values, too.
You will also need the tenant ID of the B2C directory.
After you create an application in your B2C tenant, you need to assign
it the permissions it needs to perform user CRUD operations. Assign the
application three roles: directory readers (to read users), directory
writers (to create and update users), and a user account administrator
(to delete users). These roles have well-known identifiers, so you can
replace the -RoleMemberObjectId parameter with ObjectId from above and
run the following commands. To see the list of all directory roles,
try running Get-MsolRole.
> Add-MsolRoleMember -RoleObjectId 88d8e3e3-8f55-4a1e-953a-9b9898b8876b -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId 9360feb5-f418-4baa-8175-e2a00bac4301 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
> Add-MsolRoleMember -RoleObjectId fe930be7-5e62-47db-91af-98c3a49a38b1 -RoleMemberObjectId <Your-ObjectId> -RoleMemberType servicePrincipal
You now have an application that has permission to create, read,
update, and delete users from your B2C tenant.
I totally forgot this great answer exists and this is how you do it
Authorize By Group in Azure Active Directory B2C

How to get the azure account tenant Id?

My question is: Is it possible to get the azure active directory tenant id without using powershell command?
I found this two blogs and with this help, I'm already able to get the tenant ID and subscriptions ID from powershell. Is it the only way to retrieve the tenant?
Get Windows Azure Active Directory Tenant ID in Windows PowerShell
Windows Azure AD authentication support for PowerShell
Thanks
Time changes everything. I was looking to do the same recently and came up with this:
Note
added 02/17/2021
Stable Portal Page thanks Palec
added 12/18/2017
As indicated by shadowbq, the DirectoryId and TenantId both equate to the GUID representing the ActiveDirectory Tenant. Depending on context, either term may be used by Microsoft documentation and products, which can be confusing.
Assumptions
You have access to the Azure Portal
Solution
The tenant ID is tied to ActiveDirectoy in Azure
Navigate to Dashboard
Navigate to ActiveDirectory
Navigate to Manage / Properties
Copy the "Directory ID"
Azure ActiveDirectory Tenant ID:
Go to https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration and you'll see a bunch of URLs containing your tenant ID.
My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.
So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!
How to find my Microsoft 365, Azure or SharePoint Online tenant ID?
In the Azure CLI (I use GNU/Linux):
$ azure login # add "-e AzureChinaCloud" if you're using Azure China
This will ask you to login via https://aka.ms/devicelogin or https://aka.ms/deviceloginchina
$ azure account show
info: Executing command account show
data: Name : BizSpark Plus
data: ID : aZZZZZZZ-YYYY-HHHH-GGGG-abcdef569123
data: State : Enabled
data: Tenant ID : 0XXXXXXX-YYYY-HHHH-GGGG-123456789123
data: Is Default : true
data: Environment : AzureCloud
data: Has Certificate : No
data: Has Access Token : Yes
data: User name : nico#XXXXXXX.onmicrosoft.com
data:
info: account show command OK
or simply:
azure account show --json | jq -r '.[0].tenantId'
or the new az:
az account show --subscription a... | jq -r '.tenantId'
az account list | jq -r '.[].tenantId'
I hope it helps
The tenant id is also present in the management console URL when you browse to the given Active Directory instance, e.g.,
https://manage.windowsazure.com/<morestuffhere>/ActiveDirectoryExtension/Directory/BD848865-BE84-4134-91C6-B415927B3AB1
Just to add a new method to an old (but still relevant question).
In the new portal, clicking the help icon from any screen and selecting 'Show Diagnostics' will show you a JSON document containing all your tenant information including TenantId, Tenant Name, and much, much more useful information
This answer was provided on Microsoft's website, last updated on 3/21/2018:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal
In short, here are the screenshots from the walkthrough:
Select Azure Active Directory.
To get the tenant ID, select Properties for your Azure AD tenant.
Copy the Directory ID. This value is your tenant ID.
Hope this helps.
Via PowerShell anonymously:
(Invoke-WebRequest https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration|ConvertFrom-Json).token_endpoint.Split('/')[3]
Another way to get it from App registrations
Azure Active Directory -> App registrations -> click the app and it will show the tenant ID like this
You can run a simple curl call to get the tenant id of an azure subscription without any authentication.
make a curl call to :
https://management.azure.com/subscriptions/{subscription-id}?api-version=2015-01-01
The request fails but you will be able to get the tenant id from the response header. The tenant id is present in line followed by "WWW-Authenticate: Bearer authorization_uri="https://login.windows.net/"
you can use curl -v to show the response header.
As of now (06/07/2018), an easy approach would be running az account show in the Azure Cloud Shell (requires a Storage Account) in the Azure Portal.
--- Command ---
az account show
--- Command Output ---
{
"environmentName": "AzureCloud",
"id": "{Subscription Id (GUID)}",
"isDefault": true,
"name": "{Subscription Name}",
"state": "Enabled",
"tenantId": "{Tenant Id (GUID)}",
"user": {
"cloudShellID": true,
"name": "{User email}",
"type": "user"
}
}
Find more details on Azure Cloud Shell at Overview of Azure Cloud Shell | Microsoft Docs.
If you have installed Azure CLI 2.0 in your machine, you should be able to get the list of subscription that you belong to with the following command,
az login
if you want to see as a table output you could just use
az account get-access-token --query tenant --output tsv
or you could use the Rest API
Tenants - List | Microsoft Docs
Use the Azure CLI
az account get-access-token --query tenant --output tsv
In PowerShell:
Add-AzureRmAccount #if not already logged in
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId
One click answer:
open this URL:
https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Properties
If you have Azure CLI setup, you can run the command below,
az account list
or find it at ~/.azure/credentials
Step 1: Login to Microsoft Azure portal
Step 2: Search Azure Active directory
Step 3: Click on overview and find the tenant id from tenant information section
From Java:
public static String GetSubscriptionTenantId (String subscriptionId) throws ClientProtocolException, IOException
{
String tenantId = null;
String url = "https://management.azure.com/subscriptions/" + subscriptionId + "?api-version=2016-01-01";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header[] headers = response.getAllHeaders();
for (Header header : headers)
{
if (header.getName().equals("WWW-Authenticate"))
{
// split by '"' to get the URL, split the URL by '/' to get the ID
tenantId = header.getValue().split("\"")[1].split("/")[3];
}
}
return tenantId;
}
According to Microsoft:
Find your tenantID: Your tenantId can be discovered by opening the following metadata.xml document: https://login.microsoft.com/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml - replace "graphDir1.onMicrosoft.com", with your tenant's domain value (any domain that is owned by the tenant will work). The tenantId is a guid, that is part of the sts URL, returned in the first xml node's sts url ("EntityDescriptor"): e.g. "https://sts.windows.net/".
Reference:
https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-graphapi-web/
A simple way to get the tenantID is:
Connect-MsolService -cred $LiveCred #sign in to tenant
(Get-MSOLCompanyInformation).objectid.guid #get tenantID
Using Azure Portal:
Step1: Login to azure portal and search for Azure Active Directory and select it .
Step2: In the overview page of Azure Active Directory,find the tenant ID.
Using Azure CLI:
Use one of the commands az login, az account list, or az account tenant list. Find the TenantId property for each of subscriptions in the output from each command.
Using Powershell
Use the below command in powershell cmdlet.
Connect-AzAccount
Get-AzTenant
Reference:
Azure CLI
Get-Aztenant
I use following to get tenant id
az account show --query homeTenantId --output tsv
You can also get the tenant id, in fact all subscription details by logging into the url resources.azure.com
For AAD-B2C it is fairly simple. From Azure Portal with a B2C directory associated, go to your B2C directory (I added the "Azure AD B2C" to my portal's left menu). In the B2C directory click on "User flows (policies) directory menu item. In the policies pane click on one of your policies you previously added to select it. It should open a pane for the policy. Click "Properties". In the next pane is a section, "Token compatibility settings" which has a property "Issuer". Your AAD-B2C tenant GUID is contained in the URL.
The one working for me is this (after az login):
az account show |grep tenantId | awk {'print $2'} |tr -d '[:punct:]'
Go to the Azure portal > Azure Active Direcrory.
On the main screen, you should see your tenant ID.
xxx#Azure:~$ az ad sp create-for-rbac
Retrying role assignment creation: 1/36
{
"appId": "401143c2-95ef-4792-9900-23e07f7801e7",
"displayName": "azure-cli-2018-07-10-20-31-57",
"name": "http://azure-cli-2018-07-10-20-31-57",
"password": "a0471d14-9300-4177-ab08-5c45adb3476b",
"tenant": "e569f29e-b008-4cea-b6f0-48fa8532d64a"
}

Resources