dnx451 RC1 InMemorySymmetricSecurityKey发生了什么?

我一直在尝试使用一个简单的密钥来创建和签署一个JwtSecurityToken。 经过大量的研究,似乎我发现的所有示例都使用InMemorySymmetricSecurityKey类,但不幸的是,该类似乎并不存在于最新版本的System.IdentityModel库中。

这些是我正在使用的依赖关系:

"System.IdentityModel.Tokens": "5.0.0-rc1-211161024",
"System.IdentityModel.Tokens.Jwt": "5.0.0-rc1-211161024"

我也尝试过使用它的基类SymmetricSecurityKey,但是当我尝试创建令牌时,出现以下异常:

"Value cannot be null.rnParameter name: IDX10000: The parameter 'signatureProvider' cannot be a 'null' or an empty object."

这是抛出异常的代码:

public static string CreateTokenHMAC()
{
    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String("test"));

    var key = new SymmetricSecurityKey(hmac.Key);

    var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

    JwtSecurityToken token = _tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor()
    {
        Audience = AUDIENCE,
        Issuer = ISSUER,
        Expires = DateTime.UtcNow.AddHours(6),
        NotBefore = DateTime.Now,
        Claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Email, "johndoe@example.com")
        },
        SigningCredentials = signingCredentials
    });

    return _tokenHandler.WriteToken(token);
}

这是我第一次使用JwtSecurityToken,所以我的猜测是我可能在某处丢失了一个步骤


我设法达到了完全相同的例外。 我通过另一种方式生成密钥来解决问题:

RSAParameters keyParams;
using (var rsa = new RSACryptoServiceProvider(2048))
{
    try
    {
        keyParams = rsa.ExportParameters(true);
    }
    finally
    {
        rsa.PersistKeyInCsp = false;
    }
}
RsaSecurityKey key = new RsaSecurityKey(keyParams);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

这是Mark Hughes在ASP.NET 5 RC1上关于基于令牌的身份验证的一篇很棒的文章


我无法使用接受的答案中提供的RsaSecurityKey示例使其工作,但这对我来说很有用(使用System.IdentityModel.Tokens.Jwt v5.1.3)。

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("test"));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

var securityTokenDescriptor = new SecurityTokenDescriptor()
{
    Subject = new ClaimsIdentity(new List<Claim>()
    {
        new Claim(ClaimTypes.NameIdentifier, "johndoe@example.com"),
        new Claim(ClaimTypes.Role, "Administrator"),
    }, "Custom"),
    NotBefore = DateTime.Now,
    SigningCredentials = signingCredentials,
    Issuer = "self",
    IssuedAt = DateTime.Now,
    Expires = DateTime.Now.AddHours(3),
    Audience = "http://my.website.com"
};

var tokenHandler = new JwtSecurityTokenHandler();
var plainToken = tokenHandler.CreateToken(securityTokenDescriptor);
var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

并进行验证

var validationParameters = new TokenValidationParameters()
{
     ValidateAudience = true,
     ValidAudience = "http://my.website.com",
     ValidateIssuer = true,
     ValidIssuer = "self",
     ValidateIssuerSigningKey = true,
     IssuerSigningKey = signingKey,
     RequireExpirationTime = true,
     ValidateLifetime = true,
     ClockSkew = TimeSpan.Zero
};
try
{
    SecurityToken mytoken = new JwtSecurityToken();
    var myTokenHandler = new JwtSecurityTokenHandler();
    var myPrincipal = myTokenHandler.ValidateToken(signedAndEncodedToken, validationParameters, out mytoken);
} catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine("Authentication failed");
}

这应该工作(注意这需要RC2包> 304180813)

var handler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(
        new Claim[] { new Claim(ClaimTypes.NameIdentifier, "bob") }),
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(new byte[256]),
        SecurityAlgorithms.HmacSha256)
};

var jwt = handler.CreateEncodedJwt(tokenDescriptor);
链接地址: http://www.djcxy.com/p/22381.html

上一篇: dnx451 RC1 What happened to InMemorySymmetricSecurityKey?

下一篇: Authentication in ASP.NET 5 (vNext)