整合 JustAuth 开源组件实现微信登录。
文档地址:https://justauth.wiki/oauth/wechat_open.html
1、新建一个 Spring Boot 工程
2、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>me.zhyd.oauth</groupId>
<artifactId>JustAuth</artifactId>
<version>1.16.3</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.7.7</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
4、编写配置文件
application.properties
server.port=8160
5、编写启动类
6、编写 Contorller
package com.yanghui.oauth.controller;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeChatOpenRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/oauth")
public class RestAuthController {
private String appId = "wxed9954c01bb89b47";
private String appSecret = "a7482517235173ddb4083788de60b90e";
private String redirectUrl = "http://localhost:8160/api/ucenter/wx/callback";
@RequestMapping("/render")
public void renderAuth(HttpServletResponse response) throws IOException {
AuthRequest authRequest = getAuthRequest();
response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
}
@RequestMapping("/callback")
public Object login(AuthCallback callback) {
AuthRequest authRequest = getAuthRequest();
return authRequest.login(callback);
}
private AuthRequest getAuthRequest() {
return new AuthWeChatOpenRequest(AuthConfig.builder()
.clientId(appId)
.clientSecret(appSecret)
.redirectUri(redirectUrl)
.build());
}
}
7、进行测试
访问地址:http://localhost:8160/oauth/render
|