Gitee第三方登录

写这篇文章时,参考了一位大佬的文章,算是把大佬文章里一些不详细的部分补充完整了,但是核心的代码没有什么改动,只是抛弃掉了那个重定向的工具类,以下是大佬文章的链接:http://t.csdn.cn/0L7T4


准备

1、登录gitee

官网:https://gitee.com/

2、注册或登录账号

3、进入设置》第三方应用

在这里插入图片描述

4、创建应用
在这里插入图片描述

5、客户端id和密钥
在这里插入图片描述
6、至此准备工作就结束了


开始

1、导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 网络请求 -->
<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>

2、application.yml

spring:
  thymeleaf:
    cache: false

gitee:
  oauth:
    clientid: 5094679ccb97db605a5d9bc2843768521cefffb59cd9ed21a8eda086a69b5aa4
    clientsecret: 82dbd8916d16169e0770ae3a28ce651e5792ded24fa78af4c0ad963ef8361300
    callback: http://localhost:8080/callback

3、GiteeHttpClient

package com.t1.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
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;
    }

}

4、GiteeController

package com.t1.controller;

import com.alibaba.fastjson.JSONObject;
import com.t1.config.GiteeHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

@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 = "/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";
		//因为使用的是thymeleaf模板引擎,所以是无法解析一个网址的,只能重定向
        return "redirect:"+url;
    }
    /**
     * 授权回调
     */
    @GetMapping(value = "/callback")
    public String qqCallback(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 "index";
            }
        }

        // 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);
        /**
         * 获取到用户信息之后,就该写你自己的业务逻辑了
         */
        System.out.println(jsonObject);
        return "hello";
    }
}

5、index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <a th:href="@{/auth}" class="link" title="Gitee登录">gitee登录</a>
</body>
</html>

6、hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Hello World!</title>
</head>
<body>
    <h1>登陆成功,欢迎</h1>
</body>
</html>

7、测试
在这里插入图片描述


在这里插入图片描述


在这里插入图片描述
8、至此gitee的第三方登录就到此结束了。


  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
史上最全的整合第三方登录的工具,目前已支持Github、Gitee、微博、钉钉、百度、Coding、腾讯云开发者平台、OSChina、支付宝、QQ、微信、淘宝、Google、Facebook、抖音、领英、小米、微软和今日头条等第三方平台的授权登录。 Login, so easy!JustAuth,如你所见,它仅仅是一个第三方授权登录的工具类库,它可以让我们脱离繁琐的第三方登录SDK,让登录变得So easy!项目开源地址:gitee | github特点废话不多说,就俩字:全:已集成十多家第三方平台(国内外常用的基本都已包含),后续依然还有扩展计划!简:API就是奔着最简单去设计的(见后面快速开始),尽量让您用起来没有障碍感!快速开始引入依赖     me.zhyd.oauth     JustAuth     1.8.0 调用api// 创建授权request AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()         .clientId("clientId")         .clientSecret("clientSecret")         .redirectUri("redirectUri")         .state("state")         .build()); // 生成授权页面 authRequest.authorize(); // 授权登录后会返回code(auth_code(仅限支付宝))、state,1.8.0版本后,可以用AuthCallback类作为回调接口的参数 authRequest.login(callback);注:1.8.0版本后,增加了state参数校验,用于防止CSRF。强烈建议,保证单次流程内state的唯一性,且每个state只可用一次。配套Demo:JustAuth-demo具体的例子可以参考:实现Gitee授权登录实现Github授权登录API列表平台API类 SDKAuthGiteeRequest参考文档AuthGithubRequest参考文档AuthWeiboRequest参考文档AuthDingTalkRequest参考文档AuthBaiduRequest参考文档AuthCodingRequest参考文档AuthTencentCloudRequest参考文档AuthOschinaRequest参考文档AuthAlipayRequest参考文档AuthQqRequest参考文档AuthWeChatRequest参考文档AuthTaobaoRequest参考文档AuthGoogleRequest参考文档AuthFacebookRequest参考文档AuthDouyinRequest参考文档AuthLinkedinRequest参考文档AuthMicrosoftRequest参考文档AuthMiRequest参考文档AuthToutiaoRequest参考文档AuthCsdnRequest无请知悉:经咨询CSDN官方客服得知,CSDN的授权开放平台已经下线。如果以前申请过的应用,可以继续使用,但是不再支持申请新的应用。so, 本项目中的CSDN登录只能针对少部分用户使用了后续开发计划参考:[开发计划] 待扩展的第三方平台另外,期待您和我一起完善这个项目!贡献代码fork本项目到自己的repo把fork过去的项目也就是你仓库中的项目clone到你的本地修改代码commit后push到自己的库发起PR(pull request) 请求等待作者合并致谢在项目立项初期,也对当前开源圈的一些相同类型的项目作过调研,同时本项目也参考过这些项目,再次感谢开源圈内的朋友。YurunOAuthLogin: PHP 第三方登录授权 SDK阿里妈妈MUX倾力打造的矢量图标库-iconfont: 本文档中的图标大部分取自该平台
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值