add roles to jwt claims
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:
@@ -97,7 +97,7 @@ public class AuthController : ControllerBase {
|
||||
|
||||
User? user = await jwt_.GetUser(storedToken.UserId);
|
||||
if(user == null) return NotFound();
|
||||
string? newAccessToken = jwt_.GenerateJwt(user);
|
||||
string? newAccessToken = await jwt_.GenerateJwt(user);
|
||||
if(newAccessToken == null) return NotFound();
|
||||
string newRefreshToken = jwt_.GenerateRefreshToken();
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ using System.Text;
|
||||
using System.Security.Claims;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
using agologumApi.Models;
|
||||
|
||||
@@ -12,13 +13,15 @@ public class JwtService {
|
||||
|
||||
private readonly IConfiguration config_;
|
||||
private readonly AppDbContext db_;
|
||||
private readonly UserManager<User> userManager_;
|
||||
|
||||
public JwtService(IConfiguration config, AppDbContext db) { // why the heck does c# not have initializer lists ?
|
||||
public JwtService(IConfiguration config, AppDbContext db, UserManager<User> userManager) { // why the heck does c# not have initializer lists ?
|
||||
config_ = config;
|
||||
db_ = db;
|
||||
userManager_ = userManager;
|
||||
}
|
||||
|
||||
public string? GenerateJwt(User user) {
|
||||
public async Task<string?> GenerateJwt(User user) {
|
||||
|
||||
string? jwtKey = config_["Jwt:Key"];
|
||||
if(jwtKey == null) return null;
|
||||
@@ -28,12 +31,16 @@ public class JwtService {
|
||||
|
||||
if(user.UserName == null) return null;
|
||||
|
||||
var roles = await userManager_.GetRolesAsync(user);
|
||||
|
||||
// not too sure
|
||||
var claims = new[] {
|
||||
var claims = new List<Claim> {
|
||||
new Claim(ClaimTypes.Name, user.UserName),
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
|
||||
};
|
||||
|
||||
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: "agologum",
|
||||
audience: "agologum",
|
||||
|
||||
Reference in New Issue
Block a user