Programatically get users group and role from Azure AD - azure

I am new to azure AD.
I have a third party API which gives me a userId. I have written a .NET Core API which should take this userID and get the roles and groups of that specific user.
I have read about the microsoft graph API. Not sure if this is useful in my scenario.
Also is there any other way to access the roles and groups of a AD user programatically.

Which API to use to get groups and role information
Firstly, Microsoft Graph API is your best bet to get the information you're looking for.
Which exact API works best for you depends on your scenario (a. do you need top level direct membership or transitive check? b. do you want only security groups or even O365 groups?), so you're the best judge.
I'll list down 3 of them here and you should get some ideas to pick.
memberOf -
Gets both groups and directory roles that user is a direct member of.
NOTE: only direct membership matters for this one, check is NOT transitive (i.e. User has to be a direct member of the group for that group to be returned. If user is member of a group1, but that group1 is member of group2, then group2 will NOT be returned. This behavior might be ok for some scenarios but not for others)
GET /users/{id | userPrincipalName}/memberOf
getMemberGroups
POST /users/{id | userPrincipalName}/getMemberGroups
Returns all the groups that the user is a member of. Check for this one is Transitive, so you're assured that all groups will be returned. Upto 2046 returned as part of 1 request. It also works with O365 groups and you can filter down to SecurityEnabled groups using a parameter
getMemberObjects
Returns all of the groups, directory roles and administrative units that the user is a member of. The check is again transitive.
Implementation and Code Sample.. How to get token, call API etc.
Acquiring Token for Authentication
You should make use of MSAL or ADAL libraries depending on which Azure AD endpoint you're using MSAL for v2 and ADAL for v1. Using these libraries is not mandatory but recommended because they will follow best practices and do the heavy lifting for you.
Interacting with Microsoft Graph API Endpoints
Since you're writing in .NET, you can make use of Microsoft Graph Client Library for .NET (SDK). Again, it's not mandatory to use the client library but it will make your code more declarative and will be convenient. You can always work with HttpClient and hit the REST endpoints directly if you want.
Code Sample
Microsoft Graph Connect Sample for ASP.NET Core 2.1
Important parts.. Look at the GraphService.cs file for methods that get user information, e.g.
// Load user's profile in formatted JSON.
public static async Task<string> GetUserJson(GraphServiceClient graphClient, string email, HttpContext httpContext)
{
if (email == null) return JsonConvert.SerializeObject(new { Message = "Email address cannot be null." }, Formatting.Indented);
try
{
// Load user profile.
var user = await graphClient.Users[email].Request().GetAsync();
return JsonConvert.SerializeObject(user, Formatting.Indented);
}
NOTE: The sample makes use of delegated permissions. You may need to make use of application permissions directly or On-behalf of flow (if you want to do it under a user's context) since you mention yours is an API being called. Also, this is just one of the samples, that you should look at to understand how to work with SDK, but there are many available readily once you start looking further into Microsoft Graph API and Client library documentation. I'll update the answer if I find a sample closer to your exact scenario.

Related

How to expose some API methods without subscription while keeping subscription for others?

I am using Azure API Management to proxy requests from Internet to our backend systems. I have a Product entry on Azure Portal and an API entry associated with the product. Generally access to the API must be by subscription, but I would like the method returning OpenAPI specification (as well as probably few other methods) to be accessible without subscription (freely).
I see "Requires subscription" checkbox on the Product level as well as on API level, but not on a method's level. So I need either:
bypass subscription check for certain methods while keeping access by subscription for others, or:
same but vice versa: keep the access free for API, but enforce subscription check for certain methods (not preferable, as this fraction is greater).
I checked the list of policies and did not find anything applicable for my case. Moreover this link states:
Subscriptions can be associated with various scopes: product, all
APIs, or an individual API.
Is there a way I can workaround this limitation?
I mean that, maybe you wanna some of the methods(less amount) in an Api can be called without a subscription while the left need. And I searched the ms document but failed to find such policy.
The link you provided also intended that. From my point of view,
how about trying to add a separated Api containing those methods that
don't need subscription?

Using custom attributes to store additional information about a user in Azure AD B2C

I would like to store additional information about users in my Azure AD B2C instance. What I did is the following:
I've created a new custom attribute and the name of this attribute is Producer
I've added all required permissions for a new application registration which is intended to use Azure AD B2C API through Graph API
I call Graph API to set a custom attributed for one of the users: POST https://graph.microsoft.com/v1.0/users/{user-id} with the following data according to this example
{
"officeLocation": "US",
"extension_XXX_Producer": "AN"
}
When I try to query information about this user by using Graph API: GET https://graph.microsoft.com/v1.0/users/{user-id}, I do not get anything like my custom attribute
After reading Azure AD B2C documentation, it seems like custom attributes can be activated only if I add them to one of the user flows, but it is not what our business wants. They would like to have another UI and product to be responsible for custom attributed management, it is why I would like to use Graph API for custom attributes management.
Could you please recommend me how I can manage custom attributes without including them into Azure AD B2C user flows?
I also found a couple of resources where people recommend to use Azure AD Graph API, but Microsoft tells me in Azure that this API is legacy (I've checked it and it works, but I have some concerns because of Legacy API):
I looked at the document example you provided, and I noticed that the example is a demonstration with Azure Active Directory Graph, so I suggest you also try to use Azure Active Directory Graph. When you use api to query user information, it looks like this :
https://graph.windows.net/{tenant}.onmicrosoft.com/users/{user_id}?api-version = 1.6
Before that, as the document says, you need to obtain an access token for the api, and when granting permissions, you need to grant Azure Active Directory Graph permissions to the application.
For AAD Graph, it is an older API that only allows access to directory data, and some of its functions have been migrated from AAD Graph to Microsoft Graph. But in some cases, we can only achieve the requirements through AAD Graph.
please see:The difference between AAD Graph and Microsoft Graph.
What i've done:
Add a custom attribute (for example Producer) using the Azure Portal AD B2C
Add this attribute in the Application claims of the signin user flow
Use the Graph API to list the extension properties of the b2c-extensions-app. Do not modify. Used by AADB2C for storing user data. (where the custom attributes are stored, read https://learn.microsoft.com/en-us/azure/active-directory-b2c/extensions-app, https://learn.microsoft.com/en-us/graph/api/resources/extensionproperty?view=graph-rest-beta and https://learn.microsoft.com/en-us/graph/api/application-list-extensionproperty?view=graph-rest-beta&tabs=http).
client is an initialized MicrosoftGraphClient, appObjectId is the Object ID of the b2c-extensions-app:
async function getExtensionProperties(client, appObjectId) {
return await client
.api(`/applications/${appObjectId}/extensionProperties`)
.version('beta')
.get();
}
The response should contain a line like:
name: 'extension_<Application (client) ID of the b2c-extensions-app without the dashes>_Producer'
This is the name of the custom attribute as an extension property.
Use the Graph API to set your custom attribute on a user.
id is the user Object ID in AD, attributes is { "extension_<Application (client) ID of the b2c-extensions-app without the dashes>_Producer": "your_value" }
async function updateUser(client, id, attributes) {
return await client
.api(`/users/${id}`)
.version('beta')
.header("content-type", "application/json")
.patch(attributes);
}
When login using the signin user flow, in the browser, using MSAL, myMSALObj.getAccount().extension_Producer is now set to the custom attribute value (note: extension_Producer without the Application ID between extension and Producer).
This answer https://learn.microsoft.com/en-us/answers/questions/21843/how-to-set-custom-claims-for-a-user-in-azure-ad-b2.html from amanpreetsingh-msft has been a great help to solve this.

Azure group claim returns Object ID - Need group name

Have been using Azure for Single Sign On.
For group claims, during the assertion we see only the security group object ID during the response.
e4feedb1-df0e-46ff-8a02-e63474015610
Is it possible to get Group name here in response instead of groups Object ID
If (and only if) the groups in question are groups which have been synced from on-premises AD, you can configure the groups claim to include the on-premises sAMAccountName or the on-premises SID.
Note: Including the display name is not supported. (Display names are not unique, and in most organization, any user is able to create and manage their own groups, making any sort of authorization decision based on group display names a very risky proposition.)
To issue group can be done both for gallery or non-gallery (i.e. custom) SAML apps (i.e. under Enteprise apps), through the app registration in the Azure portal (App registrations > Token configuration), or directly on the app registration's Application object by updating the optionalClaims property (e.g. via the manifest editor or through Microsoft Graph).
https://learn.microsoft.com/azure/active-directory/hybrid/how-to-connect-fed-group-claims
I'm afraid that it's only supported to get the object ids currently.
You need to call Microsoft Graph to get the Group name.
If you do need this feature, upvote this post on UserVoice and it may be implemented in the future.
A similar question which is answered by Microsoft Engineer here.

docusign custom connector pricing plans and API base path doubts

I have some doubts regarding the custom connector we are trying to build for docusign : -
Regarding the license plan that need to be bought by the customers who will be granting access for our connector to collect data from their docusign organization account. I am looking at the link https://www.docusign.com/products-and-pricing. API access support is mentioned in only the advanced solution. So I was wondering whether only we need to have "Advanced solutions plan with APIs support" plan or all our customers need to API access support in order to fetch their data.
As per the documentation, to make the REST API calls we need two fields 'base_uri' and 'account_id' (https://developers.docusign.com/esign-rest-api/guides/authentication/user-info-endpoints). Now, the response of userInfo API call gives an array of accounts and its respective fields. My doubt is, if multiple authenticated users (more than one accounts) are returned in this array but all are part of same organization, will they all have different account_ids. Main concern here is, will there be several Base Paths (https://developers.docusign.com/esign-rest-api/guides/authentication/user-info-endpoints#form-your-base-path) to make API calls?
2a. Further question is, what is the significance of 'is_default' field?
Is this related to main account (if is_default is true) using which we will create our Base Path?
Since this is a tech/engineering forum I'm going to answer only question #2 as question #1 is more of a business/sales question.
The reason you may get multiple accounts is that an authenticated user in DocuSign can be a member of multiple accounts. That said, it's the same user. Meaning, say foobar#blah.com has an account 123 with company X and account 456 with his school, then it's possible that when foobar#blah.com authenticates (With the same password!) to DocuSign we have a list of accounts associated with that user. We give you all of them when you make the API call. The default one is the main one that you would see when you log into our web app. You can decide yourself as the user which one is the default. Users who log into our web-app then see an option at the top-right to change accounts.
and yes, every API call is associated with a specific account. So when you construct the urls for your API - you do need to know which account for this user you are making the API call for. Your application can decide how to handle this.
Hope this helps.

Can we Authenticate user of specific group in Active Directory

I can Authenticate user in Active directory but I need to know can we authenticate a specific user in group if we have multiple groups.
Basically I am redirecting to http://[mydirectory].onmicrosoft.com and validating the user but I need to know do we have mechanism to validate a user from specific group so that I can give access according to that.
Assuming this is Azure AD (and not on-premises Windows Server AD), then you have three options to restrict access to an application via groups.
Option 1: Require user/group assignment to application
This is the only option that does not require adding authorization logic in your application.
When configuring your application in the classic Azure portal, you can set the application to require user assignment:
Then, under "Users and Groups" for that application, you can choose which individual users or groups should have access to the application.
The most important thing to consider here is that this will only apply to direct members of the group, not to nested members.
Option 2: Request group claims
This option will allow you to request that the token returned to the application after a user has signed in contain the list of groups that the user is a member of. This includes groups that they are transitive members of (i.e. nested groups).
From your application's configuration page in the classic Azure portal, you can download and upload the app's manifest JSON file. In the manifest, locate the "groupMembershipClaims" attribute, and set it to "All" or "SecurityGroup" (the latter will exclude distribution lists).
Once this is set, after the user signs in, the resulting token will have a groups claim that contains a list of group object IDs that the user is a member of. Your application can then use these claims to decide whether or not the user should have access.
Dushyant Gill goes into group claims in detail in his blog post: http://www.dushyantgill.com/blog/2014/12/10/authorization-cloud-applications-using-ad-groups/ (archive.org link)
The important consideration here is that there is a limit to the number of groups that can be returned. If the user is a member of more groups that this limit, then an "overage" claim is issued, and your application will need to make an Azure AD Graph API call to get the full list. (This is also described in Dushyant's blog post.)
Option 3: Use the the Microsoft Graph API or the Azure AD Graph API directly
The final option is to simply call the Microsoft Graph API (or the Azure AD Graph API, they both act almost identically for this) to establish if the signed in user is a member of a given group. Your application can then make the authorization decision.
There are several approaches you can take (these are all transitive checks, so nested groups are supported):
isMemberOf to check whether a the user is a member of a specified (single) group. This is the simplest if a single group should grant access to your app.
checkMemberGroups to check if the user is a member of any groups in a list of groups. This is useful if different groups grant different roles or permissions in your application.
getMemberGroups to return the full list of groups the user is a member of. This is generally not particularly useful for doing authorization checks.

Resources