亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

原生java代碼實現(xiàn)碼云第三方驗證登錄的示例代碼

 更新時間:2021年04月12日 10:44:08   作者:唐僧洗頭用拉芳  
這篇文章主要介紹了原生java代碼實現(xiàn)碼云第三方驗證登錄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

碼云第三方驗證登錄

研究了QQ,碼云,微信等第三方登錄接口時,發(fā)現(xiàn)QQ以及微信第一步都需要驗證授權(quán)管理,而且個人測試需要提供手持身份證一張,并且驗證時間過長( 3天工作日左右吧 ),這樣會非常浪費大家學(xué)習(xí)第三方接口登錄的時間,終于, 在我的不屑努力下,找到了適合大家快速上手,測試第三方接口登錄的平臺-————碼云(看網(wǎng)上帖子說某WX接入還要開發(fā)者認(rèn)證,人民幣300元)
碼云鏈接地址
https://gitee.com/

一、在碼云上創(chuàng)建應(yīng)用

1、在碼云上注冊一個賬號,點擊右上角設(shè)置

在這里插入圖片描述

2、創(chuàng)建應(yīng)用

在這里插入圖片描述

3、填寫資料

很多同學(xué)不太了解什么是應(yīng)用回調(diào)地址webhooks(第三方登錄成功后,會返回到你指定的地址,并且攜帶驗證是否成功的參數(shù)信息)

在這里插入圖片描述

4、獲取到clientId以及client Secret

clientId和client Sercret的主要作用是通過拼接得到請求地址,將地址重定向至授權(quán)登錄頁面

在這里插入圖片描述

在這里插入圖片描述

準(zhǔn)備過程已完成

二、在項目中實現(xiàn)第三方登錄

大概流程

在這里插入圖片描述

1、導(dǎo)入依賴jar包

   <!--servlet服務(wù)-->
	<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
	<!--第三方登錄插件包-->
    <dependency>
      <groupId>me.zhyd.oauth</groupId>
      <artifactId>JustAuth</artifactId>
      <version>1.3.2</version>
    </dependency>
	<!--服務(wù)器發(fā)送get,post工具包-->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>

2、跳轉(zhuǎn)授權(quán)頁面

AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
        .clientId(CLIENT_ID) //Client ID
        .clientSecret(CLIENT_SECRET) //Client Secret
        .redirectUri(REDIRECTURI)   //回調(diào)地址
        .build());
String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
//跳轉(zhuǎn)到授權(quán)頁面
response.sendRedirect(authorizeUrl);

3、通過回調(diào)地址獲取到code值

//http://localhost:8080/login?actionName=giteeCode&code=e063730161cd40cf&state=25c74eba2ac5f 
String code = request.getParameter("code");

4、再將用戶授權(quán)碼發(fā)送碼云服務(wù)器

補充一個小小的坑,碼云第三方驗證需要加上header信息,否則會報403錯誤

String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;
Map<String,String> map = new HashMap<>();
map.put("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)");
JSONObject s = HttpUtils.post(url,map);

授權(quán)登錄失敗會返回message錯誤信息,標(biāo)識登錄失敗

成功:

{
"access_token":"e386e20327b7c4",
"refresh_token":"057c79c2d1f957a5cb4d",
"scope":"user_info",
"created_at":15488,
"token_type":"bearer",
"expires_in":86400
}

5、獲取碼云用戶信息

通過授權(quán)碼獲取到的json數(shù)據(jù),其中access_token參數(shù),可以訪問碼云的用戶數(shù)據(jù)

//https://gitee.com/api/v5/user?access_token=*******
String access_token = s.getString("access_token");
String url2 = "https://gitee.com/api/v5/user?access_token="+access_token;
JSONObject user = HttpUtils.get(url2,map);

//1、設(shè)置響應(yīng)類型輸出流
response.setContentType("application/json;charset=UTF-8");
//2、將json轉(zhuǎn)為字符串
String str = JSON.toJSONString(user);
//3、得到字符輸出流
response.getWriter().write(str);

源碼:
在這小編要說一下回調(diào)地址操作1和回調(diào)地址操作2的區(qū)別
操作1:小編使用的是服務(wù)器的get,post發(fā)送請求,而跳轉(zhuǎn)“授權(quán)頁面”(giteeLogin 方法)使用的是插件,各位看主大大也可手動改為get請求,跳轉(zhuǎn)第三方登錄頁面,具體get地址請參考
碼云oauth文檔
其中A和B步驟,修改后就可以不用插件代碼跳轉(zhuǎn)授權(quán)頁面

