add auth files
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 9s
This commit is contained in:
42
api/src/Services/JwtService.cs
Normal file
42
api/src/Services/JwtService.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user