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(jwtToken.Claims.First().Value) ; } return userInfo; } }