zoukankan      html  css  js  c++  java
  • .net core 在代码中使用jwt token中的用户信息

        基本思路,在过滤器中将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;
        }
  • 相关阅读:
    天兔(Lepus)监控系统慢查询分析平台安装配置
    java怎么用一行代码初始化ArrayList
    yum命令不能使用的相关错误
    【转】Android APP性能测试
    【转】Java经典问题算法大全
    [转]java中Map,List与Set的区别
    关于编写性能高效的javascript事件的技术
    ESLint 规则
    HTML5 使用application cache 接口实现离线数据缓存
    qunit 前端脚本测试用例
  • 原文地址:https://www.cnblogs.com/KQNLL/p/13736798.html
Copyright © 2011-2022 走看看