Kalyan Krishna from Microsoft hosted a community call on implementing authorization in applications using features of the Microsoft Identity Platform like app roles, security groups, scopes, and directory roles. The call covered:
- Defining and assigning app roles to users and other apps to control permissions.
- Using security groups assigned to users to manage access and optionally returning group details in tokens.
- Configuring application groups to filter tokens to only include groups relevant to an application.
- Providing scopes or delegated permissions for public client applications to request access to resources.
- Directories roles for administering access in Azure AD tenants.
Implement Authorization in your Apps with Microsoft identity platform-June 2020
1. Microsoft identity platform
June 18, 2020 | 9:00AM PST
Community call
Implement Authorization in your
Applications using App Roles, Security
Groups, Scopes and Directory Roles
(2020 edition)
Kalyan Krishna
Microsoft
2. Introduction
• First things first
• Please note: We are recording this call so those unable to attend can benefit from the recording.
• This call is designed for developers who implement or are interested in implementing Microsoft identity platform
solutions.
• What kind of topics will we discuss?
• We will address development related topics submitted to us by the community for discussion.
• We build a pipeline of topics for the next few weeks, please submit your feedback and topic suggestions -
https://aka.ms/IDDevCommunityCallSurvey
• View recordings on the Microsoft 365 Developer YouTube channel - https://aka.ms/M365DevYouTube
• Follow us on Twitter @Microsoft365Dev and @azuread
• This is NOT a support channel. Please use Stack Overflow to ask your immediate support related questions.
• When is the next session?
• Community Calls: Monthly – 3rd Thursday of every month
• Next Identity Developer Community Call: Jul 16th
4. Aboutthissession
Objectives
• Introduction to Authorization with Microsoft Identity Platform.
• Discuss various available features in detail.
Features
• App roles
• Groups
• Scopes
• Directory Roles
5. Prerequisites
• You are familiar with integrating apps with Azure Active Directory
• You have integrated web apps and secured web APIs with the Identity Platform
• You have a working understanding of the Permissions and Consent framework
• Only covers modern apps
7. AuthorizationintheMicrosoftIdentityplatform
• Authentication is the process of proving you are who you say you are. Authentication is sometimes shortened
to AuthN
• Authorization is the act of granting an authenticated party permission to do something. It specifies what data
and functionality you're allowed to access and what you can do with that data. Authorization is sometimes
shortened to AuthZ.
https://docs.microsoft.com/azure/active-directory/develop/authentication-vs-authorization
8. AuthorizationintheMicrosoftIdentityPlatform
The following built-in features are available to developers
• App Roles
• App roles assigned to users
• App roles assigned to apps, aka “Application Permissions”
• Security Groups
• Getting groups in tokens
• Nested group memberships
• Application Groups, aka Groups assigned to an application
• Groups Overage
• Scopes, aka “Delegated Permissions”
• Directory Roles
11. App
Roles
• Application roles are used to assign permissions to users and apps.
• They are specific to an application. Thus removing an app from AAD
will make these roles go away.
• They are provided to an app in the roles claim.
12. How it works
• Define app roles in an application’s manifest.
• Assign roles to users and security groups or apps
• Receive assigned roles in the user’s or app’s token
in the roles claim
14. App Roles for Users
• Define app roles that will be assigned to users in a tenant
• Developers write code for role permissions in their app
• The user assignment is usually done by members of the IT team than developers themselves.
• Will only be present in tokens if a user signs in
• Arguably the most popular mechanism for roles based AuthZ today
How to: Add app roles in your application and receive them in the token
23. Id_token with
groups and
roles
Roles in a
token will
be
provided
in the
“roles”
claim
{
"aud": "300e33f5-e62e-4581-acd2-542ece0965cc",
"iss": "htps://login.microsoftonline.com/536279f6-15cc-45f2-be2d-61e352b51eef/v2.0",
"iat": 1563969244,
"nbf": 1563969244,
"exp": 1563973144,
"aio": "AeQAG/8MAAAAYPOQy4ROQXwGbt+LpH37Q8I=",
"groups": [
"MSDemoUsers"
],
"name": "Kalyan Krishna",
"nonce": "6369956633167913NDUwODI0",
"oid": "98d51ac8-a756-43ef-876f-e7e64c89b323",
"preferred_username": "kkrishna@contosoorg.net",
"roles": [
"DirectoryViewers"
],
"sub": "bGcfwO94xuVM7Dv-O62Bb76ZlB9RzHa0R-48jtQgKgg",
"tid": "536279f6-15cc-45f2-be2d-61e352b51eef",
"uti": "WQBn7mDb2UygvE7fPrIfAA",
"ver": "2.0"
}
App roles for users
24. App roles Asp.net middleware configuration
// In Startup.Auth.cs
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
RoleClaimType = "roles",
},
// In Controllers and elsewhere
[Authorize(Roles = “DirectoryViewers, Subscriber, Writer, Approver")]
public ActionResult Index()
or
User.IsInRole("DirectoryViewers");
25. Asp.net core middleware configuration
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Other code
// By default, the claims mapping will map claim names in the old format to accommodate older SAML application.
// 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles’
// This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
// The claim in the Jwt token where App roles are available.
options.TokenValidationParameters.RoleClaimType = "roles";
});
// In code..(Controllers & elsewhere)
[Authorize(Roles = “DirectoryViewers")]
or
User.IsInRole("DirectoryViewers");
26. App Roles for Users
• Using App roles limits the amount of information that needs to go into the token, is more secure, and
separates user assignment from app configuration.
• There is no explicit limit to number of app roles that can be declared for an app registration. The limit is
imposed by the total number of entries of all the collections in the manifest, which is combined at 1200.
• Their memberships are managed by app owners or users in the app admin roles.
• When assigning groups to Approles, note that, nested group memberships are not supported (yet).
• Use Microsoft Graph’s appRoleAssignment API to programmatically manage role memberships
27. App Roles for Users
• Enable “User assignment required” to make it functional or users not assigned to roles can still sign-in to your
app.
• Assigning groups to Approles is not available in Azure AD free edition
• Documentation - Add app roles in your application and receive them in the token
• Documentation - Assign a user or group to an enterprise app in Azure Active Directory
• Documentation - Delegate app registration permissions in Azure Active Directory
• Recommended Sample - Add authorization using app roles & roles claims to an ASP.NET Core web app
30. App Roles for apps
• Define app roles that will be assigned to apps in a tenant.
• Integrated with the consent framework. Popularly known as “Application Permissions”.
• The assignment can only be done via admin consent.
• Allows apps that do not sign-in user (daemons) authenticate themselves and obtain tokens for a protected
resource (web API)
How to: Add app roles in your application and receive them in the token
36. Request for role in your code
// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator
string[] scopes = new string[] { "https://kkaad.onmicrosoft.com/webapi/.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
Console.WriteLine("Token acquired n");
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be of the form "https://resourceurl/.default"
// Mitigation: change the scope to be as expected
Console.WriteLine("Scope provided is not supported");
}
38. Verify and use roles in your code
// GET: api/todolist
[HttpGet]
[Authorize(Roles = "access_as_application")]
public IActionResult Get()
{
return Ok(TodoStore.Values);
}
39. App Roles for Apps
• Use app roles to let apps request granular permissions to your resource. Study and learn from Microsoft
Graph
• The roles will only be granted once administrator consents.
• Scenario - Protected web API
• Documentation - Add app roles in your application and receive them in the token
• Recommended Sample - A .NET Core daemon console application using Microsoft identity platform
40.
41.
42. Security
Groups
• A Security Group is a collection of users assigned to the
group. Rights are assigned to them.
• These groups can be cloud-only or sync’d from on-
premise.
• Not tied to an app, security groups can be used in
multiple apps and for other access control purposes.
43. How it
works
• Users are assigned to security groups by tenant admins
or IT staff (usually).
• Developers code for a group’s permissions in their app.
• Enable group claims for your app in the App
registration portal.
• Use these group ids or names provided in the token in
your code to lookup assignments.
44. Changes to app registration
• None
• Securitygroups
• Including nested groups !
• Directoryroles
• AllGroups
• Security Groups
• Distribution Lists
• Directory roles
• Groupsassignedtotheapplication
• You choose the groups you want !
46. Let’s get group names instead
Bydefault,GroupIdswillbeemittedinthe
groupclaimvalue.
Validoptionsare:
"sam_account_name",
“dns_domain_and_sam_account_name”,
“netbios_domain_and_sam_account_name”,
"emit_as_roles"
Worksforon-premgroupsonly
Configure group claims for applications with Azure Active Directory
53. Groupsclaims
• Different features for cloud-only and on-prem groups
• Supports nested groups. Group claims in tokens include nested groups except when using the option to restrict
the group claims to groups assigned to the application (Application Groups)
• Groups and their memberships can be managed by the group owner and several Azure AD admin roles, and
the lifecycle is not controlled by the app.
• If the option to emit group data as roles is used, only groups will appear in the role claim. Any Application
Roles the user is assigned will not appear in the role claim
62. Groups assigned to application
• Just work with groups your application cares about. Application(s) get a filtered list of groups in tokens
• Needs Azure AD Premium P1
• Avoid token overage scenarios
• Set “User assignment required?” flag to true for best results as this allows users assigned to your
ApplicationGroups are the only ones signing-in to your app
• Does not support nested groups (yet)
76. Groups
overage
claim
• To ensure that the token size doesn’t exceed HTTP
header size limits, Azure AD limits the number of Ids
that it includes in the groups claim.
• If a user is member of more groups than the overage
limit (150 for SAML tokens, 200 for JWT tokens), then
Azure AD does not emit the groups claim in the
token.
• Instead, it includes an overage claim in the token that
indicates to the application to query the Graph API to
retrieve the user’s group membership.
77. Token with
overage
Emitted when a user is
member of more groups
than the overage limit
200 for JWT tokens
150 for SAML tokens
6 for Implicit Flow
{
"aud": "19a7ff3f-24fd-40ba-884b-f00e00179fdf",
"iss": "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0",
"iat": 1563966830,
"nbf": 1563966830,
"exp": 1563970730,
"_claim_names": {
"groups": "src1"
},
"_claim_sources": {
"src1": {
"endpoint": "https://graph.windows.net/72f988bf-86f1-41af-91ab-
2d7cd011db47/users/32fe213d-e4d1-4973-96f9-1901ec32a16c/getMemberObjects"
}
},
"aio": "AWQAm/8MAAAG29wflVSWrAYPL8T",
"name": "Kalyan Krishna",
"oid": "32fe213d-e4d1-4973-96f9-1901ec32a16c",
"preferred_username": "kkrishna@microsoft.com",
"sub": "mPkIo6qb0M8qYT5ULpqXJscrKhWkz-FecFsRA4NeH8w",
"tid": "72f988bf-86f1-41af-91ab-2d7cd011db47",
"uti": "38iX3BfTa0S3IOKfdLoJAA",
"ver": "2.0"
}
78. Groups
overage
claim-
Implicit flow
• The overage indication and limits are different than
the apps using other flows.
• A claim named hasgroups with a value of true will be
present in the token instead of the overage
(_claim_names) claim .
• The maximum number of groups provided in the
groups claim is limited to 6 (six). This is done to
prevent the URI fragment beyond the URL length
limits.
79. Steps to process
groups claim
• Check for the claim _claim_names with one of
the values being groups. This indicates
overage.
• If found, make a call to the endpoint specified in
_claim_sources to fetch user’s groups.
• This requires an access token for Graph with
the User.Read and GroupMember.Read.All
permissions to call getMemberObjects Api
• If none found, look into the groups claim for
user’s groups.
80. Groupsoverage
• Consider using Application Roles to provide a layer of indirection between the group membership and the
application. The application then makes internal authorization decisions based on role clams in the token.
• Handing overage scenarios builds dependency on MS Graph, which requires additional effort on part of the
developer
82. Scopes
• Scope is a mechanism in OAuth 2.0 to limit an application's access to a user's account.
• An application can request one or more scopes, this information is then presented to the user in the consent
screen, and the access token issued to the application will be limited to the scopes granted.
• Resources, like Microsoft Graph (https://graph.microsoft.com) are good examples that extensively use scopes
• In Microsoft Identity Platform terminology Scopes are popularly referred to as “Delegated Permissions”
• Apps need to expose at least one scope to be able to sign-in users
https://oauth.net/2/scope/
87. Request for scope in your code
// Get an access token to call the ToDo service.
AuthenticationResult result = null;
try
{
result = await _app.AcquireTokenSilent(new string[] {"https://kkmsftad.onmicrosoft.com/mywebapi/access_as_user" },
accounts.FirstOrDefault())
.ExecuteAsync()
.ConfigureAwait(false);
}
// There is no access token in the cache, so prompt the user to sign-in.
catch (MsalUiRequiredException)
{
result = await _app.AcquireTokenInteractive(new string[] {"https://kkmsftad.onmicrosoft.com/mywebapi/access_as_user" })
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync()
.ConfigureAwait(false);
}
catch (MsalException ex)
{
// An unexpected error occurred.
MessageBox.Show(ex.Message);
return;
}
89. Granted
scopes are
provided in
the ‘scp’
claim
{
"aud": "5ce15bc4-cfa5-4651-b8c9-59577b783125", // App id of your Api
"iss": "https://login.microsoftonline.com/4d39e0b-7068ddd47949/v2.0",
"azp": "30f6f7b2-5e76-4d9e-a0b1-ad10f8c6f41f",
"name": "Administrator",
"oid": "e15070b1-c07e-4f29-9f06-4da797e9477b",
"preferred_username": "administrator@kkmsftad.onmicrosoft.com",
"scp": "access_as_user",
"sub": "fn-EljUpW9zhzb3zM_1K576_7FJzVJnxPv4V1zVbkqE",
"tid": "4d39e77c-b0f3-4253-ae0b-7068ddd47949",
"ver": "2.0"
}
90. Verify in your code
/// <summary>
/// The Web API will only accept tokens 1) for users, and
/// 2) having the access_as_user scope for this API
/// </summary>
static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };
// GET: api/values
[HttpGet]
public IEnumerable<TodoItem> Get()
{
HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
string owner = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
return TodoStore.Where(t => t.Owner == owner).ToList();
}
91. Scopes
Scope requesting pattern. The following pattern is expected of apps when requesting scopes from Azure AD
• Scope = “[App ID URI]/[Scope1] [App ID URI]/[Scope2]” (separated by space)
• Scope = “[App ID URI]/.default]” (requires scopes declared upfront)
• For an App ID URI -> https://contoso.onmicrosoft.com/myWebAPI
• Scope = “https://contoso.onmicrosoft.com/myWebAPI/Scope1 https://contoso.onmicrosoft.com/myWebAPI/Scope2”
• Scope = “https://contoso.onmicrosoft.com/myWebAPI/.default” (requires scopes declared upfront)
When an App Id URI is not provided, https://graph.microsoft.com is automatically assumed.
For example
Scope = “User.Read Directory.Read.All”
is translated to
Scope = “https://graph.microsoft.com/User.Read https://graph.microsoft.com/Directory.Read.All”
Scopes and permissions in the Microsoft Identity Platform
92. Scopes
• Scopes (“Delegated Permissions”) are only used in scenarios when a user signs in. For applications, use App
roles
• Use scopes to let apps request granular permissions to your resource. Study and learn from Microsoft Graph
• Scopes can be consented by both users and tenant admins
• Documentation - Permissions and consent in the Microsoft identity platform endpoint
• Scenario walkthrough - Protected web API
• Recommended Sample - Calling an ASP.NET Core Web API from a WPF application
98. Use Graph to resolve the role id
https://docs.microsoft.com/en-us/graph/api/directoryroletemplate-get
99. Directory Roles
• Useful for apps that wish to drive authorization using Azure AD’s roles
• Only works for built-in roles (tenant scoped).
• Only available for authentication flows that sign in users.
• Documentation - Assign administrator and non-administrator roles to users with Azure Active Directory
100.
101. More
references
Microsoft identity platform’s permissions and consent framework
How to protect APIs using the Microsoft identity platform
Azure Active Directory app manifest
Azure AD Connect sync: Understanding Users, Groups, and Contacts
Azure Active Directory pricing
Configure Microsoft 365 Groups with on-premises Exchange hybrid
103. Join the Developer Program
Benefits
Free renewable Office 365 E5 subscription
Be your own admin
Dev sandbox creation tools
Preload sample users and data for Microsoft Graph, and more
Access to Microsoft 365 experts
Join bootcamps and monthly community calls
Tools, training and documentation
Learn, discover and explore about Office 365 development
Blogs, newsletters and social
Stay up to date with the community
https://aka.ms/o365devprogram
104. Resources
Stack Overflow Support
@AzureAD, @msiddev
developer.microsoft.com/identity/blogs/
Azure Active Directory Microsoft Identity Platform Microsoft Graph
Quick Starts Graph Explorer MSAL Libraries
UserVoice MSAL Survey
github.com/AzureAD
aka.ms/MsIdStackOverflow
azure.microsoft.com/services/active-directory
aka.ms/AzureADAppGallery
105. Microsoft Confidential
Engage with us!
Topic Feedback type Forum URL Who supports
All identity developer topics
(Auth libraries, MS Graph, App
Registration portals)
Community-driven
developer Support for
Questions and Answers
Stack Overflow
https://stackoverflow.com/questions/tagged/azure-
active-directory+or+microsoft-graph+or+azure-ad-
conditional-access
Supported by Microsoft and community
Authentication Libraries –
ADAL, MSAL, Auth Middleware
Library issues, bugs, open
source contributions
GitHub
https://docs.microsoft.com/azure/active-
directory/develop/active-directory-authentication-
libraries
Azure AD teams manage issues, bugs
and review/ approve contribution
Azure AD, MS Graph, Libraries,
App Registration – Developer
Experiences
Feature requests,
suggestions for product
improvements
Azure Feedback
Azure Feedback for Authentication and also
AppRegFeedback@microsoft.com for portal specific
feedback. User Voice for Microsoft Graph
Azure AD teams triage feature requests
All identity developer topics
(Auth libraries, MS Graph, App
Registration portals)
Discussion with other MVPs
and NDA community
Yammer Identity
Developer Advisors
https://www.yammer.com/cepartners/#/threads/in
Group?type=in_group&feedId=13045972992&view=
all
Engagement with Identity Advisors and
Microsoft product groups
Identity developer topics for
Auth
Delve deep into complex
identity related
development topics live Community Office Hours
Msiddev Twitter handle and the
Microsoft developer portal
Opportunity to make questions and
answers in real time to product teams
via live conference
All developer topics Assisted support for
developers
Customer Service and
Support
More information on support options:
https://aka.ms/devexhelpsupport
Direct 1:1 help from our support
engineering teams
106. Recording will be available soon on our
Microsoft 365 Developer YouTube channel
https://aka.ms/M365DevYouTube
(subscribe today)
Follow us on Twitter
@Microsoft365Dev and @azuread
Next call: Jun 18th at 9:00am PST
https://aka.ms/IDDevCommunityCalendar
Thank you
Notes de l'éditeur
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"description": "User readers can read basic profiles of all users in the directory",
"displayName": "UserReaders",
"id": "a816142a-2e8e-46c4-9997-f984faccb625",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "UserReaders"
},
{
"allowedMemberTypes": [
"User"
],
"description": "Directory viewers can view objects in the whole directory.",
"displayName": "DirectoryViewers",
"id": "72ff9f52-8011-49e0-a4f4-cc1bb26206fa",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "DirectoryViewers"
}
],
Go to Azure portal and add roles to the app
Assign both users and groups to roles
Run fiddler and show groups and roles claims in token.
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/blob/master/5-WebApp-AuthZ/5-1-Roles/README.md
Great benefits of app roles
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
So how do you get security groups to work for you?
Go to Azure portal and create a few groups, including “Alice’s team”. Assign users to security groups.
Create your web app and enable Security groups in claims.
Run fiddler and show groups claims in token.
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/blob/master/5-WebApp-AuthZ/5-2-Groups/README.md