我有以下代码:
下面这行代码可以正常读取令牌,但是在第二个方法中读取时会抛出异常。
我已经验证了这两个字符串是相同的,但当我想要验证令牌时,它却停止工作,我非常困惑,不知道我做错了什么。请问有什么想法吗?
编辑:
异常
public async Task<LoginResult> GenerateJwtTokenAsync(string email, string password)
{
LoginResult loginResult = await _membershipProvider.Login(email, password);
if (loginResult.Succeeded)
{
var symmetricKey = Convert.FromBase64String(Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(loginResult.Claims),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
};
var stoken = _tokenHandler.CreateToken(tokenDescriptor);
var token = _tokenHandler.WriteToken(stoken);
// Check token here to see if it works
var jwtToken = _tokenHandler.ReadToken(token) as JwtSecurityToken;
loginResult.JwtToken = token;
}
return loginResult;
}
public ClaimsPrincipal ValidateJwtToken(string tokenString)
{
ClaimsPrincipal principal;
try
{
var jwtToken = _tokenHandler.ReadToken(tokenString) as JwtSecurityToken;
if (jwtToken == null)
{
principal = null;
}
else
{
var symmetricKey = Convert.FromBase64String(Secret);
var validationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
};
SecurityToken securityToken;
principal = _tokenHandler.ValidateToken(tokenString, validationParameters, out securityToken);
}
}
catch (Exception ex)
{
principal = null;
}
return principal;
}
下面这行代码可以正常读取令牌,但是在第二个方法中读取时会抛出异常。
// Check token here to see if it works
var jwtToken = _tokenHandler.ReadToken(token) as JwtSecurityToken
我已经验证了这两个字符串是相同的,但当我想要验证令牌时,它却停止工作,我非常困惑,不知道我做错了什么。请问有什么想法吗?
编辑:
异常
"IDX10729: Unable to decode the header 'header' as Base64Url encoded string. jwtEncodedString: 'Token here'."
堆栈跟踪:
at System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[] tokenParts, String rawData)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ReadJwtToken(String token)
at AuthService.ValidateJwtToken(String tokenString) in AuthService.cs:line 57
jwtEncodedString: 'Token here'
似乎不太适合。这是您自己更改的有效令牌,还是无效的?即使您认为它们相同,也可能存在两个不同的字符串。我建议加入更多日志记录。 - Jon Skeet