简体   繁体   中英

.net core [Authorize] using ClaimsIdentity with AAD groups

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM