SpringSecurity登陸原理(源碼級講解)

1、簡單敘述

首先會進入UsernamePasswordAuthenticationFilter而且設置權限爲null和是否受權爲false,而後進入ProviderManager查找支持UsernamepasswordAuthenticationTokenprovider而且調用provider.authenticate(authentication);再而後就是UserDetailsService接口的實現類(也就是本身真正具體的業務了),這時候都檢查過了後,就會回調UsernamePasswordAuthenticationFilter而且設置權限(具體業務所查出的權限)和設置受權爲true(由於這時候確實全部關卡都檢查過了)。html

PS:雲裏霧繞的?不要緊,接下里看咱們每一步驟都具體的深刻到源碼級別的去分析。java


2、源碼分析

UsernamePasswordAuthenticationFilterspring

// 繼承了AbstractAuthenticationProcessingFilter
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 認證請求的方式必須爲POST
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        // 獲取用戶名
        String username = obtainUsername(request);
        // 獲取密碼
        String password = obtainPassword(request);

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

        if (password == null) {
            password = "";
        }
        // 用戶名去空白
        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}

能夠發現繼承了AbstractAuthenticationProcessingFilter,那咱們就來看下此類數據庫

public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean implements ApplicationEventPublisherAware, MessageSourceAware {
    
    // 過濾器doFilter方法
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        /* * 判斷當前filter是否能夠處理當前請求,若不行,則交給下一個filter去處理。 */
        if (!requiresAuthentication(request, response)) {
            chain.doFilter(request, response);

            return;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Request is to process authentication");
        }

        Authentication authResult;

        try {
            // 很關鍵!!!調用了子類(UsernamePasswordAuthenticationFilter)的方法
            authResult = attemptAuthentication(request, response);
            if (authResult == null) {
                // return immediately as subclass has indicated that it hasn't completed
                // authentication
                return;
            }
            // 最終認證成功後,會處理一些與session相關的方法(好比將認證信息存到session等操做)。
            sessionStrategy.onAuthentication(authResult, request, response);
        }
        catch (InternalAuthenticationServiceException failed) {
            logger.error(
                    "An internal error occurred while trying to authenticate the user.",
                    failed);
            // 認證失敗後的一些處理。
            unsuccessfulAuthentication(request, response, failed);

            return;
        }
        catch (AuthenticationException failed) {
            // Authentication failed
            unsuccessfulAuthentication(request, response, failed);

            return;
        }

        // Authentication success
        if (continueChainBeforeSuccessfulAuthentication) {
            chain.doFilter(request, response);
        }
        /* * 最終認證成功後的相關回調方法,主要將當前的認證信息放到SecurityContextHolder中 * 並調用成功處理器作相應的操做。 */
        successfulAuthentication(request, response, chain, authResult);
    }
}

PS:看到這裏估計不少人在罵娘了,什麼玩意,直接複製粘貼也不講解,不要急,上面只是看下類結構,下面來具體分析!這裏只分析主要代碼,不是很主要也不是很相關的不做講解,有興趣的本身去讀。緩存

(一)、 父類的處理流程

一、繼承了父類,父類是個過濾器,因此確定先執行AbstractAuthenticationProcessingFilter.doFilter(),此方法首先判斷當前的filter是否能夠處理當前請求,不能夠的話則交給下一個filter處理。安全

/* * 判斷當前filter是否能夠處理當前請求,若不行,則交給下一個filter去處理。 */
if (!requiresAuthentication(request, response)) {
    chain.doFilter(request, response);
    return;
}

二、調用此抽象類的子類UsernamePasswordAuthenticationFilter.attemptAuthentication(request, response)方法作具體的操做。markdown

// 很關鍵!!!調用了子類(UsernamePasswordAuthenticationFilter)的方法
authResult = attemptAuthentication(request, response);

三、最終認證成功後作一些成功後的session操做,好比將認證信息存到session等。session

// 最終認證成功後,會處理一些與session相關的方法(好比將認證信息存到session等操做)。
sessionStrategy.onAuthentication(authResult, request, response);

四、最終認證成功後的相關回調方法,主要將當前的認證信息放到SecurityContextHolder中並調用成功處理器作相應的操做。app

successfulAuthentication(request, response, chain, authResult);

protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
    }
    
    // 將當前的認證信息放到SecurityContextHolder中
    SecurityContextHolder.getContext().setAuthentication(authResult);
    rememberMeServices.loginSuccess(request, response, authResult);
    // Fire event
    if (this.eventPublisher != null) {
        eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
                authResult, this.getClass()));
    }
    // 調用成功處理器,能夠本身實現AuthenticationSuccessHandler接口重寫方法寫本身的邏輯
    successHandler.onAuthenticationSuccess(request, response, authResult);
}

(二)、子類的處理流程

一、父類的authResult = attemptAuthentication(request, response);觸發了自類的方法。ide

二、此方法首先判斷請求方式是否是POST提交,必須是POST

// 認證請求的方式必須爲POST
if (postOnly && !request.getMethod().equals("POST")) {
    throw new AuthenticationServiceException(
            "Authentication method not supported: " + request.getMethod());
}

三、從請求中獲取usernamepassword,並作一些處理

// 獲取用戶名
String username = obtainUsername(request);
// 獲取密碼
String password = obtainPassword(request);

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

if (password == null) {
    password = "";
}
// 用戶名去空白
username = username.trim();

四、封裝Authenticaiton類的實現類UsernamePasswordAuthenticationToken

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
        username, password);
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
    super((Collection)null);
    this.principal = principal;
    this.credentials = credentials;
    this.setAuthenticated(false);
}

PS:爲何這個構造器設置權限爲null?super((Collection)null);,而且設置是否受權爲false?this.setAuthenticated(false);

道理很簡單,由於咱們這是剛剛登錄過來,你的帳號密碼對不對咱們都沒驗證呢,因此這裏是未受權,權限null。

五、調用AuthenticationManagerauthenticate方法進行驗證

return this.getAuthenticationManager().authenticate(authRequest);

(三)、AuthenticationManager處理流程

一、怎麼觸發的?

return this.getAuthenticationManager().authenticate(authRequest);

PS:交由AuthenticationManager接口的ProviderManager實現類處理。

二、ProviderManager.authenticate(Authentication authentication);

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Class toTest = authentication.getClass();
        Object lastException = null;
        Authentication result = null;
        boolean debug = logger.isDebugEnabled();
        // 拿到所有的provider
        Iterator e = this.getProviders().iterator();
        // 遍歷provider
        while(e.hasNext()) {
            AuthenticationProvider provider = (AuthenticationProvider)e.next();
            // 挨着個的校驗是否支持當前token
            if(provider.supports(toTest)) {
                if(debug) {
                    logger.debug("Authentication attempt using " + provider.getClass().getName());
                }

                try {
                    // 找到後直接break,並由當前provider來進行校驗工做
                    result = provider.authenticate(authentication);
                    if(result != null) {
                        this.copyDetails(authentication, result);
                        break;
                    }
                } catch (AccountStatusException var11) {
                    this.prepareException(var11, authentication);
                    throw var11;
                } catch (InternalAuthenticationServiceException var12) {
                    this.prepareException(var12, authentication);
                    throw var12;
                } catch (AuthenticationException var13) {
                    lastException = var13;
                }
            }
        }
        // 若沒有一個支持,則嘗試交給父類來執行
        if(result == null && this.parent != null) {
            try {
                result = this.parent.authenticate(authentication);
            } catch (ProviderNotFoundException var9) {
                ;
            } catch (AuthenticationException var10) {
                lastException = var10;
            }
        }
    ..........................
    }

**三、此方法遍歷全部的Providers,而後依次執行驗證方法看是否支持UsernamepasswordAuthenticationToken**

// 拿到所有的provider
Iterator e = this.getProviders().iterator();
// 遍歷provider
while(e.hasNext()) {
    AuthenticationProvider provider = (AuthenticationProvider)e.next();
    // 挨着個的校驗是否支持當前token
    if(provider.supports(toTest)) {
        if(debug) {
            logger.debug("Authentication attempt using " + provider.getClass().getName());
        }
    }
}

四、如有一個可以支持當前token,則直接交由此provider處理並break。

// 找到後直接break,並由當前provider來進行校驗工做
result = provider.authenticate(authentication);
if(result != null) {
    this.copyDetails(authentication, result);
    break;
}

五、若沒一個provider驗證成功,則交由父類來嘗試處理

// 若沒有一個支持,則嘗試交給父類來執行
if(result == null && this.parent != null) {
    try {
        result = this.parent.authenticate(authentication);
    } catch (ProviderNotFoundException var9) {
        ;
    } catch (AuthenticationException var10) {
        lastException = var10;
    }
}

(四)、AuthenticationProvider處理流程

一、怎麼觸發的?

// 由上一步的ProviderManager的authenticate方法來觸發
result = provider.authenticate(authentication);

PS:這裏交由AuthenticationProvider接口的實現類DaoAuthenticationProvider來處理。

二、DaoAuthenticationProvider

// 繼承了AbstractUserDetailsAuthenticationProvider
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        UserDetails loadedUser;
        try {
            /* * 調用UserDetailsService接口的loadUserByUsername方法, * 此方法就是咱們本身定義的類去實現接口重寫的方法,處理咱們本身的業務邏輯。 */
            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
        } catch (UsernameNotFoundException var6) {
            if(authentication.getCredentials() != null) {
                String presentedPassword = authentication.getCredentials().toString();
                this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null);
            }

            throw var6;
        } catch (Exception var7) {
            throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
        }

        if(loadedUser == null) {
            throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
        } else {
            return loadedUser;
        }
    }
}

三、繼承了AbstractUserDetailsAuthenticationProvider

// 實現了AuthenticationProvider接口
public abstract class AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
  
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
        String username = authentication.getPrincipal() == null?"NONE_PROVIDED":authentication.getName();
        boolean cacheWasUsed = true;
        UserDetails user = this.userCache.getUserFromCache(username);
        if(user == null) {
            cacheWasUsed = false;

            try {
                // 調用自類retrieveUser
                user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
            } catch (UsernameNotFoundException var6) {
                this.logger.debug("User \'" + username + "\' not found");
                if(this.hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }

                throw var6;
            }

            Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
        }

        try {
            /* * 前檢查由DefaultPreAuthenticationChecks類實現(主要判斷當前用戶是否鎖定,過時,凍結 * User接口) */
            this.preAuthenticationChecks.check(user);
            // 子類具體實現
            this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
        } catch (AuthenticationException var7) {
            if(!cacheWasUsed) {
                throw var7;
            }
            cacheWasUsed = false;
            user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
            this.preAuthenticationChecks.check(user);
            this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
        }
        // 檢測用戶密碼是否過時
        this.postAuthenticationChecks.check(user);
        if(!cacheWasUsed) {
            this.userCache.putUserInCache(user);
        }

        Object principalToReturn = user;
        if(this.forcePrincipalAsString) {
            principalToReturn = user.getUsername();
        }

        return this.createSuccessAuthentication(principalToReturn, authentication, user);
    }
}

四、AbstractUserDetailsAuthenticationProvider.authenticate()首先調用了user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);

PS:調用的是DaoAuthenticationProvider.retrieveUser()

五、調用咱們本身的業務處理類

/* * 調用UserDetailsService接口的loadUserByUsername方法, * 此方法就是咱們本身定義的類去實現接口重寫的方法,處理咱們本身的業務邏輯。 */
 loadedUser = this.getUserDetailsService().loadUserByUsername(username);

好比:

/** * @author chentongwei@bshf360.com 2018-03-26 13:15 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("表單登陸用戶名:" + username);
        return buildUser(username);
    }

    private UserDetails buildUser(String username) {
        /** * passwordEncoder.encode這步驟應該放到註冊接口去作,而這裏只須要傳一個從db查出來的pwd便可。 * * passwordEncoder.encode("123456")每次打印出來都是不一樣的,雖然是同一個(123456)密碼, * 可是他會隨機生成一個鹽(salt),他會把隨機生成的鹽混到加密的密碼裏。Springsecurity驗證(matches方法)的時候會將利用此鹽解析出pwd,進行匹配。 * 這樣的好處是:若是數據庫裏面有10個123456密碼。可是被破解了1個,那麼另外九個是安全的,由於db裏存的串是不同的。 */
        String password = passwordEncoder.encode("123456");
        logger.info("數據庫密碼是:" + password);
        // 這個User不必定必須用SpringSecurity的,能夠寫一個自定義實現UserDetails接口的類,而後把是否鎖定等判斷邏輯寫進去。
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

PS:注意:實現UserDetailsService接口。可返回咱們本身定義的User類,但User類要實現UserDetails接口

