为什么未在浏览器中设置cookie,但在POSTMAN中设置了cookie?

时间:2019-02-11 22:00:09

标签: java spring-boot cookies

我正在发送GET请求以进行基本身份验证,服务器(后端API)将向其返回(如果身份验证成功)cookie。这对于POSTMAN来说运作良好,但未设置浏览器cookie。

@GetMapping("/login")
@ResponseStatus(value=HttpStatus.OK)
public void loginUser( final HttpServletRequest request ,final HttpServletResponse response) throws UnsupportedEncodingException {

        setAuthCookieToResonse(request,response);    
    }

private void setAuthCookieToResonse(final HttpServletRequest request ,final HttpServletResponse response) throws UnsupportedEncodingException {
    logger.debug("Adding cookie after authentication");
    String cookieKey = "auth";
    String cookieValue = request.getHeader("Authorization");

    if (cookieValue != null) {
        Cookie cookie = new Cookie(cookieKey, URLEncoder.encode(cookieValue, "utf-8"));
        cookie.setHttpOnly(true);
        cookie.setDomain("localhost");

        response.addCookie(cookie);
    }
}

这是我的申请流程:

  1. 使用基本身份验证的浏览器/ POSTMAN登录。发送凭证 使用Authorization Basic xxxxxx==标头。
  2. 服务器读取身份验证详细信息,如果正确,它将创建一个 名为auth的Cookie,并将其与响应一起发送回(上面的代码)。 对于安全性层,我正在使用Spring安全性。
  3. 对于其他请求,该cookie将自动与 每个请求。现在,我必须拿起那个Cookie并提取 身份验证详细信息。之后,我必须添加 Authorization Basic xxxxxx==响应该请求(因为现在 Authorization未由客户端发送,仅发送了cookie)。为了这 我创建了Filter,它将在Spring之前运行 BasicAuthenticationFilter.class

步骤2适用于POSTMAN,但不适用于浏览器。在POSTMAN中,发送的response服务器包含Set-Cookie →auth=Basic xxxxxxxx=; Domain=localhost; HttpOnly

curl -i -u pu@gmail.com:password@ http://localhost:8085/api/v1/login

HTTP/1.1 200
Set-Cookie: auth=Basic xxxxxxxx==; HttpOnly
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
Content-Length: 0
Date: Tue, 12 Feb 2019 05:59:33 GMT

浏览器中的响应标头:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3007
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Tue, 12 Feb 2019 11:52:10 GMT
Expires: 0
Pragma: no-cache
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

我需要在这里进行哪些其他配置?

1 个答案:

答案 0 :(得分:0)

您必须将withCredentials附加到您从浏览器发出的http调用中,否则浏览器将不会响应Set-Cookie标头。

角度示例

return this.http.post(url, userLoginRequest, { withCredentials: true }) as Observable<
      LoginResponse
>

Axios示例

axios.post(API_SERVER + '/login', { email, password }, { withCredentials: true })

XMLHttpRequest示例

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);