身份验证后使用令牌重定向

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

我正在使用 JWT 在 Spring Boot 中创建带有身份验证的简单 Web 应用程序。 fetch('http://localhost:8080/api/auth'...这会正确返回令牌。然后我可以使用:

    fetch('http://localhost:8080/api/admin', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token // Użycie tokena
        }
    })

此后一切正常,但我想重定向到“http://localhost:8080/api/admin”。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form id="loginForm">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br><br>
        <button type="submit">Login</button>
    </form>
    <p id="error-message" style="color: red;"></p>

    <script>
        document.getElementById('loginForm').addEventListener('submit', function(event) {
            event.preventDefault(); 

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            fetch('http://localhost:8080/api/auth', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('Network response was not ok');
                }
            })
            .then(data => {
                const token = data.token; 
                localStorage.setItem('jwttoken', token);
                // ...
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
                document.getElementById('error-message').innerText = 'Invalid username or password';
            });
        });

    </script>
</body>
</html>

我不知道如何在本地存储中保存令牌后进行重定向。我需要在标题中包含:

'授权':'承载'+令牌

jwt authorization token
1个回答
0
投票

看来使用脚本使用标头信息进行重定向是不可行的 - 请参阅此处 在此处输入链接描述

似乎存在一些关于是否可能的争论,但根据我对电子邮件协议的理解,PHP 中的标头是可能的,但可能不像他们所说的那样用于重定向。

另一种方法是对 URL 参数中的令牌数据进行加密,例如: window.location.href = "http://www.target.com?token=aef654898ab";

我发现您的问题更加复杂,尽管您正在尝试将 JSON 标头数据写入 API,但我再次不确定这是否可能或用于身份验证目的的正确方法。 您可能希望在此处查看开源 OAuth 网站以获取指导 - 在此处输入链接描述

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