All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
42 lines
1.1 KiB
C#
42 lines
1.1 KiB
C#
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.Text;
|
|
using System.Security.Claims;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
using agologumApi.Models;
|
|
|
|
public class JwtService {
|
|
|
|
private readonly IConfiguration config_;
|
|
|
|
public JwtService(IConfiguration config) { // why the heck does c# not have initializer lists ?
|
|
config_ = config;
|
|
}
|
|
|
|
public string? GenerateJwt(User user) {
|
|
|
|
string? jwtKey = config_["Jwt:Key"];
|
|
if(jwtKey == null) return null;
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
|
|
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
// not too sure
|
|
var claims = new[] {
|
|
new Claim(ClaimTypes.Name, user.Name),
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
|
|
};
|
|
|
|
var token = new JwtSecurityToken(
|
|
claims: claims,
|
|
expires: DateTime.UtcNow.AddHours(2), // will add a refresher later
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
|
|
}
|
|
|
|
|
|
} |