✨
This commit is contained in:
54
StopShopping.Services/Implementions/ClaimsService.cs
Normal file
54
StopShopping.Services/Implementions/ClaimsService.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using StopShopping.EF.Models;
|
||||
using StopShopping.Services.Models;
|
||||
|
||||
namespace StopShopping.Services.Implementions;
|
||||
|
||||
public class ClaimsService : IClaimsService
|
||||
{
|
||||
public ClaimsService(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public ClaimsIdentity BuildIdentity(User user)
|
||||
{
|
||||
var claimsIdentity = new ClaimsIdentity(
|
||||
[
|
||||
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Name, user.Account),
|
||||
new Claim(JwtRegisteredClaimNames.Nickname, user.NickName),
|
||||
new Claim(ClaimTypes.Role, SystemRoles.User.ToString()),
|
||||
]);
|
||||
|
||||
return claimsIdentity;
|
||||
}
|
||||
|
||||
public ClaimsIdentity BuildAdminIdentity(Administrator admin)
|
||||
{
|
||||
var claimsIdentity = new ClaimsIdentity(
|
||||
[
|
||||
new Claim(JwtRegisteredClaimNames.Sub, admin.Id.ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Name, admin.Account),
|
||||
new Claim(JwtRegisteredClaimNames.Nickname, admin.NickName),
|
||||
new Claim(ClaimTypes.Role, SystemRoles.Admin.ToString()),
|
||||
]);
|
||||
|
||||
return claimsIdentity;
|
||||
}
|
||||
|
||||
public int GetCurrentUserId()
|
||||
{
|
||||
var currUserId = _httpContextAccessor.HttpContext
|
||||
?.User.FindFirstValue(JwtRegisteredClaimNames.Sub);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(currUserId))
|
||||
throw new InvalidOperationException("在错误的位置获取当前登录用户");
|
||||
|
||||
return Convert.ToInt32(currUserId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user