Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net Microsoft.IdentityModel.Tokens:添加附加声明 背景_.net_Asp.net Core_Jwt_Claims Based Identity_Bearer Token - Fatal编程技术网

.net Microsoft.IdentityModel.Tokens:添加附加声明 背景

.net Microsoft.IdentityModel.Tokens:添加附加声明 背景,.net,asp.net-core,jwt,claims-based-identity,bearer-token,.net,Asp.net Core,Jwt,Claims Based Identity,Bearer Token,出于authn/z目的,我们正在使用创建JWT令牌。此令牌通过Authorize:BearerHTTP头传递到不同的微服务以模拟调用者 微服务本身利用Microsoft.IdentityModel.Tokens来验证JWT令牌: using System; using System.Text; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Builder; // The key length needs to

出于authn/z目的,我们正在使用创建JWT令牌。此令牌通过Authorize:BearerHTTP头传递到不同的微服务以模拟调用者

微服务本身利用Microsoft.IdentityModel.Tokens来验证JWT令牌:

using System;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Builder;

// The key length needs to be of sufficient length, or otherwise an error will occur.
var tokenSecretKey = Encoding.UTF8.GetBytes(Configuration["TokenSecretKey"]);

var tokenValidationParameters = new TokenValidationParameters
{
    // Token signature will be verified using a private key.
    ValidateIssuerSigningKey = true,
    RequireSignedTokens = true,
    IssuerSigningKey = new SymmetricSecurityKey(tokenSecretKey),

    // Token will only be valid if contains "accelist.com" for "iss" claim.
    ValidateIssuer = true,
    ValidIssuer = "accelist.com",

    // Token will only be valid if contains "accelist.com" for "aud" claim.
    ValidateAudience = true,
    ValidAudience = "accelist.com",

    // Token will only be valid if not expired yet, with 5 minutes clock skew.
    ValidateLifetime = true,
    RequireExpirationTime = true,
    ClockSkew = new TimeSpan(0, 5, 0),

    ValidateActor = false,
};

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    TokenValidationParameters = tokenValidationParameters,
});
某些JWT保留声明将自动填充到HttpContext.User中,即


问题 是否有一种简单而优雅的方法将其他自定义声明填充到HttpContext.User中?目前我能想到的唯一方法是解码令牌并调用HttpContext.User.Claims.Add(…)


提前谢谢你

不必解码令牌并添加您的
自定义声明
,您可以动态地对
用户
自定义
声明进行
联合

private async Task<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user)
        {
            //Get the user claims
            var userClaims = await _userManager.GetClaimsAsync(user);
            //Merge the claims here
            return new JwtSecurityToken(
                issuer: "", //Insert your issuer
                audience: "",//Insert your audience
                claims: GetTokenClaims(user).Union(userClaims), //This is the Union you need
                expires: DateTime.UtcNow.AddMinutes(5),//Add expiry time here
                signingCredentials: new SigningCredentials(IssuerSigningKey, SecurityAlgorithms.HmacSha256)//Do your magic here
            );
        }
最后,您可以将其总结如下:

//Get the token combination
var token = await GetJwtSecurityToken(user);
//Write and return the token
return Ok(new
{
    token = new JwtSecurityTokenHandler().WriteToken(token),
    expiration = token.ValidTo,              
});

您不需要解码令牌并添加您的
自定义声明
,而需要对
用户
自定义
声明进行动态的
联合

private async Task<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user)
        {
            //Get the user claims
            var userClaims = await _userManager.GetClaimsAsync(user);
            //Merge the claims here
            return new JwtSecurityToken(
                issuer: "", //Insert your issuer
                audience: "",//Insert your audience
                claims: GetTokenClaims(user).Union(userClaims), //This is the Union you need
                expires: DateTime.UtcNow.AddMinutes(5),//Add expiry time here
                signingCredentials: new SigningCredentials(IssuerSigningKey, SecurityAlgorithms.HmacSha256)//Do your magic here
            );
        }
最后,您可以将其总结如下:

//Get the token combination
var token = await GetJwtSecurityToken(user);
//Write and return the token
return Ok(new
{
    token = new JwtSecurityTokenHandler().WriteToken(token),
    expiration = token.ValidTo,              
});

嗨@Fabe,你试过我下面答案中的方法吗?嗨@Fabe,你试过我下面答案中的方法吗?非常感谢你的帮助!这不完全是我的意思。您正在描述如何向现有令牌添加其他声明。我已经将现有声明添加到JWT令牌中。当客户端接收到令牌时,一些JWT声明会自动填充到HttpContext.User中,但当我尝试访问其他JWT声明时,返回null。对不起,我没说清楚。我会更新我的问题。非常感谢你的帮助!这不完全是我的意思。您正在描述如何向现有令牌添加其他声明。我已经将现有声明添加到JWT令牌中。当客户端接收到令牌时,一些JWT声明会自动填充到HttpContext.User中,但当我尝试访问其他JWT声明时,返回null。对不起,我没说清楚。我会更新我的问题。