Blazor与IdentityServer4的集成的角色获取(转)

转自大佬Blazor与IdentityServer4的集成(六)_blazorserver microsoft.aspnetcore.identity.core_65号腕的博客-CSDN博客

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        //...
        //添加以下代码
        //指定从Identity Server的UserInfo地址来取Claim
        options.GetClaimsFromUserInfoEndpoint = true;
        //指定要取哪些资料(除Profile之外,Profile是默认包含的)
        options.Scope.Add("role");
        options.Scope.Add("permission");
        //这里是个ClaimType的转换,Identity Server的ClaimType和Blazor中间件使用的名称有区别,需要统一。
        options.TokenValidationParameters.RoleClaimType = "role";
        options.TokenValidationParameters.NameClaimType = "name";
        options.Events.OnUserInformationReceived = (context) =>
            {
                //回顾之前关于WebAssembly的例子,涉及到数组的转换,这里也一样要处理

                ClaimsIdentity claimsId = context.Principal.Identity as ClaimsIdentity;

                var roleElement = context.User.RootElement.GetProperty("role");
                if (roleElement.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    var roles = context.User.RootElement.GetProperty("role").EnumerateArray().Select(e =>
                    {
                        return e.ToString();
                    });
                    claimsId.AddClaims(roles.Select(r => new Claim("role", r)));
                }
                else
                {
                    claimsId.AddClaim(new Claim("role", roleElement.ToString()));
                }

                var permissionElement = context.User.RootElement.GetProperty("permission");
                if (permissionElement.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    var permissions = permissionElement.EnumerateArray().Select(e =>
                    {
                        return e.ToString();
                    });
                    claimsId.AddClaims(permissions.Select(p => new Claim("permission", p)));
                }
                else
                {
                    claimsId.AddClaim(new Claim("permission", permissionElement.ToString()));
                }


                return Task.CompletedTask;
            };
    });

// 这里是基于决策的授权操作,WebAssembly的例子中有相关的说明,Blazor Server的使用方式也一样
services.AddAuthorizationCore(option =>
{
    string[] permissions = new string[]
    {
        "create",
        "retrieve",
        "update",
        "delete"
    };
    foreach (var p in permissions)
    {
        option.AddPolicy(p, policy =>
        {
            policy.RequireClaim("permission", new string[] { p });
        });
    }
});

 

posted @ 2023-09-12 14:53  ccqin  阅读(34)  评论(0编辑  收藏  举报