Deep Diver – Azure AD Groups/Roles claims for developers and IT pro’s with code examples


Many enterprise applications rely on group /role information to be passed on assertions for authorization, and further role decisions. Last three to five years these applications have been moving to the cloud, or at least seeing parts of their authorization middle-wares upgraded to support SAML, or OAuth2, or both. Judging by how rich the group claim options are in Azure AD I’d say Microsoft is investing heavily into making configuration options cover all imaginable scenarios

Short version of this blog is:

Prefer SAML when:

  • Application relies on getting user and groups information including transformed claims from the IDP in the initial token response.
  • Application doesn’t need further information from other Azure AD API’s to be acquired by background flows using token delegation
  • You want to transform claims both for user and group information in the GUI
  • You want do as much as possible configuration and maintanence in the GUI

Prefer OAuth2 when

  • Application has multiple Azure AD API’s called using token delegation, or redirect based flows after initial authentication
  • Application needs combine information from Azure AD API’s beyond of that which is held in user attributes and groups
  • While Claims Transformations arent supported in the token itself, you can basically do whatever you need to combine information once you have the initial token.
  • Application needs multiple and complex group claim rules and you can do these in the back-end (Azure AD allows only adding single ’add group claims’ rule in SAML app) – Note that even in OAuth2 this applies, but in OAuth2 you do this after receiving the initial token

Mix it together

  • In complex scenarios you might need to decide on combining a mix of these approaches, or decide to lean heavily towards OAuth2. As I am mostly working from dev perspective I tend to prefer OAuth2 with or without OIDC, but in this blog I highlight benefits for both approaches
    • ”For applications that do interactive browser-based sign-in to get a SAML assertion and then want to add access to an OAuth protected API (such as Microsoft Graph), you can make an OAuth request to get an access token for the API. When the browser is redirected to Azure AD to authenticate the user, the browser will pick up the session from the SAML sign-in and the user doesn’t need to enter their credentials.” /

Useful information before proceeding

I’ve written few articles about Application Proxy If your applications remain on-premises but you need to modernize their access approach to Zero Trust

Eating the elephant

Since the scenarios where groups and roles are so many, I’ve tried to distill it into an table to help with possible evaluations, and provided some examples and considerations to back these scenarios.

Note that in Azure AD Group is not explicitly same as Role. But these two can be mixed in various rules together.

Decision criteria table

Send as claimsSAMLOAuth2
send roles 
send only groups that are assigned to the application ✔ (Send either the role or the group possible)✔ (Send either the role or the group possible)
send groups ✔(Via Group Claims in SSO settings of the enterprise application or Token configuration)✔ (Via ”Token Configuration OAuth2 Apps”)
Transform group/role attributes dynamically✔ (some limitations apply, but flexible nonetheless)See Query Graph API if when send as claims not possible
group size exceededSee Query Graph API if when send as claims not possible
or limit groups to those assigned to the application (preferred when full group information is not needed)
See Query Graph API if when send as claims not possible

Excerpt of configuration options presented in the table

send only groups that are assigned to the application (Via token configuration in App Registrations)

  • App Registrations Token Configuration includes three type of token configurations for the group claims option
  • Note the limitation only single group claims rule is available

send only groups that are assigned to the application (Via SSO settings in enterprise applications)

  • For SAML apps this approach is preferable when you also need to change the name of the claim
  • Note the limitation only single group claims rule is available

Query Graph API when send as claims is not possible

Querying Graph API is useful approach when you want/need information which is not available in the token response

Flows available for further queries

Delegate the token received in response using bearer flow Only works for SAML 1.0 tokens Rather use OAuth2 redirect based flowJWT Bearer flow available
Redirect user for OAuth2 Authorization Request *✔ (SAML app needs to support OAuth2 to in this approach as well)
  • ”For applications that do interactive browser-based sign-in to get a SAML assertion and then want to add access to an OAuth protected API (such as Microsoft Graph), you can make an OAuth request to get an access token for the API. When the browser is redirected to Azure AD to authenticate the user, the browser will pick up the session from the SAML sign-in and the user doesn’t need to enter their credentials.” /
  • For SAML and JWT tokens which exceed group size limit you get Graph API link instead of the groups
  • Azure Active Directory limits the number of groups it will emit in a token to 150 for SAML assertions, and 200 for JWT. If a user is a member of a larger number of groups, the groups are omitted and a link to the Graph endpoint to obtain group information is included instead.
  • In this approach you need to add additional permissions for the application if you want to get the group names besides group id’s.
    • If you emit groups in the claims of the token you get with the built-in scope to graph the needed information

