2017-08-25 195 views
5

我有一个与Azure AD B2C连接的Asp.NET MVC应用程序。Azure AD B2C - 角色管理

在管理员设置我创建一个Administrators组:

enter image description here

在我的代码我想用[Authorize(Roles = "Administrator")]

通过定期Azure中的Active Directory很容易添加(只3行代码)。但对于Azure AD B2C,我无法在正在工作的网络中找到任何教程或示例。也许你可以告诉我我需要修改什么。

这里是我的Startup.Auth.cs的ConfigureAuth方法

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}" 
     } 
    ); 
} 

回答

5

Azure的AD B2C还不包括在其发送给这样你就不能按照同一应用程序的令牌集团索赔就像您使用Azure AD(其中包含令牌中的组声明)所概述的那样。

可以支持此功能通过在Azure的AD B2C反馈论坛表决问:Get user membership groups in the claims with Azure AD B2C

话虽这么说,你可以在这个应用一些额外的工作有它手动检索这些索赔的组索赔并将其注入令牌

首先,注册一个单独的应用程序,该应用程序将调用Microsoft Graph以检索组声明

  1. 转到https://apps.dev.microsoft.com
  2. 创建应用程序的权限的应用程序:Directory.Read.All
  3. 通过点击添加应用程序的秘密生成新密码
  4. 添加一个平台,选择网络,并给它重新导向URI(例如https://yourtenant.onmicrosoft.com/groups
  5. 同意此应用程序导航到:https://login.microsoftonline.com/YOUR_TENANT.onmicrosoft.com/adminconsent?client_id=YOUR_CLIENT_ID&state=12345&redirect_uri=YOUR_REDIRECT_URI

然后,您需要将代码添加以下代码OnAuthorizationCodeReceived处理内,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; 
} 
+0

首先非常感谢您的回答! 我还剩下两个问题。 我应该在哪里添加该URL(步骤4)以及什么是Redirect uri(这是b2c的回复URI?)? 另一个问题的代码: 我填写变量什么要高度重视: - GraphClientId - GraphRedirectUri - GraphClientSecret - userTokenCache 和VisualStudio的呼吁,在一条错误消息:新的C。声明 非常感谢您的帮助:-) – DarkWing89

+0

进行了更新,以进一步阐明应用程序注册说明并解决c.Claim问题。 – Saca

+0

GraphClientID =您注册的应用程序的应用程序ID, GraphSecret =应用程序密钥, GraphRedirectUri =您指定的重定向URI, userTokenCache应该已经从示例中已经在该OnAuthorizationCodeReceived中的代码定义。 – Saca