六、調用完retrieveUser方法繼續回到抽象類的authenticate方法

七、首先作一些檢查

/* * 前檢查由DefaultPreAuthenticationChecks類實現(主要判斷當前用戶是否鎖定,過時,凍結 * User接口) */
this.preAuthenticationChecks.check(user);
// 檢測用戶密碼是否過時
this.postAuthenticationChecks.check(user);

八、調用createSuccessAuthentication方法進行受權成功

return this.createSuccessAuthentication(principalToReturn, authentication, user);
// 成功受權
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
    // 回調UsernamePasswordAuthenticationToken的構造器,這裏調用的是受權成功的構造器
    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
    // 將認證信息的一塊內容放到details
    result.setDetails(authentication.getDetails());
    return result;
}
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
    // 不在是null,而是傳來的權限,這個權限就是咱們本身定義的detailsService類所返回的,能夠從db查
    super(authorities);
    this.principal = principal;
    this.credentials = credentials;
    // 這裏是true,不在是false。
    super.setAuthenticated(true);
}

九、回到起點

AbstractAuthenticationProcessingFilter.doFilter()

進行session存儲和成功後的處理器的調用等


3、總結

只是簡單說下類之間的調用順序。

UsernamePasswordAuthenticationFilter
Authentication
AuthenticationManager
AuthenticationProvider
UserDetailsService
// 回到起點進行後續操做,好比緩存認證信息到session和調用成功後的處理器等等
UsernamePasswordAuthenticationFilter

4、Demo

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>登陸</title>
</head>
<body>
<h2>標準登陸頁面</h2>
<h3>表單登陸</h3>
<form action="login" method="post">
    <table>
        <tr>
            <td>用戶名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密碼:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2"><button type="submit">登陸</button></td>
        </tr>
    </table>
</form>
</body>
</html>
http.formLogin()
    // 默認表單登陸頁
    .loginPage(SecurityConstant.DEFAULT_UNAUTHENTICATION_URL)
    // 登陸接口
    .loginProcessingUrl(SecurityConstant.DEFAULT_LOGIN_PROCESSING_URL_FORM)
/** * 常量 * * @author chentongwei@bshf360.com 2018-03-26 11:40 */
public interface SecurityConstant {

    /** * 默認登陸頁 */
    String DEFAULT_LOGIN_PAGE_URL = "/default-login.html";

    /** * 默認的登陸接口 */
    String DEFAULT_LOGIN_PROCESSING_URL_FORM = "/login";
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
/** * @author chentongwei@bshf360.com 2018-03-26 13:15 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("表單登陸用戶名:" + username);
        return buildUser(username);
    }

    private UserDetails buildUser(String username) {
        /** * passwordEncoder.encode這步驟應該放到註冊接口去作,而這裏只須要傳一個從db查出來的pwd便可。 * * passwordEncoder.encode("123456")每次打印出來都是不一樣的,雖然是同一個(123456)密碼, * 可是他會隨機生成一個鹽(salt),他會把隨機生成的鹽混到加密的密碼裏。Springsecurity驗證(matches方法)的時候會將利用此鹽解析出pwd,進行匹配。 * 這樣的好處是:若是數據庫裏面有10個123456密碼。可是被破解了1個,那麼另外九個是安全的,由於db裏存的串是不同的。 */
        String password = passwordEncoder.encode("123456");
        logger.info("數據庫密碼是:" + password);
        // 這個User不必定必須用SpringSecurity的,能夠寫一個自定義實現UserDetails接口的類,而後把是否鎖定等判斷邏輯寫進去。
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

大功告成!

只須要一個html,一段配置,一個Service本身的業務類便可。

疑問:

一、接口login在哪定義的?

二、用戶名username和密碼password在哪接收的?

三、沒有控制器怎麼進入咱們的MyUserDetailsService的方法?

解答:

一、SpringSecurity內置的,而且只能爲POST

public UsernamePasswordAuthenticationFilter() {
    super(new AntPathRequestMatcher("/login", "POST"));
}

二、名稱不能變,必須是usernamepassword

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
   // ~ Static fields/initializers
   // =====================================================================================

   public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
   public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
}

三、本身看我上面的源碼分析

原文地址:https://www.jianshu.com/p/a65f883de0c1
相關文章
相關標籤/搜索