自动登录+Nginx反向代理

一、获取登录cookie

1.编写HTTP访问


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class HttpUtils {

	
	
	public Map<String,Object> executeHttps(String urlStr,String param,String requestMethod,Map<String,String> requestProperty,Boolean isRedirect) throws Exception {
		Map<String,Object> map=new HashMap<String, Object>();
		DataOutputStream out=null;
		InputStreamReader input=null;
		BufferedReader brd=null;
		HttpsURLConnection connet=null;
		try {
			// 实例一个URL资源
			URL url = new URL(urlStr);
			// 实例一个HTTP CONNECT
			connet = (HttpsURLConnection) url.openConnection();
			connet.setDoInput(true);
			connet.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
			connet.setUseCaches(false);//请求不能使用缓存
			connet.setInstanceFollowRedirects(isRedirect); //不允重定向 
			connet.setRequestMethod(requestMethod);
			
			for(Map.Entry<String,String> mapEntry:requestProperty.entrySet()){
				connet.setRequestProperty(mapEntry.getKey(), mapEntry.getValue());
			}
			connet.setConnectTimeout(1000*15);// 连接超时 单位毫秒
			connet.setReadTimeout(1000*60*20);// 读取超时 单位毫秒
			
			connet.connect(); 
			
			if(param!=null){
				out = new DataOutputStream(connet.getOutputStream());
		        out.writeBytes(param); //写入请求的字符串
		        out.flush();
			}
			
			if (connet.getResponseCode() != 200) {
				new Throwable("请求异常:" + urlStr);
			}

			InputStream inputStream = connet.getInputStream();
			// 将返回的值存入到String中
			input = new InputStreamReader(inputStream);
			brd = new BufferedReader(new InputStreamReader(connet.getInputStream(), "utf-8"));
			
			StringBuilder sb = new StringBuilder();
			String line;

			while ((line = brd.readLine()) != null) {
				sb.append(line);
			}
			
			map.put("header", connet.getHeaderFields());
			map.put("body", sb.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			
			if(out!=null){
				out.close();
			}
			if(input!=null){
				input.close();
			}
			if(brd!=null){
				brd.close();
			}
			if(connet!=null){
				connet.disconnect();
			}
			
		}
		
		return map;
	}
	
	
	
	/**
	 * ===============跳过HTTPS证书================
	 */
	static {
        try {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier((urlHostName, session) -> true);
           
        } catch (Exception e) {
        }
    }
 
    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
 
    private static class TrustAllManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkServerTrusted(X509Certificate[] certs,String authType) {
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }
    }
	
	
	
	
}

2.编写登录获取cookie方法

public Map<String,String> veeamLogin() throws Exception{
		HttpUtils hu=new HttpUtils();
		Map<String,String> proxyRequestCookieMap=new HashMap<String, String>();
		try {
			
			String pwd=encoder.encodeToString(pwdStr.getBytes());
			
			Map<String,String> hm=new HashMap<String,String>();
			
			hm.put("Accept","*/*");
			hm.put("Accept-Encoding","gzip, deflate, br");
			hm.put("Accept-Language","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
			hm.put("Connection","keep-alive");
			//hm.put("Content-Length","38");
			hm.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			hm.put("Host","XXXXXX");
			hm.put("Origin","https://XXXXXX");
			hm.put("Referer","https://XXXXXX/login.aspx");
			hm.put("TE","Trailers");
			hm.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0");
			hm.put("X-Requested-With","XMLHttpRequest");
			

			StringBuffer p=new StringBuffer();
			p.append("password="+pwd+"&username="+nameStr);
			
			
			Map<String, Object> executeHttps = hu.executeHttps(urlStr,p.toString(), "POST", hm,false);
			
			
			
			@SuppressWarnings("unchecked")
			Map<String,List<String>> hmap=(Map<String, List<String>>) executeHttps.get("header");
			for(Map.Entry<String, List<String>> ml:hmap.entrySet()){
				if("Set-Cookie".equals(ml.getKey())){
					for(String mlv:ml.getValue()){
						String[] hTempValueArr=mlv.toString().split(",");
						for(String htva:hTempValueArr){
							String[] htvaArr=htva.split(";");
							for(String htvaa:htvaArr){
								if(htvaa.indexOf("=")>-1){
									String[] htvaaArr=htvaa.split("=");
									proxyRequestCookieMap.put(htvaaArr[0], htvaaArr[1]);
								}
							}
						}
					}
					
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return proxyRequestCookieMap;
	}

注:pwdStr,nameStr,urlStr为访问网站的URL,用户名,密码


3.编写JSP用来给浏览器写cookie,写完后访问目标网站

<%
	AutoLogin al=new AutoLogin();
	Map<String,String> map=al.veeamLogin();
	
	
	
	Cookie servletCookie = new Cookie(".aaaa",map.get(".aaaa"));
	servletCookie.setPath("/");
	servletCookie.setVersion(1);
	response.addCookie(servletCookie);
	
	servletCookie = new Cookie(".bbbbb",map.get(".bbbbb"));
	servletCookie.setPath("/");
	servletCookie.setVersion(1);
	response.addCookie(servletCookie);
	

	response.sendRedirect("http://10.180.26.101/index.aspx");

%>

二、nginx配置

1.nginx配置(访问步骤使用jsp访问一次把cookie写到浏览器,然后jsp访问目标页面这样就不用登录直接访问了)


worker_processes  1;

events {
    worker_connections  1024;
    accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on
		multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off
}


http {
		
		include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;


    server {
        listen       80;
        server_name  10.180.26.101;
        location / {
            proxy_pass https://xxxxxxxx:9443;
						
            proxy_set_header   Host    $host;
		        proxy_set_header   X-Real-IP   $remote_addr;
		        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
		        proxy_cookie_path  / /;
		        proxy_set_header   Cookie $http_cookie;
		        
		        #ws wss访问
						proxy_http_version 1.1;    
						proxy_set_header Upgrade $http_upgrade;
						proxy_set_header Connection "Upgrade";
						proxy_set_header Origin "";

        }
        
        #jsp自动登录
        location ~ \.(jsp|jspx|do|wsdl)?$ {
            proxy_pass http://10.180.26.101:8080;
						
						#ws wss访问
            proxy_set_header   Host    $host;
		        proxy_set_header   X-Real-IP   $remote_addr;
		        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
		        proxy_cookie_path  / /;
		        proxy_set_header   Cookie $http_cookie;
		        
						proxy_http_version 1.1;    
						proxy_set_header Upgrade $http_upgrade;
						proxy_set_header Connection "Upgrade";
						proxy_set_header Origin "";

        }

    }

		
}

注:由于目标页面有ws wss访问需要配置如下代码:

#ws wss访问
						proxy_http_version 1.1;    
						proxy_set_header Upgrade $http_upgrade;
						proxy_set_header Connection "Upgrade";
						proxy_set_header Origin "";


(1)