前提條件
- 申請微信開放平臺賬號(掃碼登錄必須有微信開放平臺)
- 在開放平臺上創(chuàng)建一個網站應用,獲取AppID、AppSecret,并配置授權回調域。
- 集成weixin-java-mp
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
</dependency>
過程說明
如下圖所示,主要分為:用戶、統(tǒng)一認證服務和微信服務端

wxlogin.png
獲取微信掃碼地址
@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 = "微信回調后獲取微信用戶信息," +
"如果已存在且為有效狀態(tài),直接自動登錄, 登錄地址: /wxlogin/login" +
"如果不存在, 重定向到綁定頁面進行綁定" +
"如果無效狀態(tài), 重定向的登錄頁面并提示錯誤原因"
)
@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);
}
}