在C#中正确使用JwtTokens [英] Correct use of JwtTokens in C#

查看:1805
本文介绍了在C#中正确使用JwtTokens的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JwtTokens,不能使其正常工作. 我正在使用 http://www.nuget.org/packages/System. IdentityModel.Tokens.Jwt/. 我知道代码是一团糟,但是只是为了展示我正在尝试做的事情. 问题是我希望JwtTokenHandler由于生存期而使验证失败.

I'm playing a with JwtTokens and can't make them work properly. I'm using http://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/ for it. I know the code is a mess but is just to show what I'm trying to do. The problem is that I want the JwtTokenHandler to fail the validation because of the lifetime.

var key = "5A0AB091-3F84-4EC4-B227-0834FCD8B1B4";
var domain = "http://localhost";
var allowedAudience = "http://localhost";
var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
var issuer = "self";
var securityKey = System.Text.Encoding.Unicode.GetBytes(key);
var inMemorySymmetricSecurityKey = new InMemorySymmetricSecurityKey(securityKey);

var now = DateTime.UtcNow;
var expiry = now.AddSeconds(1);
var tokenHandler = new JwtSecurityTokenHandler();
var claimsList = new List<Claim>()
{
    new Claim(ClaimTypes.Name, "user"),
    new Claim(ClaimTypes.Webpage, allowedAudience),
    new Claim(ClaimTypes.Uri, domain),                
    new Claim(ClaimTypes.Expiration,expiry.Ticks.ToString())
};
var roles = new List<string>() { "admin" };
claimsList.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

var identity = new GenericIdentity("user");

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(identity, claimsList),
    TokenIssuerName = issuer,
    AppliesToAddress = allowedAudience,
    Lifetime = new Lifetime(now, expiry),
    SigningCredentials = new SigningCredentials(inMemorySymmetricSecurityKey, signatureAlgorithm, digestAlgorithm),
};

var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

var validationParameters = new TokenValidationParameters()
{
    ValidIssuer = issuer,
    ValidAudience = allowedAudience,
    IssuerSigningToken = new BinarySecretSecurityToken(securityKey)
};

Thread.Sleep(2000);
try
{
    SecurityToken securityToken;
    tokenHandler.ValidateToken(token, validationParameters, out securityToken);
    Console.WriteLine("OK");
}
catch (Exception e)
{
    Console.WriteLine("Error {0}", e.Message);
}

这不是因为我等待2秒钟而失败吗? 如果我将ValidationTokenParameter的颁发者更改为"x",则会失败...

Isn't this suppose to fail since I'm waiting 2 seconds? It fails if I change the issuer of the ValidationTokenParameter to "x"...

推荐答案

发现了问题. 验证参数的默认时钟偏差为5分钟

Found the issue. The validation parameters have a default clock skew of 5 minutes

/// <summary>
/// Default for the clock skew.
/// 
/// </summary>
/// 
/// <remarks>
/// 300 seconds (5 minutes).
/// </remarks>
public static readonly TimeSpan DefaultClockSkew;

将该值设置为0即可完成这项工作. 如果我将过期时间设置为某个时间,仍然不明白为什么偏斜时间是5分钟!!!

Setting that to 0 make this work. Still don't understand why the skew is 5 minutes, if I set the expiry at some point!!!

这篇关于在C#中正确使用JwtTokens的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