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

Spring Boot JWT认证后如何携带Token重定向至Admin接口

解决登录后重定向并携带JWT Token的问题

核心问题说明

浏览器通过location.href或window.location进行页面跳转时,无法手动添加自定义请求头(比如Authorization),这是浏览器的安全限制导致的。直接跳转的方式没法满足你的需求,可通过以下两种思路实现:


方案1:通过Fetch请求获取/admin页面内容并渲染

如果/api/admin返回的是HTML页面,你可以先通过Fetch请求带上Token获取页面内容,再替换当前页面的HTML:

修改登录成功后的代码:

.then(data => {
    const token = data.token; 
    localStorage.setItem('jwttoken', token);
    // 用Fetch请求/admin页面,携带Token
    fetch('http://localhost:8080/api/admin', {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    })
    .then(response => {
        if (response.ok) {
            return response.text(); // 获取HTML内容
        }
        throw new Error('Failed to access admin page');
    })
    .then(html => {
        document.open();
        document.write(html);
        document.close(); // 替换当前页面内容
    })
    .catch(err => {
        console.error('Access admin failed:', err);
        document.getElementById('error-message').innerText = 'Failed to enter admin page';
    });
})

方案2:重定向到前端admin页面,加载时自动携带Token

如果/api/admin是返回JSON数据的接口,或者你希望做真正的页面跳转,可以先跳转到前端的admin页面,再在该页面加载时从localStorage取出Token请求后端接口:

步骤1:登录成功后重定向到前端admin页面

修改登录成功的代码:

.then(data => {
    const token = data.token; 
    localStorage.setItem('jwttoken', token);
    // 跳转到前端的admin页面(比如/admin.html)
    window.location.href = '/admin.html';
})

步骤2:创建admin.html页面,加载时请求后端接口

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Page</title>
</head>
<body>
    <h2>Admin Dashboard</h2>
    <div id="admin-content"></div>

    <script>
        const token = localStorage.getItem('jwttoken');
        if (!token) {
            // 无Token则跳回登录页
            window.location.href = '/login.html';
            return;
        }

        // 请求后端/admin接口
        fetch('http://localhost:8080/api/admin', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            }
        })
        .then(response => response.json())
        .then(data => {
            // 将数据渲染到页面
            document.getElementById('admin-content').textContent = JSON.stringify(data, null, 2);
        })
        .catch(err => {
            console.error('Error:', err);
            alert('Failed to load admin data');
            localStorage.removeItem('jwttoken');
            window.location.href = '/login.html';
        });
    </script>
</body>
</html>

额外提示

  • 若后端/api/admin返回HTML,方案1更直接;若为API接口,方案2更符合前后端分离设计
  • 注意localStorage存储Token的安全性,可考虑配合后端使用HttpOnly Cookie存储Token以降低XSS风险
  • 确保后端正确配置CORS规则,避免跨域请求被拦截

内容的提问来源于stack exchange,提问作者Hubert Wajda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:43:19