【发布时间】:2021-02-24 01:28:22
【问题描述】:
环境
- Asp.Net Core 5.0
- Blazor WebAssembly 应用程序(Asp.Net 核心托管)
- 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
}
}
【问题讨论】:
-
您是否尝试过本期中列出的步骤? github.com/dotnet/AspNetCore.Docs/issues/17649
-
@DCCoder 它有效!!!谢谢!
标签: c# asp.net blazor-server-side blazor-client-side blazor-webassembly