如何更改 Angular 页面刷新后的令牌过期时间?

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

登录后,我将生成一个令牌并将其保存在存储会话中。令牌的到期时间是 8 分钟,一切都很好。我遇到的问题是,当我上传照片时,例如页面会刷新,并且令牌在 8 分钟后仍然过期,但我想要的是刷新时我想将令牌过期时间重置回 8 分钟或生成新令牌。如何做到这一点?

在登录中我正在 API 中生成令牌:

loginRes.Token = CreateJWT(user);

private string CreateJWT(User user)
    {
        var secretKey = configuration.GetSection("AppSettings:Key").Value;
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

        var claims = new Claim[] {
            new Claim(ClaimTypes.Name, user.Username),
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
        };

        var signingCredentials = new SigningCredentials(
                                key, SecurityAlgorithms.HmacSha256Signature);

        var tokenDescriptor = new SecurityTokenDescriptor{
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.UtcNow.AddMinutes(8),
            SigningCredentials = signingCredentials
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

上面写着

Expires = DateTime.UtcNow.AddMinutes(8),

现在在前端我有一个上传照片的页面,当我这样做时,页面会刷新以显示上传的照片

   initializeFileUploader()
  {
      this.uploader = new FileUploader({
        url: this.baseUrl + '/familydocuments/add/photo/' + this.thefolder,
        authToken: 'Bearer ' + sessionStorage.getItem('token'),
        isHTML5: true,
        removeAfterUpload: true,
        autoUpload: true,
        maxFileSize: this.maxAllowedFileSize

      });

      this.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
      };

      this.uploader.onSuccessItem = (item,respose,status, header) => 
      {
          if (respose)
          {
              const photo = JSON.stringify(respose);
              const photos = JSON.parse(photo);
              this.allPhotos.push(photos);
          }

        // setTimeout(()=>
        // {
        //   window.location.reload();
        //   this.router.navigate(["familydocuments"])
        // }, 15000);
      };
  }

  );

我需要生成新令牌或在不重新加载页面的情况下显示照片,该怎么做?

token reload angular17
1个回答
0
投票
  1. 当您刷新页面并重新加载应用程序时,您需要检查一些事项:
  • 会话存储中是否有可用的令牌。
  • 这个token还没有过期吗
  • 此令牌是颁发给您的用户帐户还是其他用户?

如果全部回答“是”,则使用会话存储中的令牌进行 http 事务。

  1. 在令牌即将过期时刷新您的令牌。当您从会话存储中接收或读取令牌时,您需要根据过期时间运行一些作业,以向 API 发送新请求并获取新令牌。有些人只是在令牌到期前 1 分钟运行
    setTimeout
    。当你收到新的令牌时,然后在其他地方更新(会话存储等)
© www.soinside.com 2019 - 2024. All rights reserved.