SAML / OAuth2 group information examples

In attempt to keep this blog even remotely readable I’ve included examples of the two main approaches, as all other examples are more or less derivatives/mixes of those two


  • deliver most if not all information in the token response


  • fetch information after receiving the initial token via separate http request to MS Graph API

Emit Groups in the token (works for both SAML and OAuth2)

Configuration for the examples below

  • Note, here is alot to play with for different group configurations

Response example JWT token (Access Token):

Though avoidable, some times you end up getting group IDs only. If you prefer this way, and don’t need human readable name to be exposed in token this may work too. If you want name of the group, you need to use graph API

Response example SAML token

Response example for exceeded group amount

Get groups of the user after token response – OAuth2 (And SAML APPS that support OAuth2)

  • This scenario could be needed if filtering is required that is not available in claims customization, or the group size exceed token limits

Using OAuth2 JWT Bearer Flow

  • I’ve written about JWT bearer grant earlier here Concept: Publish on-prem API using AAD App Proxy and API Management with Azure AD JWT Bearer Grant
  • Note that this can be also achieved with:
    • Getting new access token with interactive user redirect flow
    • using refresh token flow (if initial scope allows storing refresh tokens)
    • SAML Bearer flow (This works with only SAML 1.1 tokens, so I am not recommending it, unless its token gotten from WSfederation protocol)
  • The JWT token is stored either in back-end token store, or in user cookies (In the example is in the req.cookies.token)

Response example

Note! you can clean up the contents of graph response, if needed. This is just example 🙂

Sample code for JWT-Bearer Grant

//Bearer Grant (depedencies request etc)

