BlazorWebAssembly+IdentityServer-在成功验证后检索附加用户权限(声明)。
创始人
2024-12-21 22:30:25
0
  1. 在Identity Server中对应的用户Claims中添加需要的声明信息。

例如添加一个名为"myPermission"的声明:

new Claim("myPermission", "allowed")
  1. 在Identity Server的配置文件中,将需要的声明信息添加到IdentityResource或ApiResource中(根据自己的情况进行选择)。

例如在对应的IdentityResource或ApiResource中添加对"myPermission"声明的支持:

new IdentityResource("myIdentity", new[] {"myPermission"}),
  1. 在Blazor WebAssembly应用程序中,重写AuthenticationStateProvider以向用户Claims集合中添加Identity Server返回的附加声明信息。

例如:

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));
    }
}
  1. 注册自定义的AuthenticationStateProvider以替换内置的实现。

例如:

builder.Services.AddScoped();
  1. 在Blazor组件中使用注入的AuthenticationStateProvider。

例如:

@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!

}

相关内容

热门资讯

第二分钟了解“南通长牌有挂吗”... 第二分钟了解“南通长牌有挂吗”详细开挂辅助方法-确实是真的挂1、玩家可以在南通长牌有挂吗软件透明挂俱...
4分钟了解“都莱辅助软件”详细... 4分钟了解“都莱辅助软件”详细开挂辅助教程-真是有挂1、用户打开应用后不用登录就可以直接使用,点击都...
1分钟了解“吉祥小程序填大坑辅... 1分钟了解“吉祥小程序填大坑辅助器”详细开挂辅助工具-其实真的有挂1、每一步都需要思考,不同水平的挑...
六分钟了解“陕西三代辅助”详细... 六分钟了解“陕西三代辅助”详细开挂辅助神器-切实真的是有挂1、点击下载安装,陕西三代辅助插件透视分类...
3分钟了解“闲娱江西脚本”详细... 3分钟了解“闲娱江西脚本”详细开挂辅助技巧-其实是有挂1、闲娱江西脚本机器人多个强度级别选择2、闲娱...
1分钟了解“黑侠破解约局吧”详... 1分钟了解“黑侠破解约局吧”详细开挂辅助技巧-原来是真的挂1、让任何用户在无需黑侠破解约局吧AI插件...
第5分钟了解“蜀山四川小程序辅... 第5分钟了解“蜀山四川小程序辅助挂视频”详细开挂辅助app-其实存在有挂1、让任何用户在无需蜀山四川...
两分钟了解“好友赣南能装挂吗”... 两分钟了解“好友赣南能装挂吗”详细开挂辅助攻略-切实是有挂好友赣南能装挂吗辅助器中分为三种模型:好友...
十分钟了解“欢聚水鱼透视器”详... 十分钟了解“欢聚水鱼透视器”详细开挂辅助攻略-本来是真的挂1、进入到欢聚水鱼透视器黑科技之后,能看到...
第1分钟了解“九酷众游辅助”详... 第1分钟了解“九酷众游辅助”详细开挂辅助app-其实真的有挂1、实时九酷众游辅助开挂更新:用户可以随...