操作2:完全使用的是JustAuth插件實現(xiàn)第三方登錄

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shsxt.utils.HttpUtils;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    //ac85a173bb89ee
    private final String CLIENT_ID = “Client ID”
    private final String CLIENT_SECRET= “Client Secret”
    private final String REDIRECTURI = “回調(diào)地址”

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲取用戶行為
        String actionName = request.getParameter("actionName");
        //判斷用戶行為
        if("giteeLogin".equals(actionName)) {
            //如果發(fā)送碼云授權(quán)驗證
            giteeLogin(request,response);
        }else if("giteeCode".equals(actionName)) {
            //giteeCode(request,response);
           giteeCode2(request,response);
        }
        System.out.println("點擊了");
    }

    /**
     * 回調(diào)地址后的操作1
     * @param request
     * @param response
     */
    private void giteeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //獲取code
        String code = request.getParameter("code");
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code="+code+"&client_id="+CLIENT_ID+"&redirect_uri="+REDIRECTURI+"&client_secret="+CLIENT_SECRET;
        Map<String,String> map = new HashMap<>();
        map.put("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)");
        JSONObject s = HttpUtils.post(url,map);
        System.out.println(s);

        //https://gitee.com/api/v5/user?access_token=*******
        String access_token = s.getString("access_token");
        String url2 = "https://gitee.com/api/v5/user?access_token="+access_token;
        JSONObject user = HttpUtils.get(url2,map);
        //1、設(shè)置響應(yīng)類型輸出流
        response.setContentType("application/json;charset=UTF-8");
        //2、將json轉(zhuǎn)為字符串
        String str = JSON.toJSONString(user);
        //3、得到字符輸出流
        response.getWriter().write(str);
    }


    /**
     * 回調(diào)地址后的操作2
     * @param request
     * @param response
     */
    private void giteeCode2(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String code = request.getParameter("code");

        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId(CLIENT_ID) //Client ID
                .clientSecret(CLIENT_SECRET) //Client Secret
                .redirectUri(REDIRECTURI)   //回調(diào)地址
                .build());

        AuthResponse json = authRequest.login(code);
        System.out.println(json);

    }


    /**
     * 跳轉(zhuǎn)授權(quán)頁面
     * @param request
     * @param response
     */
    private void giteeLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //跳轉(zhuǎn)授權(quán)頁面
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId(CLIENT_ID) //Client ID
                .clientSecret(CLIENT_SECRET) //Client Secret
                .redirectUri(REDIRECTURI)   //回調(diào)地址
                .build());
        String authorizeUrl = authRequest.authorize();
        //跳轉(zhuǎn)到授權(quán)頁面
        response.sendRedirect(authorizeUrl);
    }
}

服務(wù)器發(fā)送get/post請求工具類

package com.shsxt.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;


public class HttpUtils {
    /*
     *發(fā)送簡單post請求
     */
    public static JSONObject post(String url) {
        HttpPost post = new HttpPost(url);
        return getResult(post);
    }
    /*
     *發(fā)送帶Header的post請求
     */
    public static JSONObject post(String url, Map<String, String> map) {
        HttpPost post = new HttpPost(url);
        if (!map.isEmpty()) {
            Set<Map.Entry<String, String>> entrys = map.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return getResult(post);
    }
    /*
     *發(fā)送帶Header的get請求
     */
    public static JSONObject get(String url, Map<String, String> map) {
        HttpGet get = new HttpGet(url);
        if (!map.isEmpty()) {
            Set<Map.Entry<String, String>> entrys = map.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return getResult(get);

    }
    /*
     *發(fā)送簡單的get請求
     */
    public static JSONObject get(String url) {
        HttpGet get = new HttpGet(url);
        return getResult(get);

    }
    /*
     *發(fā)送請求方法,請求響應(yīng)為JSONObject
     */
    private static JSONObject getResult(HttpRequestBase requestBase) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = null;
        try {
            result = EntityUtils.toString(httpClient.execute(requestBase).getEntity());
            result = new String(result.getBytes("ISO-8859-1"),"utf-8");
            httpClient.close();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            return new JSONObject(JSON.parseObject(result));
        }
    }
    /*
     *當(dāng)請求響應(yīng)為String時
     */
    public static String getString(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        String result = null;
        try {
            result = EntityUtils.toString(httpClient.execute(get).getEntity());
            httpClient.close();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            return result;
        }
    }

}
```*當(dāng)請求響應(yīng)為String時
     */
    public static String getString(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        String result = null;
        try {
            result = EntityUtils.toString(httpClient.execute(get).getEntity());
            httpClient.close();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            return result;
        }
    }
}

前端頁面

在這里插入圖片描述

總結(jié)

到此這篇關(guān)于原生java代碼實現(xiàn)碼云第三方驗證登錄的示例代碼的文章就介紹到這了,更多相關(guān)java碼云第三方驗證登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java單例的寫法詳解

    Java單例的寫法詳解

    在java中,單例有很多種寫法,面試時,手寫代碼環(huán)節(jié),除了寫算法題,有時候也會讓手寫單例模式,這里記錄一下單例的幾種寫法和優(yōu)缺點。需要的朋友可以參考下
    2021-09-09
  • Intellij IDEA 與maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound

    Intellij IDEA 與maven 版本不符 Unable to import maven project See

    這篇文章主要介紹了Intellij IDEA 與maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound,本文通過圖文給大家分享解決方案,需要的朋友可以參考下
    2020-08-08
  • Java數(shù)據(jù)結(jié)構(gòu)之單鏈表的實現(xiàn)與面試題匯總

    Java數(shù)據(jù)結(jié)構(gòu)之單鏈表的實現(xiàn)與面試題匯總

    由于順序表的插入刪除操作需要移動大量的元素,影響了運行效率,因此引入了線性表的鏈?zhǔn)酱鎯Α獑捂湵?。本文為大家介紹了單鏈表的實現(xiàn)與面試題匯總,感興趣的可以了解一下
    2022-10-10
  • SpringBoot壓縮json并寫入Redis的示例代碼

    SpringBoot壓縮json并寫入Redis的示例代碼

    由于業(yè)務(wù)需要,存入redis中的緩存數(shù)據(jù)過大,占用了10+G的內(nèi)存,內(nèi)存作為重要資源,需要優(yōu)化一下大對象緩存,所以我們需要對json進(jìn)行壓縮,本文給大家介紹了SpringBoot如何壓縮Json并寫入redis,需要的朋友可以參考下
    2024-08-08
  • Java輕松實現(xiàn)表單提交的三種方法

    Java輕松實現(xiàn)表單提交的三種方法

    在Web開發(fā)中,表單是用戶與網(wǎng)站交互的主要方式之一,本文將詳細(xì)介紹如何在Java中實現(xiàn)表單提交,并通過代碼和案例為新手朋友提供詳細(xì)的指導(dǎo),有需要的可以參考下
    2024-10-10
  • java使double保留兩位小數(shù)的多方法 java保留兩位小數(shù)

    java使double保留兩位小數(shù)的多方法 java保留兩位小數(shù)

    這篇文章主要介紹了java使double類型保留兩位小數(shù)的方法,大家參考使用吧
    2014-01-01
  • Java中JDBC連接數(shù)據(jù)庫詳解

    Java中JDBC連接數(shù)據(jù)庫詳解

    本文主要介紹了JDBC連接數(shù)據(jù)庫的相關(guān)知識,具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03
  • Java多線程 實例解析

    Java多線程 實例解析

    這篇文章主要介紹了Java多線程 實例解析,需要的朋友可以參考下
    2017-04-04
  • Java經(jīng)典面試題匯總:Spring

    Java經(jīng)典面試題匯總:Spring

    本篇總結(jié)的是Spring框架相關(guān)的面試題,后續(xù)會持續(xù)更新,希望我的分享可以幫助到正在備戰(zhàn)面試的實習(xí)生或者已經(jīng)工作的同行,如果發(fā)現(xiàn)錯誤還望大家多多包涵,不吝賜教,謝謝
    2021-07-07
  • Java靜態(tài)內(nèi)部類實現(xiàn)單例過程

    Java靜態(tài)內(nèi)部類實現(xiàn)單例過程

    這篇文章主要介紹了Java靜態(tài)內(nèi)部類實現(xiàn)單例過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10

最新評論