2017-08-25 192 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