I'd like to customize claims after getting authenticating a Blazor WASM app to Azure AD.
I've found sample code like below to do this.
My problem, is that I need to call a web service from inside the ExampleClaimsPrincipalFactory to get the roles and that service requires authentication that has not yet been fully completed, therefore, calling that service from the CreateUserAsync returns a 500 error (I can call that same service successfully post login). I've left the service call out of the sample for simplicity.
I've tried IClaimsTransformation with Azure AD, but when I try to manually get the User.Claims on a test page, it's not fired.
Setup in the Program Class
builder.Services.AddMsalAuthentication()
.AddAccountClaimsPrincipalFactory<ExampleClaimsPrincipalFactory<RemoteUserAccount>>();
Factory Class
public class ExampleClaimsPrincipalFactory<TAccount> : AccountClaimsPrincipalFactory<TAccount>
where TAccount : RemoteUserAccount
{
public ExampleClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
: base(accessor)
{
//Any dependency injection or construction of objects
//inside this constructor usually leads to wasm memory exceptions
}
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(TAccount account, RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
if (account != null)
{
//Add logic here to get custom user information
//Add Claims to the user identity like so
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("type", "value"));
}
return user;
}
}