[User.Claims在用户仍然登录时部署应用程序后为空

问题描述 投票:0回答:1

我有一个使用身份声明(带有JWT令牌授权)的aspnet核心Web应用程序。我的令牌设置已过期2天。

正常的登录,身份验证以及接收/发送令牌的过程都很好。

我遇到的问题是当我将应用程序部署到IIS且用户仍然登录时,User.Claims属性为null。 User对象没有值。仅当他们注销然后重新登录时,它才会刷新。

我唯一想到的想法是检测声明是否为空并重定向到登录名,但这并不理想,因为它们可能从前一天开始不断更新信息,只是使提交失败。

编辑(代码示例):

            ApplicationUser appUser = _userManager.FindByNameAsync(login).Result;

            var displayName = appUser.ToDisplayName();

            var claimsIdentity = new ClaimsIdentity(userClaims, "Bearer");
            claimsIdentity.AddClaim(new Claim("displayName", displayName));  

            await _userManager.AddClaimAsync(appUser, new Claim("id", appUser.Id)); // server claim               
            await _userManager.AddClaimAsync(appUser, new Claim("displayName", displayName)); // server claim
            await _userManager.UpdateAsync(appUser);

            // return token to client.
            var expires = DateTime.UtcNow.AddMinutes(2880);
            var token = GetJwtToken(expires, claimsIdentity);

            return new TokenDTO()
            {
                id_token = token,
                tokenExpires = expires,
                displayName = displayName,
                authenticated = true,
                username = appUser.UserName,
                roles = applicationRoles // roles is for client-side nav authorization
            };

GetJwtToken

    private string GetJwtToken(DateTime? expires, ClaimsIdentity identity)
    {
        var handler = new JwtSecurityTokenHandler();
        var securityToken = handler.CreateToken(new 
     SecurityTokenDescriptor()
        {
            Issuer = _tokenOptions.Issuer,
            Audience = _tokenOptions.Audience,
            SigningCredentials = _tokenOptions.SigningCredentials,
            Subject = identity,
            Expires = expires,
            NotBefore = DateTime.UtcNow.AddMinutes(-1)
        });

        return handler.WriteToken(securityToken);
    }

给用户打电话:

    [HttpPut]
    public IActionResult Put([FromBody]OrderProcessUpdateDTO 
     orderProcessUpdateDTO)
    {
          // claims is sometimes null here
          var currentUserId = User.Claims.Single(x => x.Type == 
          nameof(CustomClaimType.id)).Value;

        ...

      }

我有一个使用身份声明(带有JWT令牌授权)的aspnet核心Web应用程序。我的令牌设置已过期2天。登录,验证...的正常过程...

asp.net-core asp.net-identity jwt claims-based-identity
1个回答
0
投票

我遇到了同样的问题。我有一个通过依赖项注入接收IHttpContextAccessor的类,它有时会报告用户并正确声明。几秒钟后,它返回一个没有身份,没有声明的用户。几秒钟后,它再次返回正确的值。

© www.soinside.com 2019 - 2024. All rights reserved.