创建应用请参考:https://gitee.com/api/v5/oauth_doc#/

OAuth2 认证基本流程

在这里插入图片描述

OAuth2 获取 AccessToken 认证步骤

  1. 授权码模式
    应用通过 浏览器 或 Webview 将用户引导到码云三方认证页面上(GET请求)
    https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code
  2. 用户对应用进行授权
    注意: 如果之前已经授权过的需要跳过授权页面,需要在上面第一步的 URL 加上 scope 参数,且 scope 的值需要和用户上次授权的勾选的一致。如用户在上次授权了user_info、projects以及pull_requests。则步骤A 中 GET 请求应为:
    https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&scope=user_info%20projects%20pull_requests
  3. 码云认证服务器通过回调地址{redirect_uri}将 用户授权码 传递给 应用服务器 或者直接在 Webview 中跳转到携带 用户授权码的回调地址上,Webview 直接获取code即可({redirect_uri}?code=abc&state=xyz)
  4. 应用服务器 或 Webview 使用 access_token API 向 码云认证服务器发送post请求传入 用户授权码 以及 回调地址( POST请求 )注:请求过程建议将 client_secret 放在 Body 中传值,以保证数据安全。
    https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
  5. 码云认证服务器返回 access_token
    应用通过 access_token 访问 Open API 使用用户数据。
    当 access_token 过期后(有效期为一天),你可以通过以下 refresh_token 方式重新获取 access_token( POST请求 )
    https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
    注意:如果获取 access_token 返回 403,可能是没有设置User-Agent的原因。

源码

pom

	<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>GiteeProject</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.6.7</version>
        </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.80</version>
        </dependency>
    </dependencies>

</project>

yml

server:
  port: 8080

spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/

  web:
    resources:
      static-locations: classpath:/static/
gitee:
  id: 服务id
  secret: 秘钥
  callback: 回调请求

controller

package com.gitee;

import com.alibaba.fastjson.JSONObject;
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.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author: 随风飘的云
 * @describe:
 * @date 2022/06/21 10:14
 */
@Controller
public class GiteeController {
    @Value("${gitee.id}")
    private String id;

    @Value("${gitee.secret}")
    private String secret;

    @Value("${gitee.callback}")
    private String callback;

    @GetMapping("/auth")
    public String getAuth(HttpSession session){
        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=" + id +
                "&redirect_uri=" + URLEncoder.encode(callback) +
                "&state=" + uuid +
                "&scope=user_info";
        //因为使用的是thymeleaf模板引擎,所以是无法解析一个网址的,只能重定向
        return "redirect:"+url;
    }

    @GetMapping("/callback")
    public String getCallback(HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");
        if(uuid != null){
            if(!uuid.equals(state)){
                return "index";
            }
        }
        // Step2:通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + id +
                "&client_secret=" + secret +
                "&code=" + code +
                "&redirect_uri=" + callback;

        JSONObject accessToken = GiteeHttpClient.getAccessToken(url);
        // Step3: 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessToken.get("access_token");
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
        /**
         * 获取到用户信息之后,就该写你自己的业务逻辑了
         */
        System.out.println(jsonObject);
        return "hello";
    }
}

client

package com.gitee;

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;

/**
 * @author: 随风飘的云
 * @describe:
 * @date 2022/06/21 9:54
 */
@Component
public class GiteeHttpClient {

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

    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/102.0.0.0 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;
    }
}
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