You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中页面刷新后如何重置Token过期时间?

解决Token过期重置或无刷新图片上传问题

方案一:页面刷新时生成新Token

后端修改:新增Token刷新接口

  1. 添加接口验证旧Token有效性,生成并返回新Token:
[HttpPost("refresh-token")]
public IActionResult RefreshToken([FromBody] string oldToken)
{
    try
    {
        var secretKey = configuration.GetSection("AppSettings:Key").Value;
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
        
        var tokenHandler = new JwtSecurityTokenHandler();
        tokenHandler.ValidateToken(oldToken, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = key,
            ValidateIssuer = false,
            ValidateAudience = false,
            ClockSkew = TimeSpan.Zero
        }, out SecurityToken validatedToken);

        var jwtToken = (JwtSecurityToken)validatedToken;
        var username = jwtToken.Claims.First(x => x.Type == ClaimTypes.Name).Value;
        var userId = int.Parse(jwtToken.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value);
        
        var user = new User { Username = username, Id = userId };
        var newToken = CreateJWT(user);
        
        return Ok(new { Token = newToken });
    }
    catch
    {
        return Unauthorized("无效的Token");
    }
}
  1. 确保CreateJWT方法可被该接口调用(如设置为public)。

前端修改:页面加载时刷新Token

在页面初始化时调用刷新接口,更新Token及上传器配置:

window.onload = async function() {
    const oldToken = sessionStorage.getItem('token');
    if (oldToken) {
        try {
            const response = await fetch(`${this.baseUrl}/refresh-token`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(oldToken)
            });
            if (response.ok) {
                const data = await response.json();
                sessionStorage.setItem('token', data.Token);
                if (this.uploader) {
                    this.uploader.options.authToken = 'Bearer ' + data.Token;
                }
            }
        } catch (error) {
            console.error('刷新Token失败:', error);
            window.location.href = '/login';
        }
    }
};

initializeFileUploader() {
    const token = sessionStorage.getItem('token');
    this.uploader = new FileUploader({
        url: this.baseUrl + '/familydocuments/add/photo/' + this.thefolder,
        authToken: 'Bearer ' + token,
        isHTML5: true,
        removeAfterUpload: true,
        autoUpload: true,
        maxFileSize: this.maxAllowedFileSize
    });
    
    this.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
    };
    
    this.uploader.onSuccessItem = (item, response, status, header) => {
        if (response) {
            const photo = JSON.parse(response);
            this.allPhotos.push(photo);
        }
    };
}

方案二:无刷新上传并显示图片

优化前端上传逻辑,直接展示图片无需页面刷新:

前端修改:上传成功后直接渲染图片

initializeFileUploader() {
    const token = sessionStorage.getItem('token');
    this.uploader = new FileUploader({
        url: this.baseUrl + '/familydocuments/add/photo/' + this.thefolder,
        authToken: 'Bearer ' + token,
        isHTML5: true,
        removeAfterUpload: true,
        autoUpload: true,
        maxFileSize: this.maxAllowedFileSize
    });
    
    this.uploader.onAfterAddingFile = (file) => {
        file.withCredentials = false;
    };
    
    this.uploader.onSuccessItem = (item, response, status, header) => {
        if (response) {
            const photo = JSON.parse(response);
            this.allPhotos.push(photo);
            // 原生JS示例:直接创建img元素添加到页面容器
            // const img = document.createElement('img');
            // img.src = photo.url;
            // document.getElementById('photo-container').appendChild(img);
        }
    };
}

上传完成后图片会直接渲染到页面,无需刷新,避免Token过期时间问题。

注意事项

  • 方案一的刷新接口需严格验证Token,防止恶意调用。
  • 方案二需确保后端返回的图片URL可直接访问(如配置静态资源路径)。

内容的提问来源于stack exchange,提问作者taleen wahdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 23:15:35