Spring Security原始碼分析五:Spring Security實現簡訊登入

鄭龍飛發表於2018-01-15

目前常見的社交軟體、購物軟體、支付軟體、理財軟體等,均需要使用者進行登入才可享受軟體提供的服務。目前主流的登入方式主要有 3 種:賬號密碼登入、簡訊驗證碼登入和第三方授權登入。我們已經實現了賬號密碼和第三方授權登入。本章我們將使用Spring Security實現簡訊驗證碼登入。

概述

Spring Security原始碼分析一:Spring Security認證過程Spring Security原始碼分析二:Spring Security授權過程兩章中。我們已經詳細解讀過Spring Security如何處理使用者名稱和密碼登入。(其實就是過濾器鏈)本章我們將仿照使用者名稱密碼來顯示簡訊登入。

目錄結構

https://user-gold-cdn.xitu.io/2018/1/14/160f3abd6445be85?w=439&h=248&f=png&s=13161
https://user-gold-cdn.xitu.io/2018/1/14/160f3abd6445be85?w=439&h=248&f=png&s=13161

SmsCodeAuthenticationFilter

SmsCodeAuthenticationFilter對應使用者名稱密碼登入的UsernamePasswordAuthenticationFilter同樣繼承AbstractAuthenticationProcessingFilter

public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * request中必須含有mobile引數
     */
    private String mobileParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE;
    /**
     * post請求
     */
    private boolean postOnly = true;

    protected SmsCodeAuthenticationFilter() {
        /**
         * 處理的手機驗證碼登入請求處理url
         */
        super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        //判斷是是不是post請求
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //從請求中獲取手機號碼
        String mobile = obtainMobile(request);

        if (mobile == null) {
            mobile = "";
        }

        mobile = mobile.trim();
        //建立SmsCodeAuthenticationToken(未認證)
        SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

        //設定使用者資訊
        setDetails(request, authRequest);
        //返回Authentication例項
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 獲取手機號
     */
    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(mobileParameter);
    }

    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setMobileParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.mobileParameter = usernameParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getMobileParameter() {
        return mobileParameter;
    }
}
複製程式碼
  1. 認證請求的方法必須為POST
  2. 從request中獲取手機號
  3. 封裝成自己的Authenticaiton的實現類SmsCodeAuthenticationToken(未認證)
  4. 呼叫 AuthenticationManagerauthenticate 方法進行驗證(即SmsCodeAuthenticationProvider

SmsCodeAuthenticationToken

SmsCodeAuthenticationToken對應使用者名稱密碼登入的UsernamePasswordAuthenticationToken

public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = 2383092775910246006L;

    /**
     * 手機號
     */
    private final Object principal;

    /**
     * SmsCodeAuthenticationFilter中構建的未認證的Authentication
     * @param mobile
     */
    public SmsCodeAuthenticationToken(String mobile) {
        super(null);
        this.principal = mobile;
        setAuthenticated(false);
    }

    /**
     * SmsCodeAuthenticationProvider中構建已認證的Authentication
     * @param principal
     * @param authorities
     */
    public SmsCodeAuthenticationToken(Object principal,
                                      Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true); // must use super, as we override
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    /**
     * @param isAuthenticated
     * @throws IllegalArgumentException
     */
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}
複製程式碼

SmsCodeAuthenticationProvider

SmsCodeAuthenticationProvider對應使用者名稱密碼登入的DaoAuthenticationProvider

public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        //呼叫自定義的userDetailsService認證
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if (user == null) {
            throw new InternalAuthenticationServiceException("無法獲取使用者資訊");
        }
        //如果user不為空重新構建SmsCodeAuthenticationToken(已認證)
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }
	
	/**
     * 只有Authentication為SmsCodeAuthenticationToken使用此Provider認證
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
複製程式碼

SmsCodeAuthenticationSecurityConfig簡訊登入配置

@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationFailureHandler merryyouAuthenticationFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //自定義SmsCodeAuthenticationFilter過濾器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(merryyouAuthenticationFailureHandler);

        //設定自定義SmsCodeAuthenticationProvider的認證器userDetailsService
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
        //在UsernamePasswordAuthenticationFilter過濾前執行
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

複製程式碼

MerryyouSecurityConfig 主配置檔案

 @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
        http
                .formLogin()//使用表單登入,不再使用預設httpBasic方式
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)//如果請求的URL需要認證則跳轉的URL
                .loginProcessingUrl(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM)//處理表單中自定義的登入URL
                .and()
                .apply(validateCodeSecurityConfig)//驗證碼攔截
                .and()
                .apply(smsCodeAuthenticationSecurityConfig)
                .and()
                .apply(merryyouSpringSocialConfigurer)//社交登入
                .and()
                .rememberMe()
......
複製程式碼

除錯過程

簡訊登入攔截請求/authentication/mobile

https://user-gold-cdn.xitu.io/2018/1/14/160f3abd6467cddd?w=1364&h=735&f=png&s=302724
https://user-gold-cdn.xitu.io/2018/1/14/160f3abd6467cddd?w=1364&h=735&f=png&s=302724

自定義SmsCodeAuthenticationProvider

https://user-gold-cdn.xitu.io/2018/1/14/160f3abd63fdfb98?w=917&h=708&f=png&s=238342
https://user-gold-cdn.xitu.io/2018/1/14/160f3abd63fdfb98?w=917&h=708&f=png&s=238342

效果如下:

https://user-gold-cdn.xitu.io/2018/1/14/160f3abd5b178799?w=1346&h=655&f=gif&s=2641171
https://user-gold-cdn.xitu.io/2018/1/14/160f3abd5b178799?w=1346&h=655&f=gif&s=2641171

程式碼下載

從我的 github 中下載,github.com/longfeizhen…

相關文章