Spring OAuth2認證服務集成微信掃碼登錄

前提條件

  1. 申請微信開放平臺賬號(掃碼登錄必須有微信開放平臺)
  2. 在開放平臺上創(chuàng)建一個網站應用,獲取AppID、AppSecret,并配置授權回調域。
  3. 集成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);
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容