.net core [Authorize] using ClaimsIdentity with AAD groups

与世无争的帅哥 提交于 2019-12-24 06:36:27

问题


I am seeing this in my ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims:

How do I make use of these group GUID's I am getting from our Azure AD (to secure the endpoint based on group membership)?

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

or

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

Or do I need to set something up in the startup.cs file?


回答1:


You could use policy in asp.net core , use an attribute with a named policy then you define the policy in startup to require group claim and set allowed Group 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"));
            });
        }

Then in controller :

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

            return View();
        }

If the group id is not in the user group claims, it will redirect user to access denied page , you could also write your policy rules logic as shown here .



来源:https://stackoverflow.com/questions/44643361/net-core-authorize-using-claimsidentity-with-aad-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!