move jwt authentication code from startup in middleware core net code example
Example 1: c# asp.net mvc core implementing jwt
private string GenerateJSONWebToken(UserModel userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),
new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),
new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Example 2: asp net core identity bearer token authentication example
[HttpPost]
public async Task<IActionResult> AccessToken([FromForm]string code, [FromForm]string grant_type, [FromForm]string redirect_uri, [FromForm]string client_id, [FromForm]string client_secret)
{
if (grant_type != "authorization_code")
{
return Redirect(redirect_uri + "?error=unsupported_response_type");
}
if (!clientValidator.Valid(client_id, client_secret))
{
return Redirect(redirect_uri + "?error=access_denied");
}
string previous_uri = codeAndURIStorage.Load(code);
string user = codeAndUserStorage.Load(code);
codeAndURIStorage.Delete(code);
codeAndUserStorage.Delete(code);
if (redirect_uri != previous_uri)
{
return BadRequest("'redirect_uri' was inconsistent.");
}
if (user == null)
{
return BadRequest("Couldn't find user associated with the given code.");
}
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenOptions:Key"]))
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user)
}),
Expires = DateTime.UtcNow.AddYears(2),
Issuer = "MyWebsite.com",
Audience = "MyWebsite.com",
SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var access_token = tokenHandler.WriteToken(token);
return Ok(new { access_token, token_type="bearer" });
}