【问题标题】:Set-Cookie not working in browser but works with PostmanSet-Cookie 在浏览器中不起作用,但与 Postman 一起使用
【发布时间】:2017-12-04 14:25:11
【问题描述】:

前端在 localhost:4200,后端在 localhost:8080

我已经在我的后端和前端实现了 CORS 配置,并且所有其他 API 请求都可以正常工作。但是,Set-Cookie 标志并未在我的浏览器中创建 cookie。

我什至有disabled CORS in chrome

当我使用 Postman 发出 POST 请求时,我在 Cookie 选项卡中正确地看到了 Cookie。我在网络浏览器中没有看到 cookie。

选项请求

Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,credentials

选项响应

X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Access-Control-Allow-Origin: http://localhost:4200
access-control-allow-credentials: true
access-control-allow-methods: POST, GET, OPTIONS, DELETE
access-control-max-age: 3600
access-control-allow-headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, credentials
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length: 0
Date: Fri, 30 Jun 2017 14:55:58 GMT

POST 请求

Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:4200/login
Content-Type: application/json
credentials: true
Content-Length: 48
Origin: http://localhost:4200
Connection: keep-alive

POST 响应

X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Access-Control-Allow-Origin: http://localhost:4200
access-control-allow-credentials: true
access-control-allow-methods: POST, GET, OPTIONS, DELETE
access-control-max-age: 3600
access-control-allow-headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, credentials
Set-Cookie: ddd=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjJmYXhhcyIsImV4cCI6MTQ5ODkyMDk1OH0.sKJLH1GvgbJP28ws2EOZpc8EH0SElB4VQX86m59G8BjT-QAaRW6sInnrF6Y_yNJcIEcrrw_itb-O26KkKza8aA
Content-Length: 0
Date: Fri, 30 Jun 2017 14:55:58 GMT

【问题讨论】:

  • 你能解决这个问题吗??
  • 不,我决定不使用 cookie 代替..
  • 实际上在生产中这不是一个好主意,因为您将无法仅使用 http 标头(没有这样的东西)使恶意 Javascript 代码可以访问令牌。当我找到解决方案时,我会在这里发布:)
  • 您找到解决问题的方法了吗?

标签: angular cookies


【解决方案1】:

为了能够在这种情况下设置 cookie,您必须允许所有 OPTIONS 请求从过滤器通过,因为它们不包含根据 this question 的 cookie,更重要的是从服务器 withCredentials 请求 cookie 时选项必须在服务器端和客户端都设置为 true。永远不要忘记在服务器上启用 CORS 请求(您必须定义来源,例如 localhost:4200 ,使用通配符 * 将不起作用)希望这有助于任何寻找此问题答案的人。

【讨论】:

  • 所有标头都已从服务器端设置,但这仍然失败
【解决方案2】:

MrMisery 的回答对我有用,但我还添加了所有可用的方法(使用 Spring Boot):

@RestController
@CrossOrigin(
        //origins = "*", aqui dejar este si la hace de pedo
        origins = {"http://localhost:3000"},
        allowCredentials = "true",
        maxAge = 3600, 
        allowedHeaders = "*",
        methods= {RequestMethod.GET,RequestMethod.POST, 
                RequestMethod.DELETE, RequestMethod.PUT, 
                RequestMethod.PATCH, RequestMethod.OPTIONS, 
                RequestMethod.HEAD, RequestMethod.TRACE}
)
@RequestMapping("/access")
public class AccessController {...

当然在我的登录端点上我设置了 cookie:

...
//set cookie on response
Cookie authCookie = new Cookie(COOKIE_NAME, jwt);
authCookie.setHttpOnly(true);
authCookie.setMaxAge(JWT_EXPIRATION_TIME * 60 * 60);//3 hours
authCookie.setVersion(0);
authCookie.setPath("/");
response.addCookie(authCookie);
//return response
return ResponseEntity.ok(new ResponseLoad(
    Message.TYPE_MESSAGE,
    Message.SEVERITY_SUCC,
    null,
    therapist));

最后在我的 React 客户端中的 Axios 中使用 withCredentials,如下所示:

const config = {
        headers: {
            "Content-Type": "application/json"
        },
        withCredentials: true
    };

    await axios
        .post(apiURL + apiVersion + "/access/login", { email, password }, config)
        .then((response) => {

            sessionStorage.setItem(
                "somedata" + storageCode,
                JSON.stringify(response.data.subBody)
            );

            dispatch({
                type: THERAPIST_LOGIN_SUCCESS,
                payload: response.data.subBody
            });
        })

我无法在响应标头上看到 cookie,但是一旦我检查(使用 Chrome)开发工具 > 应用程序 > 存储部分 - Cookies 并单击 http://localhost:3000 就可以了!!!

【讨论】:

    【解决方案3】:

    对我有用的方法与 @Josueemx 类似,但没有将额外的 http 方法显式设置到源区域。

    我所做的只是将凭据添加到请求配置中,下面是一个示例

    const config = {
    headers: {
      "Content-Type": "application/json"
      },
      withCredentials: true
    }
    

    然后将其添加到 axios.post('host',SomeDataHere, config)

    然后使用 MrMisery 建议的 cors 凭据设置确切的来源。可以举个例子。

    app.use(cors({
        origin: 'http://localhost:3000',
        credentials: true,
    }));
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2020-11-20
      • 2021-09-04
      • 2016-11-04
      • 2017-08-20
      • 2021-11-27
      • 1970-01-01
      • 2015-03-11
      • 2012-11-09
      相关资源
      最近更新 更多