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!

}

相关内容

热门资讯

推荐一款辅助!wepoker免... 本地部署 AI 黑科技工具迎来新版本,不用上传文件到云端就能完成wepoker免费脚本咨询解析、 A...
三分钟了解透视挂!we pok... 三分钟了解透视挂!we poker插件,wepoker外卦神器软件安装(果然是真的有透视挂)AI 是...
带你了解透视挂!德扑圈透视,德... 您好:德扑之星透视这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
总算清楚透视挂!wepoker... 您好:wepoker软件靠谱么这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
我来教大家辅助器!wepoke... 我来教大家辅助器!wepoker辅助脚本,微扑克是如何开挂的教程(原本存在有辅助器)AI 是一款可以...
一秒答解透视!wepoker透... 很多人使用云端 AI 时,都担心wepoker透视有没有、内部资料上传带来隐私风险。这款本地运行的 ...
专业讨论!辅助挂!wepoke... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
记者爆料开挂!德普之星透视辅助... 记者爆料开挂!德普之星透视辅助插件,wepoker开挂技巧插件(竟然真的是有开挂)主打本地运行的 A...
一分钟带你了解透视挂!we p... 您好:we poker辅助器下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
一分钟教你辅助器!wpk俱乐部... 很多人使用云端 AI 时,都担心wpk俱乐部是真的吗、内部资料上传带来隐私风险。这款本地运行的 AI...