Sergio Di Fiore
Sergio Di Fiore

Reputation: 466

ASP.NET Core 2.2 Authorization not authorizing

I'm working on a simple example of an authorization, using claims and the authorization is not granted.

Just for clarity, I'm using ASP.NET Core 2.2.4

The startup.cs is configured as:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    ...
    services.AddIdentity<IdentityUser, IdentityRole>(option => { option.Password = new PasswordOptions { ... }; };
    services.ConfigureApplicationCookie(option => { option.LoginPath = "/logins/Index"; });

    services.AddAuthorization(option => 
    {
        option.AddPolicy("EditorOver18Policy", policy =>
        {
            policy.RequireClaim("Over18Claim");
        });
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    app.UseMvc(routes =>
        { ... });
}

During the logins the claims are built:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (!ModelState.IsValid)
    { ... }

    var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);

    if (!result.Succeeded)
    { ... }

    var claims = new List<Claim>();
    claims.Add(new Claim("Over18Claim", "True"));

    var claimIdentity = new ClaimsIdentity(claims);

    User.AddIdentity(claimIdentity);

    if (!string.IsNullOrEmpty(model.ReturnUrl))
        return Redirect(model.ReturnUrl);

    return RedirectToAction("Display", "Photos");
}

The controller that is to be protected is:

[Authorize (policy: "EditorOver18Policy")]
public IActionResult Upload()
{
    ...
}

Plain as that, when a run it, make sure I just logged in and thus acquired the claim, I get an access denied error (sorry if it's in Portuguese):

enter image description here

What am I missing?

Upvotes: 1

Views: 95

Answers (1)

Nan Yu
Nan Yu

Reputation: 27588

To add custom claims , you can implement a custom IUserClaimsPrincipalFactory or use UserClaimsPrincipalFactory as a base class:

public class ApplicationClaimsIdentityFactory : Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory<IdentityUser>
{
    UserManager<IdentityUser> _userManager;
    public ApplicationClaimsIdentityFactory(UserManager<IdentityUser> userManager,
        IOptions<IdentityOptions> optionsAccessor) : base(userManager, optionsAccessor)
    { }
    public async override Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
    {
        var principal = await base.CreateAsync(user);

            ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
            new Claim("Over18Claim", "true")
        });

        return principal;
    }
}

Then register that in ConfigureServices function of Startup.cs:

services.AddScoped<IUserClaimsPrincipalFactory<IdentityUser>, ApplicationClaimsIdentityFactory>();

Upvotes: 1

Related Questions