.Net Core 2.2 authorization required role

Hi,
I have been trying to implement the “New Policy Based Authorization” from:
here.

I can’t get the whole process to work for me. Here’s my scenario:
React SPA application is created and retrieves the token from the authorization server, with the custom created claims in the access token. The API is .net core 2.2, and here are some code snippets from the startup.cs:

           services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
                options.DefaultChallengeScheme = OktaDefaults.ApiAuthenticationScheme;
                options.DefaultSignInScheme = OktaDefaults.ApiAuthenticationScheme;
            })
           .AddOktaWebApi(new OktaWebApiOptions()
           {
               OktaDomain = "https://company.oktapreview.com",
               AuthorizationServerId = "authserveridgoeshere",

           });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminAccess", policy => policy.RequireRole("AppAdmin"));
            });

And the controller is pretect with:
[Authorize(Policy = “RequireAdminAccess”)]
[Route(“api/[controller]”)]
[ApiController]
public class ValuesController : ControllerBase

I created a scope and an access policy to include a rule with the new scope. But I am missing the part where I retrieve that scope and apply it in the policy role that should be created.

Thank you in advance.

2 Likes

Any update on this? I’m also fine with the Authentication. However, I also need to Authorize users based on their groups/roles. Couldn’t find any example for that.

Hey Andy,
Yes, we were able to authorize users based on their group, with Policy Based Authorization. First you should have a group that lists the users you want to add to, let’s say “AppXYZ admin users”, and add users to it.

In the authorization server:
1- Create a scope “AppXYZ:admin”
2- Create a claim
a- Include in token type: Access Token
b- Only Include groups the meet the following condition: Equals --> name of the group/role
c- Include in: “The following scopes”: the name of the scope you created in step 1 “AppXYZ:admin”
3- Access Policies:
a- create the access policy for the app users
b- create a rule for all users
c- create a rule for the admin group, move it to the top of the policies rules:
I- Grant type: checkbox all
II- user is: assigned the app and a member of the followind: Groups --> Name of the admin group
III- Scopes requested: the following scopes --> openid, etc… but you must add the scope you
creaed in step 1

Then go back to your code as explained in the original article and on top of the controller/method: authorize to the policy you created in the startup file.

I hope this helps.
Thanks,
Shehab

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.