前提条件
- 申请微信开放平台账号(扫码登录必须有微信开放平台)
- 在开放平台上创建一个网站应用,获取AppID、AppSecret,并配置授权回调域。
- 集成weixin-java-mp
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
</dependency>
过程说明
如下图所示,主要分为:用户、统一认证服务和微信服务端
获取微信扫码地址
@ApiOperation("跳转微信扫码登录页面")
@GetMapping("/redirect")
public String redirect() throws UnsupportedEncodingException {
String appId = wxService.getWxMpConfigStorage().getAppId();
String state = URLEncoder.encode(ssoProperties.getSuccessUrl(), "UTF-8");
String url = wxService.buildQrConnectUrl("http://wx.test.com/wxlogin/callback", WxConsts.QrConnectScope.SNSAPI_LOGIN, state);
log.info(">> wxlogin redirect, url: {}", url);
return "redirect:" + url;
}
回调接口
@ApiOperation(
value = "微信回调接口",
notes = "微信回调后获取微信用户信息," +
"如果已存在且为有效状态,直接自动登录, 登录地址: /wxlogin/login" +
"如果不存在, 重定向到绑定页面进行绑定" +
"如果无效状态, 重定向的登录页面并提示错误原因"
)
@ApiImplicitParams({
@ApiImplicitParam(name = "code", value = "微信oauth2认证码"),
@ApiImplicitParam(name = "state", value = "微信oauth2认证state")
})
@GetMapping("/callback")
public String callback(String code, String state) throws WxErrorException {
log.info(">> wxlogin callback, code: {}, state: {}", code, state);
WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
log.info(">> wxlogin callback, wxMpUser: {}", user);
String wxUnionId = user.getUnionId();
AccountCredential accountCredential = this.credentialService.getCredentialByName(wxUnionId);
ResponseCode responseCode;
if (accountCredential == null) {
responseCode = ResponseCode.NOT_EXISTED;
} else {
Account account = this.accountService.getAccount(accountCredential.getAccountId());
if (Account.ACCOUNT_STATE_DISABLED.equals(account.getAccountState())) {
responseCode = ResponseCode.DISABLED;
} else if (Account.ACCOUNT_STATE_LOCKING.equals(account.getAccountState())) {
responseCode = ResponseCode.LOCKED;
} else {
responseCode = ResponseCode.SUCCESS;
}
}
log.info(">> wxlogin callback, ResponseCode: {}", responseCode);
String redirectUrl;
if (ResponseCode.SUCCESS.equals(responseCode)) {
// 直接登录
redirectUrl = String.format("%s?wxUnionId=%s&state=%s", ssoProperties.getWxloginUrl(), wxUnionId, state);
} else if (ResponseCode.NOT_EXISTED.equals(responseCode)) {
//TODO 绑定成功后如何自动登录呢?
redirectUrl = String.format("%s?responseCode=%s&wxUnionId=%s", ssoProperties.getWxbindUrl(), responseCode.val(), wxUnionId);
} else {
// 跳转到登录页面
redirectUrl = String.format("%s?authentication_error=true&error=%s", ssoProperties.getFailuresUrl(), responseCode.encodeMessage());
}
return "redirect:" + redirectUrl;
}
微信登录扩展实现
public class WeiXinAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final WxUserDetailsService userDetailsService;
private final WxMpService wxService;
public WeiXinAuthenticationFilter(WxUserDetailsService userDetailsService, WxMpService wxService) {
super(new AntPathRequestMatcher("/wxlogin/login"));
this.userDetailsService = userDetailsService;
this.wxService = wxService;
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
String wxUnionId = request.getParameter("wxUnionId");
return super.requiresAuthentication(request, response) && StringUtils.hasText(wxUnionId);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String wxUnionId = request.getParameter("wxUnionId");
String state = request.getParameter("state");
UserDetails userDetails = this.userDetailsService.loadUserByUsername(wxUnionId);
if (userDetails != null) {
return new WeiXinAuthenticationToken(userDetails.getUsername(), userDetails, state);
}
throw new UsernameNotFoundException("微信用户不存在," + wxUnionId);
}
}