Среды
- Asp.Net Core 5.0
- Приложение Blazor WebAssembly (хостинг Asp.Net Core)
- Asp.Net Core Identity (с Identity Server 4)
Проблема
Я хочу использовать авторизацию на основе ролей между стороной сервера и стороной клиента.
Я могу войти в систему правильно, и UserManager.IsInRoleAsync(user, "admin")
вернет True на стороне сервера.
Но ни @attribute [Authorize(Roles = "admin")]
, ни <AuthorizeView Roles="admin">
не работают на стороне клиента. Также User.Identity.IsInRole("admin")
возвращает False на стороне клиента.
Как мне получить роль пользователя на стороне клиента?
Коды
Server.csproj
// Startup.ConfigureServices()
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 2;
options.Password.RequireNonAlphanumeric = false;
options.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
// Startup.Configure()
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
// RolesController.Get()
var userid = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var currentUser = await userManager.FindByIdAsync(userid);
return await userManager.IsInRoleAsync(currentUser, "admin"); // Returns True
Client.csproj
// Program.Main()
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("WebAppIdentity.ServerAPI"));
builder.Services.AddApiAuthorization();
// Test.razor
<AuthorizeView Roles="admin">
<Authorizing>
Authorizing...
</Authorizing>
<NotAuthorized>
You are not an admin. // Always here
</NotAuthorized>
<Authorized>
Hello, admin!
</Authorized>
</AuthorizeView>
<button @onclick="ShowInfo">Show Info</button>
<p>@infoString</p>
@code
{
[CascadingParameter]
private Task<AuthenticationState> stateTask { get; set; }
private string infoString { get; set; }
private async void ShowInfo()
{
var user = (await stateTask).User;
infoString = $"Is admin: {user.IsInRole("admin")}"; // Always False
}
}