URL 重定向 Cookie丢失 问题

1.在A系统中部分菜单功能是需要访问B系统的,两个系统两套登录,现在有这样一个需求,省去登录B系统的操作,点击菜单直接跳转到B的功能页面。

思路是:写一个Controller 所有访问/grafana/**的请求都到这里,判断是否携带“grafana_session”cookie,如果没有携带,通过httpclient发送B系统的登录请求,将登录成功后返回的grafana_session写入cookie中,重定向到B系统。

package cn.com.bjev.admin.vms.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.bjev.admin.vms.common.HttpResponseEntity;

/**
 * grafana登录
 */
@RequestMapping("/grafana")
@Controller
public class GrafanaLogin {

	private static final Logger logger = LoggerFactory.getLogger(GrafanaLogin.class);
	
	private static final String USER="****";
	private static final String PASSWORD="****";
	
	@RequestMapping("/**")
	public String login(HttpServletRequest request, Model model, HttpServletResponse response){
		try {
			boolean isExist=false;
			String requestURI = request.getRequestURI();
			Cookie[] cookies = request.getCookies();
			for (int i = 0; i < cookies.length; i++) {
				if("grafana_session".equals(cookies[i].getName())){
					isExist=true;
				}
			}
			if(!isExist){
				Map params=new HashMap();
				params.put("user", USER);
				params.put("password", PASSWORD);
				HttpResponseEntity responseEntity = httpPostForm("http://***.com/login", params, null, null);
				if(responseEntity.getContent().contains("Logged in")){
					
					for (Header header : responseEntity.getHeaders()) {
						if("Set-Cookie".equals(header.getName())){
							
							HeaderElement[] elements = header.getElements();
							for (int i = 0; i < elements.length; i++) {
								HeaderElement headerElement = elements[i];
								Cookie cookie=new Cookie(headerElement.getName(),headerElement.getValue());
								cookie.setMaxAge(-1);
								cookie.setPath("/");
								cookie.setDomain(".*****.com");
								response.addCookie(cookie);
							}
							break;
						}
					}
				}
			}
			return "redirect:http://*******.com/"+requestURI.substring(requestURI.indexOf("/",2)+1);
		} catch (Exception e) {
			logger.error("grafana登录异常", e);
		}
		return "redirect:http://*******.com/";
	}
	
	
	
	/** 
     * 发送 http post 请求,参数以form表单键值对的形式提交。 
     */  
    public HttpResponseEntity httpPostForm(String url,Map params, Map headers,String encode){  
    	HttpResponseEntity result=new HttpResponseEntity();
    	if(encode == null){  
            encode = "utf-8";  
        }  
        //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();   
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();   
        HttpPost httpost = new HttpPost(url);  
        
        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数  
        List paramList = new ArrayList ();  
        if(params != null && params.size() > 0){
            Set keySet = params.keySet();  
            for(String key : keySet) {  
                paramList.add(new BasicNameValuePair(key, params.get(key)));  
            }  
        }
        try {  
            httpost.setEntity(new UrlEncodedFormEntity(paramList, encode));  
        } catch (UnsupportedEncodingException e1) {  
            e1.printStackTrace();  
        }  
        String content = null;  
        CloseableHttpResponse  httpResponse = null;  
        try {  
            httpResponse = closeableHttpClient.execute(httpost);  
            HttpEntity entity = httpResponse.getEntity();  
            content = EntityUtils.toString(entity, encode); 
            result.setContent(content);
            result.setHeaders(httpResponse.getAllHeaders());
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                httpResponse.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        try {  //关闭连接、释放资源  
            closeableHttpClient.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        return result;
    }  
}

遇到的问题:重定向设置cookie丢失,B系统获取不到设置的cookie。

解决方案:将cookie的domain属性设置为二级域名例如:.baidu.com

domain:可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”。

你可能感兴趣的:(web,cookie,domain,重定向)