SpringBoot第三方登录JustAuth

JustAuth流程

  1. 创建授权请求,并跳转到授权页面,以便用户进行认证和授权
  2. 生成一个随机的 stateId,用于标识本次授权请求
  3. 封装到 Map 中作为响应返回给客户端
  4. 处理授权成功后回调的请求
  5. 调用 AuthRequest 的 login() 方法完成授权
  6. AuthResponse 对象封装到 ResponseResult 中返回给客户端

配置第三方应用

我们以gitee为例子,在个人设置中找到第三方应用。

创建应用

填写申请第三方应用

获取这两个关键密文

引入依赖

java 复制代码
<dependency>
	<groupId>me.zhyd.oauth</groupId>
	<artifactId>JustAuth</artifactId>
	<version>1.16.5</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置properties文件

java 复制代码
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
gitee.ClientID=139dd95598cb6539e2e79edfdc67f29acf8ea52bbaa2f45c204efdb0d9bc0e24
gitee.ClientSecret=f0158ab4d918dd2f9b8d2c427bed5ecfbb1c1ddf8941c519108ce33a17fc3bd9

封装结果类

java 复制代码
import java.io.Serializable;
@Data
public class ResponseResult<T> implements Serializable {
    private Boolean success;
    private Integer code;
    private String msg;
    private T data;

    public static ResponseResult ok(Object data) {
        ResponseResult result = new ResponseResult();
        result.setData(data);
        return result;
    }

}

login页面

通过这个login-controller跳转到login页面

复制代码
@Controller
@RequestMapping("/login")
public class LoginController {
    @RequestMapping("/home")
    public String login(Model model){
        return "login";
    }
}

在这个页面点击gitee登录可以返回后端接口,后端接口再跳转gitee授权页面,返回数据给前端

复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="/js/jquery-3.5.1.min.js"></script>
</head>
<body>
    <button id="bg">使用gitee登录</button>
</body>
<script type="text/javascript">
    $(function(){
        $("#bg").click(function(){
            $.get("/login-before",function(data,status){
               window.location=data.data.authorizePageUrl;
            });
        });
    });
</script>
</html>

Oauth2controller

后端完成获取授权码,发送授权码获取用户基本信息等操作

java 复制代码
import com.example.demo.util.ResponseResult;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class Oauth2Controller {

    @Value("${gitee.ClientID}")
    private String clientID;
    @Value("${gitee.ClientSecret}")
    private String clientSecret;

    private static final Logger LOG = LoggerFactory.getLogger(Oauth2Controller.class);
    @GetMapping("/login-before")
    public ResponseResult loginBeforByGitee(){
        // 创建授权request
        AuthRequest authRequest = getAuthRequest();
        String stateId = UUID.randomUUID().toString();
        LOG.info("stateId = " + stateId);
        // 跳转到授权页面
        String authorizePageUrl = authRequest.authorize(stateId);
        LOG.info("authorizePageUrl地址为"+authorizePageUrl);
        Map map = new HashMap<>();
        map.put("authorizePageUrl",authorizePageUrl);
        return ResponseResult.ok(map);
    }
    @GetMapping("/callback")
    public ResponseResult callback(String code,String state) {
        // gitee授权通过跳转到回调接口
        LOG.info("code = " + code);
        LOG.info("state = " + state);
        // 使用这个code去获取用户基本信息
        AuthResponse login = getAuthRequest().login(AuthCallback.builder().state(state).code(code).build());
        // 数据返回给前端
        return ResponseResult.ok(login);
    }

    private AuthRequest getAuthRequest(){
        // 创建授权request
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId(clientID)
                .clientSecret(clientSecret)
                .redirectUri("http://127.0.0.1:7125/callback")
                .build());
        return authRequest;
    }

}

测试

访问localhost:7125/login/home

授权登录

前端获取到基本信息

相关推荐
SHUIPING_YANG3 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼15 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、21 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
墨染点香34 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 小时前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
江南一点雨1 小时前
Tokenizer 和 BPE
后端
风象南1 小时前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山1 小时前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记