例如添加一个名为"myPermission"的声明:
new Claim("myPermission", "allowed")
例如在对应的IdentityResource或ApiResource中添加对"myPermission"声明的支持:
new IdentityResource("myIdentity", new[] {"myPermission"}),
例如:
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private readonly HttpClient httpClient;
public CustomAuthStateProvider(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public override async Task GetAuthenticationStateAsync()
{
ClaimsIdentity identity;
// 利用Identity Server获取当前用户的Claims信息
var user = await httpClient.GetFromJsonAsync("/api/identity");
if (user.IsAuthenticated)
{
// 创建一个包含附加声明的Identity
identity = new ClaimsIdentity(user.Claims, "BlazorServerAuth");
// 向用户的Claims集合中添加Identity Server返回的附加声明信息
identity.AddClaim(new Claim("myPermission", user.MyPermission);
}
else
{
identity = new ClaimsIdentity();
}
return new AuthenticationState(new ClaimsPrincipal(identity));
}
}
例如:
builder.Services.AddScoped();
例如:
@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider
@if (((await AuthenticationStateProvider.GetAuthenticationStateAsync()).User).IsInRole("admin"))
{
Welcome Admin!
}
else if (((await AuthenticationStateProvider.GetAuthenticationStateAsync()).User).HasClaim(c => c.Type == "myPermission" && c.Value == "allowed"))
{
Welcome User With Extra Permission!
}
else
{
Welcome User!
}
上一篇:BlazorWebAssembly(net5.0)在IIS上无法发布
下一篇:BlazorWebAssembly-BestpracticesforUserAccountsandIdentityServer