Yes, you can.
The logic process is in this method:
Step 1: GetUserClaims
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
Into GetClaimsIdentity you will
private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
return await Task.FromResult<ClaimsIdentity>(null);
var userToVerify = await _userManager.FindByNameAsync(userName);
if (userToVerify == null) {
userToVerify = await _userManager.FindByEmailAsync(userName);
if (userToVerify == null) {
return await Task.FromResult<ClaimsIdentity>(null);
}
}
// check the credentials
if (await _userManager.CheckPasswordAsync(userToVerify, password))
{
_claims = await _userManager.GetClaimsAsync(userToVerify);
return await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userToVerify.UserName, userToVerify.Id, _claims));
}
// Credentials are invalid, or account doesn't exist
return await Task.FromResult<ClaimsIdentity>(null);
}
Step 2: Group all user claims you need add to the token - Use System.Security.Claims
public ClaimsIdentity GenerateClaimsIdentity(string userName, string id, IList<Claim> claims)
{
claims.Add(new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, id));
// If your security is role based you can get then with the RoleManager and add then here as claims
// Ask here for all claims your app need to validate later
return new ClaimsIdentity(new GenericIdentity(userName, "Token"), claims);
}
Step 3: Then back on your method you have to generate and return the JWT Token
jwt = await jwtFactory.GenerateEncodedToken(userName, identity);
return new OkObjectResult(jwt);
To generate token do something like this:
public async Task<string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
{
List<Claim> claims = new List<Claim>();
//Config claims
claims.Add(new Claim(JwtRegisteredClaimNames.Sub, userName));
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()));
claims.Add(new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));
//End Config claims
claims.AddRange(identity.FindAll(Helpers.Constants.Strings.JwtClaimIdentifiers.Roles));
claims.AddRange(identity.FindAll("EspecificClaimName"));
// Create the JWT security token and encode it.
var jwt = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
notBefore: _jwtOptions.NotBefore,
expires: _jwtOptions.Expiration,
signingCredentials: _jwtOptions.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
return encodedJwt;
}
There are many ways to do this.
The most common is:
Validate Identity User --> Get User identifiers --> Generate and Return Token Based on Identifiers --> Use Authorization for endpoints
Hope this help