2017-06-20 35 views
0

我看到這在我的((System.Security.Claims.ClaimsIdentity)User.Identity).Claims.NET核心使用ClaimsIdentity與AAD組[授權]

enter image description here

如何利用這些組GUID的我從我們的Azure的AD得到的(保證基於組員資格的端點)?

[Authorize(Roles="<group guid here>")] 

[Authorize("<group guid here>")] 

或者我需要在startup.cs文件中設置的東西了?

回答

2

你可以在asp.net核心使用政策,使用屬性與命名策略,那麼你在啓動定義策略,要求組要求,並設置能通過組ID:

 public void ConfigureServices(IServiceCollection services) 
     { 
      // Add MVC services to the services container. 
      services.AddMvc(); 

      // Add Authentication services. 
      services.AddAuthentication(sharedOptions => sharedOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme); 


      services.AddAuthorization(options => 
      { 
       options.AddPolicy(
        "CanAccessGroup", 
        policyBuilder => policyBuilder.RequireClaim("groups", "8e39f882-3453-4aeb-9efa-f6ac6ad8e2e0")); 
      }); 
     } 

然後在控制器:

[Authorize(Policy = "CanAccessGroup")] 
public IActionResult Contact() 
     { 
      ViewData["Message"] = "Your contact page."; 

      return View(); 
     } 

如果組ID不在用戶組要求的,將重定向用戶訪問被拒絕頁面,你也可以寫你的策略規則的邏輯如圖所示here

+0

我認爲你也可以設置RoleClaimType,然後使用角色,但這是一個更好的解決方案。 – juunas

+0

@juunas:不鼓勵使用角色,因爲它非常不靈活,需要對角色進行硬編碼。而策略允許模塊插入自己的策略或覆蓋現有的策略。有了索賠,你可以做任何你可以做的一切,你可以做的角色和更多 – Tseng

+0

是的,正是爲什麼我說這是更好的;) – juunas