Spring Security源碼分析五:Spring Security實現短信登陸

目前常見的社交軟件、購物軟件、支付軟件、理財軟件等,均須要用戶進行登陸纔可享受軟件提供的服務。目前主流的登陸方式主要有 3 種:帳號密碼登陸、短信驗證碼登陸和第三方受權登陸。咱們已經實現了帳號密碼和第三方受權登陸。本章咱們將使用Spring Security實現短信驗證碼登陸。java

概述

Spring Security源碼分析一:Spring Security認證過程Spring Security源碼分析二:Spring Security受權過程兩章中。咱們已經詳細解讀過Spring Security如何處理用戶名和密碼登陸。(其實就是過濾器鏈)本章咱們將仿照用戶名密碼來顯示短信登陸。git

目錄結構

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一樣繼承AbstractAuthenticationProcessingFiltergithub

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對應用戶名密碼登陸的UsernamePasswordAuthenticationTokenapp

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對應用戶名密碼登陸的DaoAuthenticationProvideride

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 post

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

效果以下: ui

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…this

相關文章
相關標籤/搜索