1. 程式人生 > 其它 >OAuth2.0整合gitee第三方登入註冊

OAuth2.0整合gitee第三方登入註冊

OAuth2.0

  • OAuth: : OAuth(開放授權)是一個開放標準,允許使用者授權第三方網站訪問他們儲存在另外的服務提供者上的資訊,而不需要將使用者名稱和密碼提供給第三方網站或分享他們資料的所有內容。

  • OAuth2.0 :對於使用者相關的 OpenAPI(例如獲取使用者資訊,動態同步,照片,日誌,分享等),為了保護使用者資料的安全和隱私,第三方網站訪問使用者資料前都需要顯式的向用戶徵求授權

授權流程圖示:

其他第三方服務類似

申請Gitee第三方應用ID和金鑰

將資訊儲存至專案中

gitee:
   oauth:
    clientid: XX
    clientsecret: XX
    callback: XX

專案匯入依賴

<!-- 網路請求 -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
<!-- alibaba的fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.51</version>
</dependency>

新增工具類GiteeHttpClient

public class GiteeHttpClient {
    /**
     * 獲取Access Token
     * post
     */
    public static JSONObject getAccessToken(String url) throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (null != entity) {
            String result = EntityUtils.toString(entity, "UTF-8");
            return JSONObject.parseObject(result);
        }
        httpPost.releaseConnection();
        return null;
    }

    /**
     * 獲取使用者資訊
     * get
     */
    public static JSONObject getUserInfo(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();

        return jsonObject;
    }

}

頁面登陸按鈕的請求方法

@Controller
public class GiteeController {
    /**
     * gitee授權中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;

    /**
     * 請求授權頁面
     */
    @GetMapping(value = "/gitee/auth")
    public String qqAuth(HttpSession session) {
        // 用於第三方應用防止CSRF攻擊
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1:獲取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid +
                "&scope=user_info";

        //重定向
        return "redirect:"+url;
    }
}

點選同意授權後,編寫OAuth2Controller控制器,裡面添加回調方法

@Slf4j
@Controller
public class OAuth2Controller {
    /**
     * gitee授權中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;


  /**
 * 授權回撥
 */
@GetMapping(value = "/callback")
public String giteeCallback(HttpServletRequest request) throws Exception {
    HttpSession session = request.getSession();
    // 得到Authorization Code
    String code = request.getParameter("code");
    // 我們放在地址中的狀態碼
    String state = request.getParameter("state");
    String uuid = (String) session.getAttribute("state");

    // 驗證資訊我們傳送的狀態碼
    if (null != uuid) {
        // 狀態碼不正確,直接返回登入頁面
        if (!uuid.equals(state)) {
            return PasswordUtils.redirectTo("/login");
        }
    }

    // Step2:通過Authorization Code獲取Access Token
    String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
            "&client_id=" + CLIENTID +
            "&client_secret=" + CLIENTSECRET +
            "&code=" + code +
            "&redirect_uri=" + URL;
    JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);

    // Step3: 獲取使用者資訊
    url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
    JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
    /**
     * 獲取到使用者資訊之後,就該寫你自己的業務邏輯了
     */
    return PasswordUtils.redirectTo("/success");
}

}