使用第三方GitLab登录

经过研究第三方GitLab,做了一个简单的demo,实现使用GitLab登录。

一、效果图

先展示一下效果截图,大概就如下图所示
1.1 点击登录按钮
在这里插入图片描述
1.2 正在跳转到GitLab中。。。。
在这里插入图片描述
1.3 到GitLab登录页面,输入邮箱和密码
在这里插入图片描述
1.4 登录成功后,便会跳转到授权登录。选择授权登录或者拒绝。若选择授权登录,便会跳到我们之前写好的页面。之后再用GitLab登录的话,就不会有这个授权页面了,而是直接到之前写好的页面。
在这里插入图片描述
1.5 登录成功跳到之前写好的重定向的页面。并且会返回一串code值,通过这个code值,我们便可以拿到token。也就是后面放的方法,有注释。
在这里插入图片描述

二、具体操作如下:

2.1 首先需要登录到GitLab,进行一个账号注册
进入用户中心设置,下拉选择【Settings】
在这里插入图片描述
2.2 选择【Application】新建,输入一个名字和返回路径,勾选【api】即可生成Application ID。
在这里插入图片描述
2.3 下方是生成好的Application ID以及相关信息, 后面会用上。
在这里插入图片描述

三、前端jsp和js 写一个简单的按钮跳转到GitLab登录页面,进行授权登录。

3.1 jsp内容

选择:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button onclick="tolo()">GitLab登录</button>

3.2 js内容使用【window.location.href】进行跳转,参数详情下方有说明。

跳转授权的接口:

https://gitlab.com/oauth/authorize

参数:

参数内容
client_id注册应用的 Application Id
redirect_uri颁发令牌后的回调网址
response_type返回的类型,授权码模式即为code
state用于确认请求和回调的状态,OAuth 建议以此来防止 CSRF 攻击
scopeapi 权限设置,范围不得超出创建应用时的配置,以空格分隔
<script type="text/javascript">
    function tolo(){
        //注册 GitLab 应用成功后的 Application Id
        var client_id="49d44eaf1792cd5ee3813d2fef98f2951b913f5fdb4698279d2b0a092dd6bd5d";
        //注册应用时设置的重定向 URI
        var redirect_uri= "http://localhost:8089/****/back/ToGitLabSuccess";
        //返回的类型,授权码模式即为code
        var response_type ="code";
        //用于确认请求和回调的状态,OAuth 建议以此来防止 CSRF 攻击
        var state = "linda";
        //权限设置,范围不得超出创建应用时的配置,以空格分隔
        var scope = "api";
        //https://gitlab.example.com
        window.location.href ="https://gitlab.com/oauth/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri+"&response_type="+response_type+"&state="+state+"&&scope="+scope+""
    }
</script>

四、后端代码:

Controller

import com.alibaba.fastjson.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class GitLabController {

    
	/**
     * 返回的地址以及方法
     * @param code
     * @param access_token
     * @return
     * @throws Exception
     */
    @RequestMapping("/back/ToGitLabSuccess")
    public String ToGitLabSuccess(String code) throws Exception {
        if(code!=null){
                JSONObject jsonObject = this.getGitLabToken(code);
                //得到的数据 {"access_token":"23b905a8e6531ebeed*********************9512750a91e954a801","token_type":"Bearer","refresh_token":"51409b5516a******************************************3c291ff0455e4f01549f27cc7cc","scope":"api","created_at":1605516513}

                String access_tokenJosn = jsonObject.getString("access_token");
                System.out.println("输出的数据为access_token:"+access_tokenJosn);

                if(!access_tokenJosn.equals("")){
                    JSONObject gitLabUser = this.getGitLabUser(access_tokenJosn);
                    System.out.println("得到的用户信息为:"+gitLabUser.getString("name"));

                }

                return "back/ToGitLabSuccess";
        }

        return "back/ToGitLabSuccess";
    }


    /**
     * 通过code查询token
     * @param code
     * @return
     */
    public JSONObject getGitLabToken(String code){
        //访问token路径
        String url=GitURl.accessToken(code);
        //发送 POST 请求拿到token
        String sendPost = HTRequest.sendPost(url, "");
        JSONObject jsonObject = JSONObject.parseObject(sendPost);
        return jsonObject;
    }
    

    /**
     * 通过token拿到用户信息
     * @param access_token
     * @return
     */
    public JSONObject getGitLabUser(String access_token){
        String getToken= "access_token="+access_token;
        //请求拿到用户信息  Get请求
        String userURl= GitURl.userInfo();
        String UserInfos = HTRequest.sendGet(userURl,getToken);
        JSONObject jsonObjects = JSONObject.parseObject(UserInfos);
        UserTable userTable = new UserTable();
        return jsonObjects;
    }




}

URL
获取token信息的接口为:

https://gitlab.com/oauth/token

参数:

参数内容
client_id注册应用的 Application Id
client_secret注册应用的 Secret
grant_type授权方式,authorization_code
code上面获取到的授权码,但是其有效期很短,一般为10min
redirect_uri颁发令牌后的回调网址

根据token获取用户的信息接口为:

https://gitlab.com/api/v4/user

参数:

参数内容
access_token获取到的token


import org.springframework.context.annotation.Bean;

public class GitURl {

    //授权方式,authorization_code
    private static  String grant_type= "authorization_code";
    //注册应用的 Application Id
    private static  String client_id="49d44eaf1792cd5ee3813d2fef98f2951b913f5fdb****************dd6bd5d";
    //注册应用的 Secret
    private static  String client_secret= "a987ce1854376aed1e********************4a8c07e2a890a99797fc691a28";
    //颁发令牌后的回调网址
    private static  String redirect_uri ="http://localhost:8089/****/back/ToGitLabSuccess";


    /**
     * 访问登录,需要 client_id,redirect_uri,response_type=code&state=linda&&scope=api"
     * @return
     */
    public static String authorize() {
        return "https://gitlab.com/oauth/authorize";
    }

    /**
     * 访问令牌,获取token  ,需要code,grant_type=authorization_code,redirect_uri,client_id,client_secret
     * @return
     */
    public static String accessToken(String code) {
        return "https://gitlab.com/oauth/token?grant_type="+grant_type+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&code="+code+"";
    }

    /**
     * 得到用户信息,需要 access_token
     * @return
     */
    public static String userInfo() {
        return "https://gitlab.com/api/v4/user";
    }


get和post工具


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HTRequest {


    /**
     * 向指定URL发送GET方法的请求
     * @param url:发送请求的URL
     * @param param:请求参数,请求参数应该是 name1=value1&name2=value2&name3=value3 的形式。
     * @return String[result]:所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 建立实际的连接
            connection.connect();

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();

            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }

        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     *
     * 向指定 URL 发送POST方法的请求
     *
     * @param url:发送请求的 URL
     * @param param:请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     *  @return String[result]:所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);

            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());

            // 发送请求参数
            out.print(param);

            // flush输出流的缓冲
            out.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }

        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }



}

以上就是这次使用第三方GitLab登录的dome,记录一下。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