var getJwtBearerAssertion = ({client_id,redirect_uri,resource,assertion,client_secret},callback) => {
    var options = {
      form: {
      }"",options, (error,response) => {
        if (!response.body.access_token) { return callback(undefined,response.body)}
        callback(response.body.access_token, undefined)

// New code from here /Different JS file
var options = {
   getJwtBearerAssertion(options, (result,error) =>  {
                if (error) {return res.send(error)}
                apiCall(result,"", (result) => {
                      var data =   result.value.filter((group) => {
                          console.log('group iterated')
//Iterate groups into Cookies
                         if (group.displayName) {res.cookie(`groupID:${}`,group.displayName,CookieOpts)}
                        return != undefined

Other stuff: SAML parser in NodeJS

Following parsing code is used as expressJS middleware, to implement demonstrational SAML parsing functionality without verifying the SAML token itself. This is useful when you want to inspect assertions in the back-end test that information on functions you might be working. Such as updating back-end database stored information based on the information of such assertion

SAML parser Middle-ware function for expressJS

var xmlparser = require('fast-xml-parser');
const util = require('util')

function samlParser () {

    return function (req,res,next) {
        if (req.body.SAMLResponse) {
            console.log('SAML response')
            let bbuffer = Buffer.from(req.body.SAMLResponse, 'base64')
            var xmlstring = bbuffer.toString('utf-8')

            if (xmlparser.validate(xmlstring)) {
                var options = {
            var xmlpayload = xmlparser.parse(xmlstring,options)
            var detailed = util.inspect(xmlpayload,true,7,true)


            return next()


console.log('using SAML parser')


Security aspects

Using app permissions in place of delegated permissions?

This is generally not recommended practice (at least in my opinion) because

Using app permissions for substituting flows that are originally suited to use user delegation is not good idea, because it decouples user authorization and further requests to other API’s from the user context.

With delegated permissions 

  • With delegation existing access rights of the user is used to get further information. The process delegating the token cannot exceed permissions of the user with the token
  • More coherent log trail is produced as user context is shown which the app accessed API’s on behalf of the user

When instead app permissions are used

  • Log trail is problematic. The action which was destined towards user API’s doesn’t show user context rather only the application acting towards the API
  • Elevation of privilege risks enter the picture, as the app permissions might exceed by far margin the permissions of the user
  • incomplete or no user consent even when the app does actions on behalf of user without delegation. 

Attacker figuring out a client side input parameters intended for back-end queries

  • In ”SAML approach” all of the delivered attributes are verified by signature verification, this applies to OAuth2 tokens too, but in OAuth2 approach you need to query often information after receiving the token for further information
    • Since the token JWT token might not have needed information, hypothetically you could have bad application code running ”curl –insecure-” against what it expects to be Graph API” – but is instead being tricked to read an attacker controlled version of the endpoint. Attacker could use an limited Remote Code Injection approach, or figure out that some client side information is used in the back end with no integrity check, or has serious issues in with its input validation
      • example function running in the back-end expects that the array from client side function always produces single item array. The validation function assumes that the content is thus always stored in the index[0]. But the function processes all items in the array if the first index item is validated
  • The obvious counter argument here is that if application is running insecure curl requests and such bad coding practices 🙂 how can you be sure, that its not being tricked to use the wrong token sign-in key? or have more serious security issues. In especially older apps, the public verification key is stored in the application itself With Azure AD this is not recommended, querying the JWKS uri needs to happen always from the metadata because those public keys can rollover (Read ”Signing key rollover in Azure Active Directory”)
    • There is no plausible production scenario where you wouldn’t be verifying signatures of the either token types (SAML / JWT)

Where from here?

The current blog highlights technical decision criteria’s and examples of code sample and response outputs. For solving a particular group based scenarios don’t hesitate to ask me in twitter or LI for further additions into this blog

Microsoft references

Add sAMAccountName to Azure AD Access Token (JWT) with Claims Mapping Policy (and avoiding AADSTS50146)

With the possibilities available (and quite many of blogs) regarding the subject, I cant blame anyone for wondering whats the right way to do this. At least I can present one way that worked for me

Here are the total ways to do it (1. obviously not the JWT token)

  1. With SAML federations you have full claims selection in GUI
  2. Populate optional claims to the API in app registration manifest, given you’ve updated the schema for the particular app
  3. Create custom Claims Policy, to choose emitted claims (The option we’re exploring here)
  4. Query the directory extension claims from Microsoft Graph API appended in to the directory schema extension app* that Graph API can call

Please note, for sAMAccountName we’re not using the approach where we add directory extensions to Graph API queryable application = NO DIRECTORY EXTENSION SYNC IN AAD CONNECT NEEDED

Checklist for using Claims Mapping Policy

Pre: Have Client application, and web API ready before proceeding

#Example App to Add the Claims 
$Definition = [ordered]@{
    "ClaimsMappingPolicy" = [ordered]@{
        "Version" = 1
        "IncludeBasicClaimSet" = $true
        "ClaimsSchema" = @(
                "Source" = "user"
                "ID" = "onpremisessamaccountname"
                "JwtClaimType" = "onpremisessamaccountname"
$pol =  New-AzureADPolicy -Definition ($definition | ConvertTo-Json -Depth 3) -DisplayName ("Policy_" + ([System.Guid]::NewGuid().guid) + "_" + $template.Values.claimsschema.JwtClaimType) -Type "ClaimsMappingPolicy" 
$entApp =  New-AzureADApplication -DisplayName  ("DemoApp_" + $template.Values.claimsschema.JwtClaimType)
$spnob =  New-AzureADServicePrincipal -DisplayName $entApp.DisplayName -AppId $entApp.AppId 
Add-AzureADServicePrincipalPolicy -Id $spnob.ObjectId -RefObjectId $pol.Id 
#From the GUI change the Identifier and acceptMappedClaims value (From the legacy experience)

  • Generally: The app that will emit the claims is not the one you use as the clientID (Client subscribing to the Audience)
    • Essentially you should create un-trusted client with clientID, and then add under Api permissions the audience/resource you’re using
  • Ensure that SPN has IdentifierURI that matches registered custom domain in the tenant
    • The reasoning is vaguely explained here & here
      • Whatever research work the feedback senders did, it sure looked in depth 🙂
  • Update the app manifest to Accept Mapped Claims
    • (Works now in the new experience too) Do this in the legacy experience, the new experience at least in my tenant didn’t support updating this particular value
”Insufficient privileges to complete the operation”

if mapped claims are not accepted in manifest, and pre-requisites are not satisfied you might get this error

”AADSTS50146: This application is required to be configured with an application-specific signing key. It is either not configured with one, or the key has expired or is not yet valid. Please contact the application’s administrator.”

  • Below is example for the Manifest changes (AcceptMappedClaims, and verified domain matching URI)
     "id": "901e4433-88a9-4f76-84ca-ddb4ceac8703",
    "acceptMappedClaims": true,
    "accessTokenAcceptedVersion": null,
    "addIns": [],
    "allowPublicClient": null,
    "appId": "9bcda514-7e6a-4702-9a0a-735dfdf248fd",
    "appRoles": [],
    "oauth2AllowUrlPathMatching": false,
    "createdDateTime": "2019-06-05T17:37:58Z",
    "groupMembershipClaims": null,
    "identifierUris": [


If you’re planning to use non-verified domain based identifier

”AADSTS501461: AcceptMappedClaims is only supported for a token audience matching the application GUID or an audience within the tenant’s verified domains.


Decode JWT access and id tokens via PowerShell