我正在发送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);
}
}
这是我的申请流程:
Authorization Basic xxxxxx==
标头。auth
的Cookie,并将其与响应一起发送回(上面的代码)。
对于安全性层,我正在使用Spring安全性。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
我需要在这里进行哪些其他配置?
答案 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);