Reputation: 2442
I'm working on a small side-project API and I wanted to implement JWT authentication. I already made some API with JWT and always made custom implementation and validation.
This time, I wanted to use Identity/Entity Framework to go faster and to use the tools that are already made for me.
While doing the GenerateToken method and looking through the internet, I noticed that a lot of the tables created by IdentityFramework are not used. And I got interested in AspNetUserToken
.
I noticed that instead of
private object GenerateToken(IdentityUser user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(ApiConfig.JwtSecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Email, user.Email),
}),
Expires = DateTime.UtcNow.AddSeconds(double.Parse(ApiConfig.JwtExp)), //TODO: Try parse
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Audience = ApiConfig.JwtAudience,
Issuer = ApiConfig.JwtIssuer
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
Which I used to generate a new JWT token, add the claims, issuer, audience, etc... Could maybe be replaced by this :
//Removes existing token
_userManager.RemoveAuthenticationTokenAsync(user, "lboard", "login");
//Creates a new one
var newToken = await _userManager.GenerateUserTokenAsync(user, "lboard", "login");
//Set the new token for the user
await _userManager.SetAuthenticationTokenAsync(user, "lboard", "login", newToken);
I would like to know what are the differences between the two methods, and if there are any benefits of using a custom implementation or if I'm better off with the IdentityFramework one.
Upvotes: 2
Views: 1510
Reputation: 860
The GenerateUserTokenAsync
methods is used internally by other UserManager
methods like GenerateChangeEmailTokenAsync
, GenerateChangePhoneNumberTokenAsync
and so on. REF
In order to use more abstract GenerateUserTokenAsync
, you must provide a token provider that actually generates the token. Since you don't have any default token providers for a JWT access token, you would still have to write the logic yourself and register your custom token provider and then you could use the GenerateUserTokenAsync
method.
You would still need to write the JWT logic by yourself, incude claims etc, but with an added overhead.
Upvotes: 3