Skip to content

Instantly share code, notes, and snippets.

@utarn
Last active June 2, 2021 11:39
Show Gist options
  • Save utarn/4d108faf3dfefd2526aedea06c19c5e6 to your computer and use it in GitHub Desktop.
Save utarn/4d108faf3dfefd2526aedea06c19c5e6 to your computer and use it in GitHub Desktop.
ASP.NET Core JWT Function part 1/2
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; }
}
@KB-TH
Copy link

KB-TH commented Jun 2, 2021

cool !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment