Previously in .NET Framework I used a custom RoleProvider
alongside Windows Authentication to deliver custom roles against the current principal as opposed to using Active Directory groups.
So, the goal is to be able to use the decorative [Authorize(Roles="")]
attribute where the roles are coming from a database and not active directory (or a combination of both would be fine).
To achieve this in core I believe I need to use IClaimsTransformation
to assign role claims as discussed here.
Here I'm just trying to add one role "Admin" however when I use [Authorize(Roles = "Admin")]
I get a 403 Unauthorised response.
Startup.cs
services.AddRazorPages();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
-------
app.UseAuthorization();
ClaimsTransformer.cs
public class ClaimsTransformer : IClaimsTransformation
{
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identity = (ClaimsIdentity)principal.Identity;
var c = new Claim(identity.RoleClaimType, "Admin");
identity.AddClaim(c);
return await Task.FromResult(principal);
}
}
Annoyingly this works when I call User.IsInRole()
and I can see the group when I inspect the Claims so it is being added however it doesn't work with the Authorize attribute. Any advice would be appreciated.