无法使用HttpClient读取浏览器cookie

时间:2013-04-18 10:08:07

标签: java spring spring-mvc cookies spring-security

我需要检查浏览器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。知道可能是什么问题吗?任何人都有比这更好的方法吗?

1 个答案:

答案 0 :(得分:1)

getToken()从收到的请求中提取cookie。那么,当您使用HttpClient向请求发送请求而不向请求添加任何Cookie时,您如何期望从中返回令牌?当您使用浏览器呼叫getToken()时,浏览器会发送同一个webapp之前设置的任何cookie以及请求。这就是你获得令牌的原因。