在C#中正确使用JwtTokens

时间:2015-04-04 11:29:29

标签: c# jwt claims

我正在玩JwtTokens并且无法使它们正常工作。 我正在使用http://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/。 我知道代码是乱七八糟的,但只是为了展示我正在尝试做的事情。 问题是我希望JwtTokenHandler因为生命周期而无法通过验证。

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”...

,则会失败

2 个答案:

答案 0 :(得分:25)

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

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

将其设置为0可使此功能正常运行。 仍然不明白为什么歪斜是5分钟,如果我在某个时候设置到期!!!

答案 1 :(得分:-2)

这肯定会起作用

TimeSpan.FromSeconds(0)将ClockSkew时间重置为零

TokenValidationParameters parameters = new TokenValidationParameters()
{
  RequireExpirationTime = true,
  ValidateIssuer = false,
  ValidateAudience = false,
  ClockSkew= TimeSpan.FromSeconds(0)
};