Home > Enterprise >  Policy based authorization gives InvalidOperationException
Policy based authorization gives InvalidOperationException

Time:09-30

I have to add policy based authentication to my .net 6 webapp. I added

builder.Services.AddAuthorization(options =>
{
     options.AddPolicy(Constants.Policies.RequireGlobalAdminRole, policy => policy.RequireRole(Constants.Roles.GlobalAdmin));
 });

to the program.cs file and in the dashboard controller I have decorated

 [Authorize(Policy = Constants.Policies.RequireGlobalAdminRole)]

In the after login, I created the claim for the role

                 var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Role,Data.User.Role.RoleName)
                    };
                    var Identity=new ClaimsIdentity(claims);
                    ClaimsPrincipal claimsPrincipal=new ClaimsPrincipal(Identity);.

But after successfull login, this error occurs.

InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).

enter image description here

CodePudding user response:

You need to define an authentication scheme. For example (if you are using OIDC):

builder.Services.AddAuthentication(options =>
{
   options.DefaultScheme = "WebAuthScheme";
   options.DefaultChallengeScheme = "oidc";
})

Take a look at enter image description here

Finally, add the policy to the home controller:

[Authorize(Policy = "mypolicy")]
public class HomeController : Controller {}
  • Related