我需要检查浏览器 cookie(以及 id - 密码)来确定用户是否有效。当用户激活帐户时,我已在浏览器中设置 cookie。登录时我需要检查 cookie 和凭据。我正在使用 spring security (daoAuthenticationProvider) 进行身份验证。 我正在使用代码设置 cookie:
public void setCookie(String token, HttpServletRequest request, HttpServletResponse response) {
try {
Cookie cookie = new Cookie(cookieName, token);
cookie.setDomain(cookieDomain);
cookie.setPath(cookiePath);
cookie.setMaxAge(31536000); // seconds for 365 days
response.addCookie(cookie);
} catch(Exception e) {
log.error("Exception in setting cookie : {}", e.getMessage());
}
}
当需要读取 cookie 时,我没有携带 HttpServletRequest
对象。因为它不是一个 Spring Controller ,我可以在其中拥有请求对象。所以我在 spring Controller 中编写了一个方法,它将返回 cookie 值。代码是:
@RequestMapping(value = "gettoken", method = RequestMethod.GET, produces={"text/html"})
public ResponseEntity<String> getToken(HttpServletRequest request) {
String token = "";
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
System.out.println("Cookie details : " + cookies[i].getName()
+ "\t" + cookies[i].getValue());
if (cookieName.equalsIgnoreCase(cookies[i].getName())) {
token = cookies[i].getValue();
break;
}
}
} else {
logger.info("No cookies found...");
}
return new ResponseEntity<String>(token,HttpStatus.OK);
}
这个 spring Controller 操作返回 cookie 值。当我点击这个 URL 时,我可以在浏览器中看到返回的 cookie 值。
现在我使用 HttpClient 从应用程序内调用此 URL。代码是:
public boolean isCookieValid(String token) {
boolean valid = false;
try {
String requestUrl = serverUrl + "gettoken";
log.info("requestUrl is : {} ", requestUrl);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet getRequest = new HttpGet(requestUrl.trim());
getRequest.addHeader("accept", "text/html");
HttpResponse response = httpClient.execute(getRequest,localContext);
System.out.println("call success : " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() != 200) {
return false;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String cookieToken = EntityUtils.toString(entity);
System.out.println("Cookie Token : " + cookieToken);
if(token.equalsIgnoreCase(cookieToken)) {
valid = true;
}
}
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
log.info("Exception in reading cookies : {}", e.getMessage());
}
return valid;
}
当我使用 http 客户端点击 spring 操作时,我收到 HTTP 200 响应代码。但是 Spring Controller 无法读取 cookie。知道可能是什么问题吗?有人有比这更好的方法吗?
最佳答案
getToken()
从收到的请求中提取 cookie。那么,当您使用 HttpClient 向其发送请求而不在请求中添加任何 cookie 时,您如何期望从它返回 token 呢?当您使用浏览器调用 getToken()
时,浏览器会随请求一起发送同一 Web 应用程序之前设置的所有 Cookie。这就是您取回 token 的原因。
关于java - 无法使用 HttpClient 读取浏览器 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080079/