gpt4 book ai didi

java - 尽管 {withCredentials :true},但未能在 GET 请求中发送 Cookie

转载 作者:行者123 更新时间:2023-12-02 09:01:31 25 4
gpt4 key购买 nike

我打算使用 Spring Boot REST API、JWT(Auth0 -java-jwt) 和 Angular 8 实现一个简单的登录应用程序。登录后,我从 REST API 收到一个 Cookie,如下所示如下:

Cookie cookie= new Cookie("token",token);
cookie.setPath("/");
cookie.setDomain("localhost");
cookie.setHttpOnly(true);
cookie.setMaxAge(60 * 60 * 24 * 365 * 10);
//cookie.setSecure(true); - for deployment
httpServletResponse.addCookie(cookie);

在浏览器(开发工具、响应 header )中,我可以看到收到的 Cookie 以及正确的 token 。但是,我在 chrome://settings/siteData?search 中看不到它,我尝试了 Chrome、Chromium 和 Firefox,都显示了相同的结果。

现在,这就是我从 Angular 客户端发送请求的方式:

const h = new HttpHeaders().append("Authorization", "Bearer ");
this.http.get("http://localhost:8080/api/users", {headers:h, withCredentials: true })

在请求 header 中,我没有看到此 cookie,因此我认为该请求未获得授权。

enter image description here

我错过了什么?另外,我很欣赏任何演示使用 Spring Boot(仅限 REST API,不使用 Thymleaf 或其他东西)、Angular 和 JWT (java-jwt) 进行简单登录的文章。谢谢。

最佳答案

在我看来,这里的问题是您在没有 JWT 的情况下发送 Authorzation header ,实际上您正在代码中编写 const h = new HttpHeaders().append("Authorization", "Bearer ") ;.

我在 react 应用程序中使用 fetch 解决了类似的问题,但我想这对你来说应该是一样的,没有设置授权 header ,而是像你一样设置 withCredentials: true。

最后,我的建议是尝试删除 header ,因为您的配置没有发送 JWT token

提示如果在您的问题中您编写了一个空白 token ,但在实际的生产代码中您正确插入了它,也许您应该检查您的资源服务器是否可以正常工作,我不知道... postman curl 或类似的东西或者您应该检查您的 token 是否是有效 token 而不是过期 token

附:在您的后端服务器实现中,我看到了非常低级的详细信息,如果您使用的是 Spring Boot 2.x,我建议您使用 Spring Security oauth2 模块;如果您使用的是 Spring Boot 1.5.x 版本,则建议您使用 Spring Cloud Security OAuth2

关于java - 尽管 {withCredentials :true},但未能在 GET 请求中发送 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60127352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com