【问题标题】:Why does the Authorization header token does not get displayed in my browser为什么授权标头令牌未显示在我的浏览器中
【发布时间】:2020-11-10 12:38:50
【问题描述】:

我想创建一个登录系统。我有一个带有 JWT-Token 的 Spring Boot Api,用于使用this 教程编写的安全性。在我的前端,我使用 React JS 和 Axios 来处理请求。

这是我的 axios 配置:

import axios from 'axios';

const api = axios.create({
    baseURL:'http://localhost:8080',
    headers: {'Access-Control-Allow-Origin': '*'}
});

export default api;

这是登录功能:

loginClickHandler = () => {
        const data = {
            "username":this.state.username,
            "password":this.state.password
        };
        api.post("/login",data)
            .then(response => {
                console.log(response);
                if(response.data !== null) {
                    this.setState({
                        loggedIn:true,
                        userData:response.data
                    });
                }else{
                    this.showMessage(2,response.data.error)
                }
            })
            .catch(error => {
                this.showMessage(2,error);
            });
    };

登录功能本身和其他一切都可以正常工作,但我没有在浏览器中获得作为标题显示的授权令牌。这是console.log(response)(仅标题):

headers:
cache-control: "no-cache, no-store, max-age=0, must-revalidate"
content-length: "0"
expires: "0"
pragma: "no-cache"

但是,当我使用 Postman 进行请求时,我得到 14 个标头,其中一个是 Authorization 标头,其中包含预期的令牌。

现在我的问题是,如何在浏览器中显示标题,以便将其存储以供以后请求。

谢谢

编辑:

我刚刚发现授权标头显示在浏览器的网络选项卡中,但没有显示在响应中。

解决方案:

我必须在我的 JWTAuthenticationFilter successfulAuthentication 方法中添加这一行:

res.addHeader("Access-Control-Expose-Headers",HEADER_STRING);

正如@Jack Chen 和@Sarthak Aggarwal 建议的那样

【问题讨论】:

  • 必须在服务器上设置 Access-Control-Allow-Origin 标头,而不是在浏览器上。
  • 感谢您的输入,但我认为这与问题无关,因为请求本身正在运行

标签: reactjs spring spring-boot spring-security authorization


【解决方案1】:

您无法在此处在客户端请求中设置标头信息:

import axios from 'axios';

const api = axios.create({
    baseURL:'http://localhost:8080',
    // pass 'Access-Control-Allow-Origin' is not working!
    headers: {'Access-Control-Allow-Origin': '*'}
});

export default api;

由于CORS,在服务器端设置此标头之前,您无法获得正确的响应。你可以根据this guide在你的Spring Boot服务中设置header。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    您可能需要在服务器上设置 The Access-Control-Expose-Headers 标头集,因为它允许服务器将允许浏览器访问的标头列入白名单。`

    语法:

    Access-Control-Expose-Headers: <header-name>[, <header-name>]*
    

    【讨论】:

    • 欲了解更多信息,请查看this
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2015-05-26
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2021-12-27
    相关资源
    最近更新 更多