I'm trying to give custom roles in my Blazor Server application. User who are authenticated with Windows Authentication should be given one of these custom roles depending on their Active Directory Groups, one group represents one role.
If the user is in the correct group, then the user will be given a claim of the type RoleClaimType. These claims are later used to authorize certain pages and actions.
I haven't seen anyone talk so much about Windows Authentication and Active Directory using Blazor Server so therefore I am having these questions. This is my attempt but it is a mix of parts from here and there. So I'm not sure if this is the best way to do it or if it's unsafe.
This is what I've come up with so far..
ClaimTransformer.cs, I got the Adgroup from appsettings.json.
public class ClaimsTransformer : IClaimsTransformation
{
private readonly IConfiguration _configuration;
public ClaimsTransformer(IConfiguration configuration)
{
_configuration = configuration;
}
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var claimsIdentity = (ClaimsIdentity)principal.Identity
string adGroup = _configuration.GetSection("Roles")
.GetSection("CustomRole")
.GetSection("AdGroup").Value;
if (principal.IsInRole(adGroup))
{
Claim customRoleClaim = new Claim(claimsIdentity.RoleClaimType, "CustomRole");
claimsIdentity.AddClaim(customRoleClaim);
}
return Task.FromResult(principal);
}
}
To get the Claimstransformer to work with the Authorize attribute, use this in Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAuthorization();
app.UseAuthentication();
...
}
I also have registered the ClaimsTransformer in Startup.cs with:
services.AddScoped<IClaimsTransformation, ClaimsTransformer>();
To authorize the whole Blazor component:
@attribute [Authorize(Roles = "CustomRole")]
or to authorize parts of the component:
<AuthorizeView Roles="CustomRole">
<Authorized>You are authorized</Authorized>
</AuthorizeView>
So my questions are basically:
- Does these claims have to be reapplied? If they expire, when do they expire?
- What is the best practice for this type of authorization?
- Is this way secure?