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

     
     
  • 相关阅读:
    TC配置文件WCMD.INI详解,只能在ini重修改的配置
    Source Insight中的多行注释
    ACE_Timer_Heap_T定时器
    什么是代理服务器
    太阳能传感器目前主要故障问题解决方案
    source insight中文显示和处理
    C#3.0新特性小结(2)
    .NET中事务操作小结(1)
    常用的正则表达式收藏版
    几种流行的Ajax开发框架比较
  • 原文地址:https://www.cnblogs.com/qqhfeng/p/14208111.html
Copyright © 2011-2022 走看看