C# 在C中正确使用JWTtoken#

C# 在C中正确使用JWTtoken#,c#,jwt,claims,C#,Jwt,Claims,我正在使用JWTToken玩游戏,无法使它们正常工作。 我正在用它。 我知道代码很混乱,但只是为了显示我正在尝试做什么。 问题是,我希望JwtTokenHandler由于生命周期而无法通过验证 var key = "5A0AB091-3F84-4EC4-B227-0834FCD8B1B4"; var domain = "http://localhost"; var allowedAudience = "http://localhost"; var signatureAlgorithm = "ht

我正在使用JWTToken玩游戏,无法使它们正常工作。 我正在用它。 我知道代码很混乱,但只是为了显示我正在尝试做什么。 问题是,我希望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);
}
var key=“5A0AB091-3F84-4EC4-B227-0834FCD8B1B4”;
变量域=”http://localhost";
var allowedAudience=”http://localhost";
var signatureAlgorithm=”http://www.w3.org/2001/04/xmldsig-more#hmac-sha256”;
var算法=”http://www.w3.org/2001/04/xmlenc#sha256";
var issuer=“self”;
var securityKey=System.Text.Encoding.Unicode.GetBytes(key);
var InMemorySymetricSecurityKey=新的InMemorySymetricSecurityKey(securityKey);
var now=DateTime.UtcNow;
var expiry=now.AddSeconds(1);
var tokenHandler=new JwtSecurityTokenHandler();
var claimsList=新列表()
{
新索赔(ClaimTypes.Name,“用户”),
新索赔(ClaimTypes.Webpage,允许观众),
新声明(ClaimTypes.Uri,域),
新声明(ClaimTypes.Expiration、expiry.Ticks.ToString())
};
var roles=new List(){“admin”};
claimsList.AddRange(roles.Select(role=>newclaim(ClaimTypes.role,role));
var标识=新的GenericEntity(“用户”);
var tokenDescriptor=新的SecurityTokenDescriptor
{
主题=新的索赔实体(身份、索赔清单),
TokenIssuerName=issuer,
AppliesToAddress=允许的观众,
寿命=新的寿命(现在,到期),
SigningCredentials=新的签名凭证(InMemorySymetricSecurityKey、signatureAlgorithm、digestAlgorithm),
};
var token=tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
var validationParameters=new-TokenValidationParameters()
{
ValidisUser=发行人,
有效性=允许的观众,
IssuerSigningToken=新的BinarySecretSecurityToken(securityKey)
};
《睡眠》(2000年);
尝试
{
SecurityToken SecurityToken;
ValidateToken(令牌、validationParameters、out securityToken);
控制台。写入线(“OK”);
}
捕获(例外e)
{
WriteLine(“错误{0}”,e.Message);
}
既然我等了2秒钟,这不是应该失败吗? 如果我将ValidationTokenParameter的颁发者更改为“x”,它将失败。…

找到了该问题。 验证参数的默认时钟偏差为5分钟

/// <summary>
/// Default for the clock skew.
/// 
/// </summary>
/// 
/// <remarks>
/// 300 seconds (5 minutes).
/// </remarks>
public static readonly TimeSpan DefaultClockSkew;
//
///时钟偏移的默认值。
/// 
/// 
/// 
/// 
///300秒(5分钟)。
/// 
公共静态只读TimeSpan DefaultClockSkew;
如果将其设置为0,则可以执行此操作。
仍然不明白为什么偏斜是5分钟,如果我把到期时间设定在某个点上

这肯定有效

TimeSpan.FromSeconds(0)将时钟偏移时间重置为零


@dariogriffo,@Mitklantekutli实际上你是如何将其设置为0的?我试过这样做:tokenHandler.Configuration.MaxClockSkew=new TimeSpan(0,0,0);但不工作。我在TokenValidationParameters中设置了ClockSkew属性,我不使用配置。我使用代码var validationParameters=new-TokenValidationParameters(){…ClockSkew=new-TimeSpan(0)}@dariogriffo我会使用TimeSpan.Zero来获得更简洁的方法,但这只是吹毛求疵!谢谢你的信息。看看它对我是否有效:)@thenator你说得对,谢谢你的建议只是尝试和调试:请看一看是否有正确的实现。@FabianVilers该实现尚未完成,isse的验证正在引发异常。
TokenValidationParameters parameters = new TokenValidationParameters()
{
  RequireExpirationTime = true,
  ValidateIssuer = false,
  ValidateAudience = false,
  ClockSkew= TimeSpan.FromSeconds(0)
};