Hello! everyone, I followed this tutorial Link and everything works fine. But now I want to implement authorization based on roles.
The roles are assigned through the Dashboard manually. In the App (razor page) I add the AuthorizeView to verify the role of the user, but it is not working as it should, since it does not show me anything.
Just to check how are you reading back the roles in the App?
Is it via the Acess tokens?
Usually, you can add the roles in the tokens when the Rules are executed, or you can enable
RBAC also on the API which will add permissions in the tokens as well.
When I read the Claims in the App, gives me the Role of the user, but I can’t (how can I said?) “transfer” that Role. Right now when I use [Authorize(Name=“name_of_role”)] on razor page gives me the custom error that “the user is not authorize to view this resource”, even when the user has the Role to view that resource.
Well, I just did it. I have to add .AddAccountClaimsPrincipalFactory< ArrayClaimsPrincipalFactory<RemoteUserAccount>>(); to OidcAuthentication. So the final code in Program.cs in Client side is:
public class ArrayClaimsPrincipalFactory<TAccount> : AccountClaimsPrincipalFactory<TAccount> where TAccount : RemoteUserAccount
{
public ArrayClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
: base(accessor)
{ }
// when a user belongs to multiple roles, IS4 returns a single claim with a serialised array of values
// this class improves the original factory by deserializing the claims in the correct way
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(TAccount account, RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
var claimsIdentity = (ClaimsIdentity)user.Identity;
if (account != null)
{
foreach (var kvp in account.AdditionalProperties)
{
var name = kvp.Key;
var value = kvp.Value;
if (value != null &&
(value is JsonElement element && element.ValueKind == JsonValueKind.Array))
{
claimsIdentity.RemoveClaim(claimsIdentity.FindFirst(kvp.Key));
var claims = element.EnumerateArray()
.Select(x => new Claim(kvp.Key, x.ToString()));
claimsIdentity.AddClaims(claims);
}
}
}
return user;
}
}