Home > Software engineering >  Claims and policy based Authorization
Claims and policy based Authorization

Time:04-04

I am using policy-based authorization. here I'm storing claims information if after login in MVC controller

ClaimsIdentity identity = null;
                identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Role, user[0].Type)
                });

here is the Authorization setup in startup.cs configurationServices method

services.AddAuthorization(options =>
        {
            options.AddPolicy("OwnerOnly", policy => policy.RequireClaim(ClaimTypes.Role,"Owner"));
            options.AddPolicy("AdminOnly", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
            options.AddPolicy("UserOnly", policy => policy.RequireClaim(ClaimTypes.Role, "User"));

        });

and the controller

[Authorize(Policy = "OwnerOnly")]
    public IActionResult NewDepartment()
    {
        return View();
    }

This authorization redirects to me to (This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 401) page although admin logs in with role. What are the problems here?

CodePudding user response:

well, you don't need to define a policy for each roles in your app. you can define your policy like this below:

services.AddAuthentication(
                CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(x =>
                {
                    x.LoginPath = "/Account/Login";
                    x.AccessDeniedPath = "/Account/AccessDenied";
                });
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            });

and you can control it as [Authorize(Roles="Owner")] in top of your action.

that [Authorize(Roles="Owner")] Roles comes from your claims that you are setting it in login action.

ClaimsIdentity identity = null;
identity = new ClaimsIdentity(new[]
{
  new Claim(ClaimTypes.Role, "Owner")
});

CodePudding user response:

In your Startup.cs you should call, app.UseAuthorization();

  • Related