Java实现Google第三方授权认证---

package com.dycx.web;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**

  • Created by it on 2020/5/7.
    */
    @Controller
    @RequestMapping("/google")
    public class google {
    private static String client_id = “xxxxxx”;
    private static String client_secret = “xxxxxx”;
    private static String scope = “https://www.googleapis.com/auth/drive.metadata.readonly”;
    private static String redirect_url = “https://localhost:9008/google/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”;
    private String idToken;

    /**

    • @return String
    • @throws Exception
    • @throws
    • @throws
    • @Title: sendRedirect
    • @Description:页面直接请求这个接口
    • @author 第1步,配置好参数后,浏览器直接访问这个接口,发送请求让用户授权,授权成功后重定向到/GoogleUserInfo,也就是创建应用时定义的重定向地址
    • @date Mar 24, 2017 3:11:36 PM
      */
      @RequestMapping(value = “/sendRedirect”)
      public String sendRedirect() throws Exception {
      String s = code_url + “?client_id=” + client_id + “&redirect_uri=” + redirect_url + “&response_type=” + “code” + “&scope=” + scope + “&access_type=offline&include_granted_scopes=true”;
      return “redirect:” + s;
      }

    /**

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

    /**

    • @return String

    • @throws

    • @Title: getGoogleAccessToken

    • @Description: 获取accessToken

    • @author 第三步,用重定向带回来的code换取accessToken

    • @date Mar 25, 2017 10:25:00 AM
      */
      public String getGoogleAccessToken(String code) {
      RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(50000)
      .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
      // 创建cookie store的本地实例
      CookieStore cookieStore = new BasicCookieStore();
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
      .setDefaultCookieStore(cookieStore).build();
      String accessToken = null;

      try {
      HttpPost httpPost = new HttpPost(token_url);
      // List lastnvps = new ArrayList<>();
      // lastnvps.add(new BasicNameValuePair(“client_id”, client_id));
      // lastnvps.add(new BasicNameValuePair(“redirect_uri”, redirect_url));
      // lastnvps.add(new BasicNameValuePair(“client_secret”, client_secret));
      // lastnvps.add(new BasicNameValuePair(“grant_type”, “authorization_code”));
      // lastnvps.add(new BasicNameValuePair(“code”, code));
      JSONObject params = new JSONObject();
      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);
      StringEntity s = new StringEntity(params.toString());
      s.setContentType(“application/json”);//发送json数据需要设置contentType
      httpPost.setEntity(s);
      HttpResponse response = httpClient.execute(httpPost);
      if (response != null) {
      HttpEntity resEntity = response.getEntity();
      if (resEntity != null) {
      accessToken = EntityUtils.toString(resEntity, “UTF-8”);
      }
      }
      // responseResult = HttpClientUtil.getStringByPost(token_url, params,
      // null);
      } catch (Exception e) {
      e.printStackTrace();
      } finally {
      JSONObject jsonObject = JSONObject.parseObject(accessToken);
      String access_token = jsonObject.get(“access_token”).toString();
      this.idToken = jsonObject.getString(“id_token”);
      return access_token;

      }
      }

    /**

    • @return String
    • @throws
    • @Title: getUserInfo
    • @Description: 获取用户信息
    • @author第四步,用accessToken获取用户信息
    • @date Mar 25, 2017 11:50:23 AM
      */
      public static String getUserInfo(String accessToken) {
      RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(50000)
      .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
      // 创建cookie store的本地实例
      CookieStore cookieStore = new BasicCookieStore();
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
      .setDefaultCookieStore(cookieStore).build();
      String userInfo = new String();
      try {
      HttpGet httpGet = new HttpGet(user_url + “?access_token=” + accessToken);
      HttpResponse execute = httpClient.execute(httpGet);
      HttpEntity entity = execute.getEntity();
      userInfo = EntityUtils.toString(entity, “UTF-8”);

// responseResult = HttpClientUtil.getStringByGet(user_url, params);
} catch (Exception e) {
e.printStackTrace();
}
// if (null != responseResult && responseResult[0].equals(“200”)) {
// String result = responseResult[1];
// userInfo = JSONObject.fromObject(result);
// }
return userInfo;
}

/**
 * @return String
 * @throws
 * @Title: verifyToken
 * @Description:验证用户token是否是来自本应用的请求,校验aud和clientID是否相同
 * @author第五步,验证用户是否来自你的应用,防刷,根据需要加到逻辑里
 * @date Mar 25, 2017 7:36:33 PM
 */
public static JSONObject verifyToken(String idToken) {
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setSocketTimeout(50000)
            .setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();
    // 创建cookie store的本地实例
    CookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore).build();
    String s = new String();
    try {
        HttpGet httpGet = new HttpGet(verify_url + "?id_token=" + idToken);
        HttpResponse execute = httpClient.execute(httpGet);
        HttpEntity entity = execute.getEntity();
        s = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        return JSONObject.parseObject(s);
    }


}

}
转载+参考

你可能感兴趣的:(google)