Google第三方登录的实现

谷歌第三方登录实现

  1. Controller类的实现
import cn.stylefeng.guns.core.util.HttpClientUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @ClassName: LoginController
* @Description: Google第三方登录
* @param
* @date Mar 13, 2017
*/
@Controller
public class GLoginController {

   private static String client_id = "693702919517-g5jgaqdt3et1k81kh8k1otgdlkuvkf04.apps.googleusercontent.com";
   private static String client_secret = "JupmsoPgdrm9ph9dhkC-wq25";
   private static String scope = "https://www.googleapis.com/auth/drive.metadata.readonly";
   private static String redirect_url = "http://localhost:8081/GoogleUserInfo";
   private static String code_url = "https://accounts.google.com/o/oauth2/v2/auth";
   private static String token_url = "https://www.googleapis.com/oauth2/v4/token";
   private static String user_url = "https://www.googleapis.com/oauth2/v2/userinfo";
   private static String verify_url = "https://www.googleapis.com/oauth2/v3/tokeninfo";

   /**
    * @Title: Login
    * @Description: google登录验证后会重定向到此地址,并附带访问授权码,不能为公开的ip地址
    * @author 此方法是用带回的code换取accessToken,然后用accessToken换取用户信息,这个地址就是在创建应用时定义的重定向地址
    * @return Object
    * @date Mar 23, 2017 10:37:38 AM
    * @throws
    */
   @RequestMapping(value = "/GoogleUserInfo")
   @ResponseBody
   public static Object Login(HttpServletRequest request) {
       String code = request.getParameter("code");
       System.out.println(code);

//		String idToken = getGoogleAccessToken(code);
//		System.out.println(idToken);
//		JSONObject verifyToken = verifyToken(idToken);
//		System.out.println(verifyToken);

       String accessToken = getGoogleAccessToken(code);
       System.out.println(accessToken);
       JSONObject userInfo = getUserInfo(accessToken);
       System.out.println(userInfo);
       return userInfo;
   }

   /**
    * @throws Exception
    * @Title: sendRedirect
    * @Description:发送授权请求
    * @author 第二步,在google.jsp中用户登录成功以后回跳转到这个路径,发送请求让用户授权,授权成功后重定向到/GoogleUserInfo,也就是创建应用时定义的重定向地址
    * @return String
    * @date Mar 24, 2017 3:11:36 PM
    * @throws
    */
   @RequestMapping(value = "/sendRedirect")
   public void sendRedirect(HttpServletResponse response) throws Exception {
       // 随机字符串,防止csrf攻击
       String state = UUID.randomUUID() + "";
       Map<String, String> params = new HashMap<String, String>();
       params.put("client_id", client_id);
       params.put("redirect_uri", redirect_url);
       params.put("response_type", "code");
       params.put("scope", scope);
       params.put("access_type", "offline");
       params.put("state", state);
       params.put("include_granted_scopes", "true");
       String url = code_url+"?"+ "client_id=" +client_id+
                                  "&redirect_uri="+ redirect_url+
                                  "&response_type=code" +
                                  "&scope="+ scope+
                                  "&access_type=offline"+
                                  "&state="+ state+
                                  "&include_granted_scopes=true";
       //String url = HttpClientUtil.getUrl(code_url, params);
       response.sendRedirect(url);
   }

   /**
    * @Title: getGoogleAccessToken
    * @Description: 获取accessToken
    * @author 第三步,用重定向带回来的code换取accessToken
    * @return String
    * @date Mar 25, 2017 10:25:00 AM
    * @throws
    */
   public static String getGoogleAccessToken(String code) {
       HashMap<String, String> params = new HashMap<String, String>();
       params.put("client_id", client_id);
       params.put("redirect_uri", redirect_url);
       params.put("client_secret", client_secret);
       params.put("grant_type", "authorization_code");
       params.put("code", code);
       String httpClientResult = null;
       String accessToken =null;
       String idToken=null;
       try {
           httpClientResult = HttpClientUtil.doPost(token_url, params, "utf-8");
       } catch (Exception e) {
           e.printStackTrace();
       }
       if (null != httpClientResult ) {
           //String result = httpClientResult.getContent();
           String result = httpClientResult;
           JSONObject jsonObject = JSONObject.fromObject(result);
           accessToken = jsonObject.getString("access_token");
           idToken=jsonObject.getString("id_token");
       }
       return accessToken;
//		return idToken;
   }

   /**
    * @Title: getUserInfo
    * @Description: 获取用户信息
    * @author第四步,用accessToken获取用户信息
    * @return String
    * @date Mar 25, 2017 11:50:23 AM
    * @throws
    */
   public static JSONObject getUserInfo(String accessToken) {
       HashMap<String, String> params = new HashMap<String,String>();
       params.put("access_token", accessToken);
       String responseResult =null;
       JSONObject userInfo=null;
       try {
           responseResult = HttpClientUtil.doGet(user_url, params);
       } catch (Exception e) {
           e.printStackTrace();
       }
       if (null != responseResult) {
           String result = responseResult;
           userInfo =  JSONObject.fromObject(result);
       }
       return userInfo;
   }

   /**
    * @Title: verifyToken
    * @Description:验证用户token是否是来自本应用的请求,校验aud和clientID是否相同
    * @author第五步,验证用户是否来自你的应用,防刷,根据需要加到逻辑里
    * @return String
    * @date Mar 25, 2017 7:36:33 PM
    * @throws
    */
   public static JSONObject verifyToken(String idToken){
       HashMap<String, String> params = new HashMap<String,String>();
       params.put("id_token", idToken);
       String responseResult =null;
       JSONObject verifyInfo=null;
       try {
           responseResult = HttpClientUtil.doGet(verify_url, params);
       } catch (Exception e) {
           e.printStackTrace();
       }
       if (null != responseResult) {
           String result = "";
       verifyInfo =  JSONObject.fromObject(result);
   }
       return verifyInfo;
   }

}
  1. Utils类的实现
import java.io.Serializable;

/**
 * Description: 封装httpClient响应结果
 *
 * @author JourWon
 * @date Created on 2018年4月19日
 */
public class HttpClientResult implements Serializable {

    private static final long serialVersionUID = 2168152194164783950L;

    /**
     * 响应状态码
     */
    private int code;

    /**
     * 响应数据
     */
    private String content;

    public HttpClientResult() {
    }

    public HttpClientResult(int code) {
        this.code = code;
    }

    public HttpClientResult(String content) {
        this.content = content;
    }

    public HttpClientResult(int code, String content) {
        this.code = code;
        this.content = content;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "HttpClientResult [code=" + code + ", content=" + content + "]";
    }

}
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.apache.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class HttpClientUtil {

    private static final Logger LOG = Logger.getLogger(HttpClientUtil.class);

    public static String doGet(String url, Map<String, String> param) throws Exception {

        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpClient httpclient = new SSLClient();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            LOG.error(e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                // httpclient.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        return resultString;
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            LOG.error(e);

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
        }

        return resultString;
    }

    public static String doPostOfJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            LOG.error(e);

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
        }

        return resultString;
    }

    public static String doPutOfJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Put请求
            HttpPut httpPut = new HttpPut(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPut.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPut);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            LOG.error(e);

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
        }

        return resultString;
    }

    public static String doDelete(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(uri);
            // 执行http请求
            response = httpClient.execute(httpDelete);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            LOG.error(e);

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
        }

        return resultString;
    }

    public static String doDeleteOfJson(String url, String json) {
        /**
         * 没有现成的delete可以带json的,自己实现一个,参考HttpPost的实现
         */
        class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
            public static final String METHOD_NAME = "DELETE";

            @SuppressWarnings("unused")
            public HttpDeleteWithBody() {
            }

            @SuppressWarnings("unused")
            public HttpDeleteWithBody(URI uri) {
                setURI(uri);
            }

            public HttpDeleteWithBody(String uri) {
                setURI(URI.create(uri));
            }

            @Override
            public String getMethod() {
                return METHOD_NAME;
            }
        }

        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            StringEntity params = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpDelete.setEntity(params);
            // 执行http请求
            response = httpClient.execute(httpDelete);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            LOG.error(e);

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOG.error(e);
            }
        }

        return resultString;
    }

    /*
     * 利用HttpClient进行post请求的工具类,键值对方式组装数据
     */
    public static String doPost(String url, Map<String, String> map, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

}
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSLClient extends DefaultHttpClient {
    //用于进行Https请求的HttpClient
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException { }
            @Override
            public X509Certificate[] getAcceptedIssuers() {return null; }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}
  1. 前端页面的实现
//引入openid-jquery.js
/*
   Simple OpenID Plugin
   http://code.google.com/p/openid-selector/
   
   This code is licensed under the New BSD License.
*/

var providers;
var openid;
(function ($) {
openid = {
   version : '1.3', // version constant
   demo : false,
   demo_text : null,
   cookie_expires : 6 * 30, // 6 months.
   cookie_name : 'openid_provider',
   cookie_path : '/',

   img_path : 'images/',
   locale : null, // is set in openid-<locale>.js
   sprite : null, // usually equals to locale, is set in
   // openid-<locale>.js
   signin_text : null, // text on submit button on the form
   all_small : false, // output large providers w/ small icons
   no_sprite : false, // don't use sprite image
   image_title : '{provider}', // for image title

   input_id : null,
   provider_url : null,
   provider_id : null,

   /**
    * Class constructor
    * 
    * @return {Void}
    */
   init : function(input_id) {
   	providers = $.extend({}, providers_large, providers_small);
   	var openid_btns = $('#openid_btns');
   	this.input_id = input_id;
   	$('#openid_choice').show();
   	$('#openid_input_area').empty();
   	var i = 0;
   	// add box for each provider
   	for (id in providers_large) {
   		box = this.getBoxHTML(id, providers_large[id], (this.all_small ? 'small' : 'large'), i++);
   		openid_btns.append(box);
   	}
   	if (providers_small) {
   		openid_btns.append('<br/>');
   		for (id in providers_small) {
   			box = this.getBoxHTML(id, providers_small[id], 'small', i++);
   			openid_btns.append(box);
   		}
   	}
   	$('#openid_form').submit(this.submit);
   	var box_id = this.readCookie();
   	if (box_id) {
   		this.signin(box_id, true);
   	}
   },

   /**
    * @return {String}
    */
   getBoxHTML : function(box_id, provider, box_size, index) {
   	if (this.no_sprite) {
   		var image_ext = box_size == 'small' ? '.ico.gif' : '.gif';
   		return '<a title="' + this.image_title.replace('{provider}', provider["name"]) + '" href="javascript:openid.signin(\'' + box_id + '\');"'
   				+ ' style="background: #FFF url(' + this.img_path + '../images.' + box_size + '/' + box_id + image_ext + ') no-repeat center center" '
   				+ 'class="' + box_id + ' openid_' + box_size + '_btn"></a>';
   	}
   	var x = box_size == 'small' ? -index * 24 : -index * 100;
   	var y = box_size == 'small' ? -60 : 0;
   	return '<a title="' + this.image_title.replace('{provider}', provider["name"]) + '" href="javascript:openid.signin(\'' + box_id + '\');"'
   			+ ' style="background: #FFF url(' + this.img_path + 'openid-providers-' + this.sprite + '.png); background-position: ' + x + 'px ' + y + 'px" '
   			+ 'class="' + box_id + ' openid_' + box_size + '_btn"></a>';
   },

   /**
    * Provider image click
    * 
    * @return {Void}
    */
   signin : function(box_id, onload) {
   	var provider = providers[box_id];
   	if (!provider) {
   		return;
   	}
   	this.highlight(box_id);
   	this.setCookie(box_id);
   	this.provider_id = box_id;
   	this.provider_url = provider['url'];
   	// prompt user for input?
   	if (provider['label']) {
   		this.useInputBox(provider);
   	} else {
   		$('#openid_input_area').empty();
   		if (!onload) {
   			$('#openid_form').submit();
   		}
   	}
   },

   /**
    * Sign-in button click
    * 
    * @return {Boolean}
    */
   submit : function() {
   	var url = openid.provider_url;
   	if (url) {
   		url = url.replace('{username}', $('#openid_username').val());
   		openid.setOpenIdUrl(url);
   	}
   	if (openid.demo) {
   		alert(openid.demo_text + "\r\n" + document.getElementById(openid.input_id).value);
   		return false;
   	}
   	if (url.indexOf("javascript:") == 0) {
   		url = url.substr("javascript:".length);
   		eval(url);
   		return false;
   	}
   	return true;
   },

   /**
    * @return {Void}
    */
   setOpenIdUrl : function(url) {
   	var hidden = document.getElementById(this.input_id);
   	if (hidden != null) {
   		hidden.value = url;
   	} else {
   		$('#openid_form').append('<input type="hidden" id="' + this.input_id + '" name="' + this.input_id + '" value="' + url + '"/>');
   	}
   },

   /**
    * @return {Void}
    */
   highlight : function(box_id) {
   	// remove previous highlight.
   	var highlight = $('#openid_highlight');
   	if (highlight) {
   		highlight.replaceWith($('#openid_highlight a')[0]);
   	}
   	// add new highlight.
   	$('.' + box_id).wrap('<div id="openid_highlight"></div>');
   },

   setCookie : function(value) {
   	var date = new Date();
   	date.setTime(date.getTime() + (this.cookie_expires * 24 * 60 * 60 * 1000));
   	var expires = "; expires=" + date.toGMTString();
   	document.cookie = this.cookie_name + "=" + value + expires + "; path=" + this.cookie_path;
   },

   readCookie : function() {
   	var nameEQ = this.cookie_name + "=";
   	var ca = document.cookie.split(';');
   	for ( var i = 0; i < ca.length; i++) {
   		var c = ca[i];
   		while (c.charAt(0) == ' ')
   			c = c.substring(1, c.length);
   		if (c.indexOf(nameEQ) == 0)
   			return c.substring(nameEQ.length, c.length);
   	}
   	return null;
   },

   /**
    * @return {Void}
    */
   useInputBox : function(provider) {
   	var input_area = $('#openid_input_area');
   	var html = '';
   	var id = 'openid_username';
   	var value = '';
   	var label = provider['label'];
   	var style = '';
   	if (label) {
   		html = '<p>' + label + '</p>';
   	}
   	if (provider['name'] == 'OpenID') {
   		id = this.input_id;
   		value = 'http://';
   		style = 'background: #FFF url(' + this.img_path + 'openid-inputicon.gif) no-repeat scroll 0 50%; padding-left:18px;';
   	}
   	html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />'
   			+ '<input id="openid_submit" type="submit" value="' + this.signin_text + '"/>';
   	input_area.empty();
   	input_area.append(html);
   	$('#' + id).focus();
   },

   setDemoMode : function(demoMode) {
   	this.demo = demoMode;
   }
};
})(jQuery);
//添加谷歌图标的点击按钮(注:下面的一些参数需要在谷歌的https://console.developers.google.com/apis/credentials/oauthclient网址中配置)

<a href="https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=693702919517-g5jgaqdt3et1k81kh8k1otgdlkuvkf04.apps.googleusercontent.com&redirect_uri=http://localhost:8081/GoogleUserInfo&scope=https://www.googleapis.com/auth/userinfo.email"><i class="iconfont layui-extend-google"></i></a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值