如何在.netcore

时间:2018-10-27 00:03:58

标签: c# .net-core jwt asp.net-core-2.0 asp.net-core-webapi

我正在将.netcore 2与JwtSecurityToken一起使用来生成令牌

            var jwtSecurityToken = new JwtSecurityToken(
                issuer: issuer,
                audience:issuer,
                claims: claims,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );

            jwtSecurityToken.Header.Add("kid", requestAPIKey);

现在,因为我使用了Idenity,所以我已经从JwtSecurityToken切换到Security Token Descriptor,并且我的代码是:

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

我的问题是使用安全令牌描述符时如何将小孩添加到令牌头中?在JwtSecurityToken中,我使用以下代码添加了它:

jwtSecurityToken.Header.Add("kid", requestAPIKey);

如何使用SecurityTokenDescriptor做同样的事情?谢谢你!

3 个答案:

答案 0 :(得分:1)

尝试一下:

var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(secretKey));
securityKey.KeyId = "KID_HERE";
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

var jwtSecurityToken = new JwtSecurityToken(
                issuer: issuer,
                audience:issuer,
                claims: claims,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: signingCredentials 
            );

jwtSecurityToken.Header.Add("kid", requestAPIKey);

答案 1 :(得分:1)

这是一个您可以使用的小型复制和粘贴就绪功能:

private static string CreateJwt(IEnumerable<Claim> claims, DateTime expiresAt)
    {
        // Creating the symmetric key and signing credentials
        var veryUnsecureSecureString = "YOURSYMMETRICKEYHERE";
        var symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(veryUnsecureSecureString));
        symmetricKey.KeyId = "YourKeyId";
        var credentials = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256);

        // Set security token descriptor
        var tokenDescriptor = new SecurityTokenDescriptor {
            Subject = new ClaimsIdentity(claims),
            Expires = expiresAt,
            Issuer = "your issuer",
            Audience = "your audience",
            SigningCredentials = credentials,
        };

        // Crate jwt security token handler to create the token
        var tokenHandler = new JwtSecurityTokenHandler();

        // create the jwt object
        var token = tokenHandler.CreateToken(tokenDescriptor);

        // convert to string
        return tokenHandler.WriteToken(token);
    }

这是一个生成的 JWT:

eyJhbGciOiJIUzI1NiIsImtpZCI6IllvdXJLZXlJZCIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2MTE2ODQ2NzgsImV4cCI6MTYxMTg0NjY3MywiaWF0IjoxNjExNjg0Njc4LCJpc3MiOiJ5b3VyIGlzc3VlciIsImF1ZCI6InlvdXIgYXVkaWVuY2UifQ.wHOw-PkrP1iXgLkcT0JznDr2D01KAdFpVkdL6xIo5zc

使用 JWT.io 调试器解码,我得到以下信息:

标题:

{
  "alg": "HS256",
  "kid": "YourKeyId",
  "typ": "JWT"
}

有效载荷:

{
  "nbf": 1611684678,
  "exp": 1611846673,
  "iat": 1611684678,
  "iss": "your issuer",
  "aud": "your audience"
}

答案 2 :(得分:0)

这是我使用的代码段:

var tokenHandler = new JwtSecurityTokenHandler(); 
        var key = Encoding.UTF8.GetBytes("Secret"); 
        var tokenDescriptor = new SecurityTokenDescriptor 
        { 
            Subject = new ClaimsIdentity(new Claim[] 
            { 
                new Claim(ClaimTypes.Name, UserId), 
                new Claim(name, value), 
                new Claim(name, value)
            }), 

            Expires = DateTime.UtcNow.AddMinutes(5), 
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) 

        }; 

        var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); 
        token.Header.Add("kid", ""); 

        token.Payload.Remove("iss"); 
        token.Payload.Add("iss", "your issuer"); 

        var tokenString = tokenHandler.WriteToken(token);