繁体   English   中英

如何在用户的声明列表中保留多个 ClaimTypes.Role 值?

[英]How do I persist multiple ClaimTypes.Role values in User's Claims list?

我正在构建一个 ASP.NET 核心(v3.1)模块,我只是设法配置了一个 OpenIdConnect 身份验证。 现在,我需要从 API 获取所有用户角色,以便授予或拒绝对它们的访问权限,然后我通过OnAuthorizationCodeReceived事件将多个声明值添加到用户声明列表中的同一声明角色“ClaimTypes.Role”,如下所示:

OnAuthorizationCodeReceived = async (context) =>
{
    // Uses the authentication code and gets the access and refresh token
    var client = new HttpClient();
    var response = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest()
    {
        Address = urlServer + "/connect/token",
        ClientId = "hybrid",

        Code = context.TokenEndpointRequest.Code,
        RedirectUri = context.TokenEndpointRequest.RedirectUri,
    }

    if (response.IsError) throw new Exception(response.Error);

    var identity = new ClaimsIdentity(context.Principal.Identity);

    var listRoles = GenericProxies.RestGet<List<string>>(urlGetRoles, response.AccessToken); // GET request to API
    listRoles.ForEach(role => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

    context.HttpContext.User = new ClaimsPrincipal(identity);

    context.HandleCodeRedemption(response.AccessToken, response.IdentityToken);
}

在调试时,我注意到所有角色都添加到了用户声明列表之后:

context.HttpContext.User = new ClaimsPrincipal(identity);

但是,显然,在我的主页 controller 中(这是用户在经过身份验证后被重定向到的地方),当我访问 HttpContext.User 时,我似乎找不到我之前添加的任何角色,除了“管理员”(我猜这是一个默认的 ClaimTypes.Role 值)。

[Authorize]
public IActionResult Index()
{
    if (User.IsInRole("SomeRole"))
    {
        return RedirectToAction("SomeAction", "SomeController");
    }
    else
    {
        return RedirectToAction("Forbidden", "Error");
    }
}

阅读一些其他帖子论坛和主题,我发现这可能是一个上下文持久性问题,我试图用我的帐户 controller 中的这段代码来解决这个问题:

public async Task Login(string returnUrl = "/")
{
    await HttpContext.ChallengeAsync(
        "OIDC",
        new AuthenticationProperties
        {
            AllowRefresh = false,
            IsPersistent = true,
            RedirectUri = returnUrl
        });
}

一些例子说我可以使用context.Principal.AddIdentity(identity); 为了保留新的声明列表,但随后出现以下错误:

InvalidOperationException: only a single identity supported
IdentityServer4.Hosting.IdentityServerAuthenticationService.AssertRequiredClaims(ClaimsPrincipal principal)

总而言之,我必须找到一种方法来持久化我添加到用户声明列表中的角色声明,但直到现在我都没有成功。

如果这对任何人有用,请对此进行更新。

我推断出问题出在context.HttpContext.User = new ClaimsPrincipal(identity); ,我之前理解为处理新声明的持久性的代码部分。

实际上,我确实注意到有一个ClaimsPrincipal类型的context.Principal属性,并且看起来它是实际的 Current 上下文,所以我深入研究它并试图找出一种将元素添加到其“ IEnumerable<Claim> Claims ”的方法" 属性是只读的。

过了一会儿,我发现以下解决方案对我来说很好用:

代替

var identity = new ClaimsIdentity(context.Principal.Identity);
var listRoles = GenericProxies.RestGet<List<string>>(urlGetRoles, response.AccessToken); // GET request to API
listRoles.ForEach(role => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

我试过了

var identity = context.Principal.Identity as ClaimsIdentity;
if(identity != null)
{
    var listRoles = GenericProxies.RestGet<List<string>>(urlGetRoles, response.AccessToken); // GET request to API 
    foreach (var role in listRoles)
    {
        identity.AddClaim(new Claim(ClaimTypes.Role, role));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM