java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > JustAuth-第三方Oauth2登录

JustAuth-第三方Oauth2登录方式

作者:勿语&

JustAuth是一款支持多种第三方登录的工具,本文通过实战介绍了如何在Springboot项目中集成JustAuth实现第三方登录,主要步骤包括引入依赖、配置Controller、设置登录和回调页面,通过访问登录页面并选择Gitee登录,系统会重定向至Gitee进行认证

JustAuth-第三方Oauth2登录

JustAuth官网: https://www.justauth.cn/

JustAuth整合Springboot

1.引入依赖

<dependency>
	 <groupId>org.springframework.boot</groupId>
	 <artifactId>spring-boot-starter-web</artifactId>
	 <version>2.7.15</version>
</dependency>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.26</version>
</dependency>
<dependency>
    <groupId>me.zhyd.oauth</groupId>
    <artifactId>JustAuth</artifactId>
    <version>1.16.6</version>
</dependency>

2.Controller

(到Gitee或GitHub上申请第三方授权,修改为自己的clientId、clientSecret)。

这里url中的 {source} 是为了接口和方法的复用。

@RestController
@RequestMapping("/oauth")
public class OauthController {

    @RequestMapping("/{source}")
    public void renderAuth(@PathVariable("source") String source,HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest(source);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public String login(@RequestParam("source") String source, AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest(source);
        // 返回用户的基本信息
        AuthResponse authResponse = authRequest.login(callback);
        // 返回Token
        return UUID.randomUUID().toString();
    }

    private AuthRequest getAuthRequest(String source) {
        if ("gitee".equals(source)) {
            return new AuthGiteeRequest(AuthConfig.builder()
                    .clientId("***************************")
                    .clientSecret("****************************")
                    // 回调地址与Gitee上注册的保持一致
                    .redirectUri("http://127.0.0.1:8080/callback.html?source=gitee")
                    .build());
        }else if ("github".equals(source)){
            return new AuthGithubRequest(AuthConfig.builder()
                    .clientId("**********")
                    .clientSecret("*********")
                    // 回调地址与Github上注册的保持一致
                    .redirectUri("http://127.0.0.1:8080/callback.html?source=github")
                    .build());
        }
        return null;
    }
}

3.登陆页面 login.html

(放在resources/static/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="http://localhost:8080/oauth/gitee" rel="external nofollow" >Gitee登录</a>
<a href="http://localhost:8080/oauth/github" rel="external nofollow" >Github登录</a>
</body>
</html>

4.回调页面 callback.html

(放在resources/static/callback.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>callback</title>
    <style>
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .loader {
            font-size: 24px;
            color: white;
        }
    </style>
</head>
<body>
<div id="loading-overlay" class="overlay">
    <div class="loader">Loading</div>
</div>
<script>
    window.onload = async function () {
        showLoadingOverlay()
        // 获取 source、code、state参数发起fetch请求
        const params = new URLSearchParams(window.location.search);
        // 发起请求
        try {
            const res = await fetch("/oauth/callback", {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: params.toString(),
            }).then(res => res.text())
            localStorage.setItem("token", res)
            location.href = "/index.html"
        } finally {
            hideLoadingOverlay()
        }
    }

    // 显示遮罩
    function showLoadingOverlay() {
        document.getElementById("loading-overlay").style.display = "flex";
    }

    // 隐藏遮罩
    function hideLoadingOverlay() {
        document.getElementById("loading-overlay").style.display = "none";
    }
</script>
</body>
</html>

5.登录成功后跳转首页 index.html

(放在resources/static/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<div>首页</div>
</body>
</html>

启动项目访问 http://localhost:8080/login.html

点击Gitee登录 (会跳转到Gitee进行登录,登录成功后携带参数重定向到回调页面,如果Gitee已经登陆,则直接携带参数重定向到回调页面)。

callback.html 挂载后,会携带url参数,发起请求,请求结束之后保存返回的token,并跳转到index.html。

Gitee的回调URL:

http://127.0.0.1:8080/callback.html?source=gitee&code=19c26e280bc9a83de9df6c9698b802a61e210e4fce67b0867b8166eef990c053&state=f40f8a38c9dfed67ee912960016f8f69

index.html

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文