BlazorStandaloneWASM-无法获取角色
创始人
2024-12-21 18:30:19
0

在 Blazor standalone WASM 应用程序中,要使用角色权限资源,需要先从服务器获取当前用户的角色。当在应用程序初始化时尝试获取角色时出现以下错误:Cannot fetch roles。

解决这个问题,需要确保在应用程序启动时已经通过身份验证,即已经获取到 JSON Web Token(JWT)。通过JWT可以向服务器发送包含用户角色的请求,获取用户角色是鉴定用户权限的有效方式。

下面是获取用户角色并将其保存到应用程序状态中的代码示例:

1.在Main方法中,调用带有身份验证的httpClient,来获取当前用户的角色。

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add("app");
 
    builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    // add authorization header to http client
    builder.Services.AddScoped(sp => new HttpClient
    {
        BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
    }.EnableIntercept(sp));

    // check the user authentication state
    builder.Services.AddAuthorizationCore();
    builder.Services.AddScoped();
    builder.Services.AddScoped();
 
    await builder.Build().RunAsync();
}

2.使用添加了身份验证的httpClient获取用户角色,并将其保存在应用程序状态中,以便其他组件可以使用它来做出访问控制决策。

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly IAccountService _accountService;
    public ApiAuthenticationStateProvider(IAccountService accountService)
    {
        _accountService = accountService;
    }

    public override async Task GetAuthenticationStateAsync()
    {
        try
        {
            var userInfo = await _accountService.GetUserInfoAsync();
            var identity = new ClaimsIdentity(userInfo.Claims, "jwt");
            var user = new ClaimsPrincipal(identity);

            // store user role in local state

相关内容

热门资讯

科技通报!德州局透视脚本下载安... 科技通报!德州局透视脚本下载安装最新版本,德州透视hhpoker,揭秘教程(有挂技巧)准备好在德州局...
专业讨论!wepoker辅助器... 专业讨论!wepoker辅助器如何使用,德扑HHpoker有挂吗,2025新版教程(有挂教程);大神...
玩家必看教程!佛手大菠萝有挂吗... 玩家必看教程!佛手大菠萝有挂吗,德普之星透视辅助,wpk教程(有挂技巧)是一款可以让一直输的玩家,快...
实测发现!约局吧辅助器,哈糖大... 实测发现!约局吧辅助器,哈糖大菠萝万能挂,教你教程(有挂攻略);《WPK辅助透视》‌:支持手机实时对...
一起来讨论!wepoker透视... 一起来讨论!wepoker透视底牌,wepoker免费辅助器,安装教程(有挂技巧)准备好在wepok...
最新技巧!pokemmo脚本辅... 最新技巧!pokemmo脚本辅助下载,hhpoker软件安装包,必备教程(有挂透明)准备好在poke...
玩家必看教程!wepoker透... 玩家必看教程!wepoker透视脚本免费下载pc,拱趴大菠萝机器人,AI教程(有挂软件);建议优先通...
来一盘!we poker辅助器... 来一盘!we poker辅助器v3.3,aapoker透视脚本入口,力荐教程(有挂透明);小薇(透视...
推荐十款!hhpoker免费透... 推荐十款!hhpoker免费透视脚本,wepoker黑侠辅助器,教你教程(有挂透明)科技教程也叫必备...
玩家交流!aapoker怎么拿... 玩家交流!aapoker怎么拿好牌,hh poker软件,扑克教程(有挂神器);原来确实真的有挂(需...