前言:由于工作需要对接微信公众号登录,所以就去了解了JustAuth这个依赖,这中间遇到了很多坑,(别笑我)我弄了整整两天…
前置操作
一:安装依赖
<!--JustAuth依赖--><dependency><groupId>me.zhyd.oauth</groupId><artifactId>JustAuth</artifactId><version>1.16.5</version></dependency><!-- okhttp3/okhttp模块 --><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.10.0</version></dependency>
二:具体的Controller
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeChatMpRequest;
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 AuthDemoController {@RequestMapping("/render")public void renderAuth(HttpServletResponse response) throws IOException {AuthRequest authRequest = getAuthRequest();response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));}/*** 获取用户信息* @param authCallback* @return*/@RequestMapping("/callback")public Object getUserInfo(AuthCallback authCallback) {AuthRequest authRequest = getAuthRequest();AuthResponse login = authRequest.login(authCallback);AuthUser authUser = (AuthUser) login.getData();String openId = authUser.getUuid();String nickname = authUser.getNickname();String headimgurl = authUser.getAvatar();String username = authUser.getUsername();return authUser;}private AuthRequest getAuthRequest() {return new AuthWeChatMpRequest(AuthConfig.builder().clientId("xxxxxxxxx").clientSecret("xxxxxxxxxxxxxx").redirectUri("http://xxxxxxxxxxxxx/oauth/callback").build());}
}
三:操作
- 记得去 微信公众号配置自己的域名并且进行测试,
这里修改成自己的服务器域名
然后就可以访问这个链接了
http://xxxxxxxxxxx/oauth/render
四:访问上面那个链接你会得到这样一个界面
- 你可以把上面地址栏中的地址,从微信打开,或者把这个地址栏中的链接生成二维码,引导用户扫码
- 扫码完成后,认证成功之后,用户就会跳转到你在后端预先设置好的回调地址,就是这个
http://xxxxxxxxxxxxx/oauth/callback