You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.2 KiB
C#

2 years ago
using System.IdentityModel.Tokens.Jwt;
using DS.Module.Core;
using DS.Module.Core.Extensions;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace DS.Module.UserModule;
public static class UserExtensions
{
public static UserInfo GetUserInfo(this HttpRequest request)
{
if (request.HttpContext.User.Claims is null)
{
return null;
}
var json = request.HttpContext.User.Claims;
//获取上传token可自定义扩展
var token = request.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
?? request.HttpContext.Request.Headers["X-Token"].FirstOrDefault()
?? request.HttpContext.Request.Query["Token"].FirstOrDefault()
?? request.HttpContext.Request.Cookies["Token"];
// token校验
var jwtHandler = new JwtSecurityTokenHandler();
var userInfo = new UserInfo();
if (token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
{
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
userInfo = JsonConvert.DeserializeObject<UserInfo>(jwtToken.Claims.First().Value) ;
}
return userInfo;
}
}