我需要检查浏览器 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 控制器中编写了一个方法,它将返回 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 控制器动作返回 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 控制器无法读取 cookie。知道可能是什么问题吗?有人有比这更好的方法吗?