zoukankan      html  css  js  c++  java
  • .NetCore3.1 使用JWT认证授权时获取当前请求的用户名

    在netcore5.0里,这样不行了

    应该编入用户名,最后用HttpContext.User.Identity获取(从claim获取)

    //======================================================================================================================================================================

    最近使用JWT来给WebApi进行授权认证,在项目中使用 HttpContext.User.Identity.Name 获取当前登录的用户名一直获取不到,以往都是这样获取,这个问题查了很久都没找到相关资料

    特此记录一下,避坑。

    在JWT生成Token时一定要加入ClaimTypes.Name这样才能获取到用户名

    复制代码
    public static string GetToken(string userName)
            {
                var claims = new List<Claim>();
                claims.AddRange(new[] {
                    new Claim(ClaimTypes.Name, userName),
                    new Claim(JwtRegisteredClaimNames.Sub, userName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
                });
                var tokenManagement = UtilConfHelper.GetTokenManagement();
                DateTime now = DateTime.Now;
                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: tokenManagement.Issuer,
                    audience: tokenManagement.Audience,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromMinutes(tokenManagement.AccessExpiration)),
                    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenManagement.Secret)), SecurityAlgorithms.HmacSha256)
                );
                string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                return token;
            }
    复制代码

     获取就使用 Response.HttpContext.User.Identity.Name 获取userName

     
     
  • 相关阅读:
    归并排序,树状数组 两种方法求逆序对
    volley源代码解析(六)--HurlStack与HttpClientStack之争
    what&#39;s new in vc2015
    [ajax 学习笔记] ajax初试
    安卓项目开发实战(1)--首页顶部菜单BAR实现
    eclipse下Tomcat7.0启动奔溃问题
    伸缩--也可用于tabs
    怎样提高团队管理能力8
    mysql查询今天,昨天,近7天,近30天,本月,上一月数据
    SDSoC使用体验
  • 原文地址:https://www.cnblogs.com/qqhfeng/p/14208111.html
Copyright © 2011-2022 走看看