Last active
June 2, 2021 11:39
-
-
Save utarn/4d108faf3dfefd2526aedea06c19c5e6 to your computer and use it in GitHub Desktop.
ASP.NET Core JWT Function part 1/2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Configuration; | |
using Microsoft.IdentityModel.Tokens; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Security.Claims; | |
using Microsoft.AspNetCore.Authorization; | |
public TokenController(IConfiguration config, ApplicationDbContext dbContext) | |
{ | |
_config = config; | |
_dbContext = dbContext; | |
} | |
public IActionResult CreateToken([FromBody]LoginCredential login) | |
{ | |
IActionResult response = Unauthorized(); | |
if (login != null) | |
{ | |
var user = Authenticate(login); | |
if (user != null) | |
{ | |
var tokenString = BuildToken(user); | |
response = Ok(new { Token = tokenString }); | |
} | |
} | |
return response; | |
} | |
private string BuildToken(Client user) | |
{ | |
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); | |
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | |
var claims = new List<Claim> | |
{ | |
new Claim(ClaimTypes.NameIdentifier, user.Id), | |
new Claim(ClaimTypes.Name, user.Name), | |
new Claim(ClaimTypes.Version, "1.0") | |
}; | |
var token = new JwtSecurityToken(_config["Jwt:Issuer"], | |
_config["Jwt:Issuer"], | |
claims, | |
notBefore: DateTime.UtcNow, | |
expires: DateTime.UtcNow.AddDays(1), | |
signingCredentials: creds); | |
return new JwtSecurityTokenHandler().WriteToken(token); | |
} | |
private Client Authenticate(LoginCredential login) | |
{ | |
var client = _dbContext.Clients.FirstOrDefault(c => c.Id == login.ClientId && c.Secret == login.ClientSecret); | |
return client; | |
} | |
public class LoginCredential | |
{ | |
public string ClientId { get; set; } | |
public string ClientSecret { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cool !