基本思路,在过滤器中将token中的用户信息存放到context.HttpContext.User或者Thread.CurrentPrincipal中。使用时通过扩展方法或者静态方法获取用户信息。
存放到context.HttpContext.User中
services.AddHttpContextAccessor();
public class TokenActionFilter1: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var test = context.HttpContext.Request.Path;
string bearer = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
if (string.IsNullOrEmpty(bearer) || !bearer.Contains("Bearer")) return;
string[] jwt = bearer.Split(' ');
var tokenObj = new JwtSecurityToken(jwt[1]);
var claimsIdentity = new ClaimsIdentity(tokenObj.Claims);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
context.HttpContext.User = claimsPrincipal;
}
}
public static int GetUserId(this ClaimsPrincipal claimsPrincipal)
{
try
{
var claim = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == "UserId");
if (claim == null || string.IsNullOrEmpty(claim.Value))
{
return 0;
}
return int.Parse(claim.Value);
}
catch
{
return 0;
}
}
//_httpContextAccessor为IHttpContextAccessor通过构造函数注入
[HttpGet("get1")]
[TokenActionFilter1]
public async Task<int> Get1()
{
var id = _httpContextAccessor.HttpContext.User.GetUserId();
return id;
}
存放到Thread.CurrentPrincipal中
public class TokenActionFilter2 : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var test = context.HttpContext.Request.Path;
string bearer = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
if (string.IsNullOrEmpty(bearer) || !bearer.Contains("Bearer")) return;
string[] jwt = bearer.Split(' ');
var tokenObj = new JwtSecurityToken(jwt[1]);
var claimsIdentity = new ClaimsIdentity();
claimsIdentity.AddClaims(tokenObj.Claims);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
Thread.CurrentPrincipal = claimsPrincipal;
}
}
public static int GetUserId()
{
try
{
var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
var claim = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == "UserId");
if (claim == null || string.IsNullOrEmpty(claim.Value))
{
return 0;
}
return int.Parse(claim.Value);
}
catch
{
return 0;
}
}
[HttpGet]
[TokenActionFilter2]
public async Task<int> Get2()
{
var id = TokenExtension2.GetUserId();
return id;
}