I’m trying to understand the code block below. Everything is fine until the third argument of the tokenHandler.ValidateToken(...) method which is out SecurityToken validatedToken.
I checked the docs but could not find out much about that last argument. How does it work?
And what happens to tokenHandler.ValidateToken(...)? we are not assigning its return value to anything it looks like it just stays there and idk.
Could you make these clear for me?
private void attachUserToContext(HttpContext context, IUserService userService, string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
tokenHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
// set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
ClockSkew = TimeSpan.Zero
}, out SecurityToken validatedToken);
var jwtToken = (JwtSecurityToken)validatedToken;
var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
// attach user to context on successful jwt validation
context.Items["User"] = userService.GetById(userId);
}
catch
{
// do nothing if jwt validation fails
// user is not attached to context so request won't have access to secure routes
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The method ValidateToken() takes the received token as a String, validates the token according to the TokenValidationParameters and creates an object of type SecurityToken, which is returned via the out parameter.
In the next line this object is casted to the type JwtSecurityToken
var jwtToken = (JwtSecurityToken)validatedToken;
and then parsed
var userId = int.Parse(...)
to get the userId and finally the HttpContext context
get’s populated
context.Items["User"] = userService.GetById(userId);
with the user information. If validation is successful, you have the user information available via the httpContext.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0