JustAuth官网: https://www.justauth.cn/
JustAuth整合Springboot
- 引入依赖
<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>
- 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/{source}")
public String login(@PathVariable("source") String source, AuthCallback callback) {
AuthRequest authRequest = getAuthRequest(source);
return JSONUtil.toJsonStr(authRequest.login(callback));
}
private AuthRequest getAuthRequest(String source) {
if ("gitee".equals(source)) {
return new AuthGiteeRequest(AuthConfig.builder()
.clientId("***************************")
.clientSecret("***************************")
.redirectUri("http://127.0.0.1:8080/oauth/callback/gitee")
.build());
}else if ("github".equals(source)){
return new AuthGithubRequest(AuthConfig.builder()
.clientId("**********")
.clientSecret("*********")
.redirectUri("http://127.0.0.1:8080/oauth/callback/github")
.build());
}
return null;
}
}
- 登陆页面 index.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">Gitee登录</a>
<a href="http://localhost:8080/oauth/github">GitHub登录</a>
</body>
</html>
- 启动项目
- 访问 http://localhost:8080/
- 点击Gitee登录