日期:2014-05-18  浏览次数:20719 次

无法用COOKIE实现自动登录其他网站
我想在用户访问我的网站(A)的时候自动登录上另一个网站(B)。结果失败了。
具体操作是这样的,我先用IE登录我的A网站,照理说如果程序没错,我已经登录了B网站。但是当我访问B网站的时候,它还是提示我没登录。为什么啊?
PS:我监听HTTP包,发现IE并没有发送COOKIE给B网站。可我明明在Response里面addCookie了啊,而且也设置了Domain为B网站。


附上代码:

public class LoginFilter implements Filter {

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
Cookie[] cookies = (Cookie[]) ((HttpServletRequest) request)
.getSession(true).getServletContext().getAttribute(
"storage-cookies");

if (null == cookies) {
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(
CookiePolicy.BROWSER_COMPATIBILITY);

PostMethod postMethod = new PostMethod("www.anotherwebsite.com");
postMethod.addParameter("user_name", "user1");
postMethod.addParameter("password", "pwd1");
postMethod.addParameter("remember_me", "1");

client.executeMethod(postMethod);
cookies = client.getState().getCookies();
((HttpServletRequest) request).getSession(true).getServletContext()
.setAttribute("storage-cookies", cookies);

HttpServletResponse rsp = (HttpServletResponse) response;
for (int i = 0; i < cookies.length; i++) {
javax.servlet.http.Cookie c = new javax.servlet.http.Cookie(cookies[i].getName(),cookies[i].getValue());
c.setDomain(cookies[i].getDomain());
c.setPath(cookies[i].getPath());
rsp.addCookie(c);
}
postMethod.releaseConnection();
}
chain.doFilter(request, response);
}
............

------解决方案--------------------
我也出现了这个问题,你看客户端生成cookie文件没有
------解决方案--------------------
没有生成cookie文件,是因为你没有设置cookie的过期时间,一般没有设置是默认时间为当前浏览器,如果浏览器关闭掉就自动删除。。。


------解决方案--------------------
探讨
在网上看到这样的说法-----“按照浏览器的约定,只有来自同一域名的cookie才可以读写”。
这么一来,跨域登录岂非无法实现了???

------解决方案--------------------
IE限制只有当前服务器对应的域名(可以根域名),但是不能是其他域名。否则的话。别人的网站随便让你后台跨一下。不是很没面子。

以前的办法可以搞个隐藏的窗口,来提交其数据。在隐藏的窗口中登陆。但是IE等浏览器已经升级过。也不允许跨域访问IE窗口。

目前有个办法,是通过你的服务器中转。 而不能直接让客户访问对方网站。