Andrew
Andrew

Reputation: 3570

ASP.NET Core Custom Role Based Authorization (Custom User.IsInRole)?

I am using a postgres Database through a library called Marten with a .NET app, I have a custom IUserLoginStore which manages retrieving the user and its roles. This seems to be working correctly but I am have an issue with setting up authorization.

I am using authentication through google and it is working fine:

var info = await _signInManager.GetExternalLoginInfoAsync();
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);

This action throws an access denied issue:

[HttpPost()]
[Authorize(Roles = "Admin")]
public JsonResult SubmitArticle([FromBody] ArticleInputModel input) {...}

I have dug into the Authorization code and the problem seems to be with the default ClaimsPrincipal code:

public virtual bool IsInRole(string role)
{
  return false;
}

Should I implement my own version of ClaimsPrinciple and override the IsInRole, and if I do how do I get this back into the app?

private static void ConfigureSecurity(IServiceCollection services)
{
    services.AddIdentity<User, Role>()
        .AddUserValidator<UserValidator>()
        .AddUserStore<MartenUserStore>()
        .AddRoleStore<MartenRoleStore>()
        .AddDefaultTokenProviders();
}

Upvotes: 3

Views: 2550

Answers (1)

Andrew
Andrew

Reputation: 3570

Alright figured it out after a large amount of digging, In my case the MartenRoleStore was implementing IUserLoginStore it also needed to implement IUserRoleStore which has GetRolesAsync and IsInRoleAsync. (This is very important it has to be the exact same class you used for .AddUserStore<>();)

This is the code that I found that caused the issue:

https://github.com/aspnet/Identity/blob/master/src/Microsoft.AspNetCore.Identity/UserManager.cs#L258

This is what makes it work:

https://github.com/aspnet/Identity/blob/master/src/Microsoft.AspNetCore.Identity/UserClaimsPrincipalFactory.cs#L96

Upvotes: 5

Related Questions