Azure AD B2C-角色管理 [英] Azure AD B2C - Role management
问题描述
我有一个与Azure AD B2C连接的Asp.NET MVC应用程序.
I have an Asp.NET MVC Application connected with Azure AD B2C.
在管理员设置中,我创建了一个管理员组:
In the Administrator settings I've created an Administrators Group:
在我的代码中,我想使用[Authorize(Roles = "Administrator")]
In my code I would like to use [Authorize(Roles = "Administrator")]
使用常规的Azure Active Directory,添加起来很容易(只需3行代码).但是对于Azure AD B2C,我无法在网络上找到任何有效的教程或示例.也许你可以告诉我我需要修改什么.
With regular Azure Active Directory it was easy to add (just 3 lines of code). But for the Azure AD B2C I cannot find any tutorial or example in the web which is working. Maybe you can tell me what i need to modify.
这是我的Startup.Auth.cs的ConfigureAuth方法
Here is the ConfigureAuth method of my Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Generate the metadata address using the tenant and policy information
MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = ClientId,
RedirectUri = RedirectUri,
PostLogoutRedirectUri = RedirectUri,
// Specify the callbacks for each type of notifications
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed,
},
// Specify the claims to validate
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
// Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
Scope = $"openid profile offline_access {ReadTasksScope} {WriteTasksScope}"
}
);
}
推荐答案
Azure AD B2C尚未在发送给应用程序的令牌中包含组声明,因此您不能采用相同的方法如您使用Azure AD概述的那样(该令牌中确实包含组声明).
Azure AD B2C does not yet include Group claims in the token it sends to the application thus you can't follow the same approach as you outlined with Azure AD (which does include group claims in the token).
您可以通过在Azure AD B2C反馈论坛中对该功能进行投票来支持该功能:使用Azure AD B2C获得声明中的用户成员资格组
You can support this feature ask by voting for it in the Azure AD B2C feedback forum: Get user membership groups in the claims with Azure AD B2C
话虽这么说,您可以在此应用程序中做一些额外的工作,以使其手动检索组声明中的这些声明并将其注入令牌中.
首先,注册一个单独的应用程序,该应用程序将调用Microsoft Graph来检索组声明.
- 转到 https://apps.dev.microsoft.com
- 创建具有应用程序权限的应用程序: Directory.Read.All .
- 通过点击生成新密码 来添加应用程序密码
- 添加平台并选择Web并为其提供任何重定向URI(例如
https://yourtenant.onmicrosoft.com/groups
) - 通过导航至
https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI
同意此应用程序
- Go to https://apps.dev.microsoft.com
- Create an app with Application Permissions : Directory.Read.All.
- Add an application secret by clicking on Generate new password
- Add a Platform and select Web and give it any redirect URI, (e.g.
https://yourtenant.onmicrosoft.com/groups
) - Consent to this application by navigating to:
https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI
然后,您将需要在OnAuthorizationCodeReceived
处理程序内的以下代码中添加代码,
Then, you'll need to add code the following code inside of the OnAuthorizationCodeReceived
handler, right after redeeming the code:
var authority = $"https://login.microsoftonline.com/{Tenant}";
var graphCca = new ConfidentialClientApplication(GraphClientId, authority, GraphRedirectUri, new ClientCredential(GraphClientSecret), userTokenCache, null);
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
try
{
AuthenticationResult authenticationResult = await graphCca.AcquireTokenForClientAsync(scopes);
string token = authenticationResult.AccessToken;
using (var client = new HttpClient())
{
string requestUrl = $"https://graph.microsoft.com/v1.0/users/{signedInUserID}/memberOf?$select=displayName";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(responseString);
foreach (var group in json["value"])
notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, group["displayName"].ToString(), System.Security.Claims.ClaimValueTypes.String, "Graph"));
//TODO: Handle paging.
// https://developer.microsoft.com/en-us/graph/docs/concepts/paging
// If the user is a member of more than 100 groups,
// you'll need to retrieve the next page of results.
}
} catch (Exception ex)
{
//TODO: Handle
throw;
}
这篇关于Azure AD B2C-角色管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!