mirror of
https://github.com/azaion/admin.git
synced 2026-04-22 22:16:33 +00:00
53 lines
1.8 KiB
C#
53 lines
1.8 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Azaion.Common.Configs;
|
|
using Azaion.Common.Entities;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Azaion.Services;
|
|
|
|
public interface IAuthService
|
|
{
|
|
Task<User?> GetCurrentUser();
|
|
string CreateToken(User user);
|
|
}
|
|
|
|
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig, IUserService userService) : IAuthService
|
|
{
|
|
private string? GetCurrentUserEmail()
|
|
{
|
|
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
|
return claims?[ClaimTypes.Name].Value;
|
|
}
|
|
|
|
public async Task<User?> GetCurrentUser()
|
|
{
|
|
var email = GetCurrentUserEmail();
|
|
return await userService.GetByEmail(email);
|
|
}
|
|
|
|
public string CreateToken(User user)
|
|
{
|
|
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Value.Secret));
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity([
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, user.Email),
|
|
new Claim(ClaimTypes.Role, user.Role.ToString())
|
|
]),
|
|
Expires = DateTime.UtcNow.AddHours(jwtConfig.Value.TokenLifetimeHours),
|
|
Issuer = jwtConfig.Value.Issuer,
|
|
Audience = jwtConfig.Value.Audience,
|
|
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature)
|
|
};
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
} |