Spring Security原始碼分析二:Spring Security授權過程

鄭龍飛發表於2018-01-05

前言

本文是接上一章Spring Security原始碼分析一:Spring Security認證過程進一步分析Spring Security使用者名稱密碼登入授權是如何實現得;

類圖

https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c4a662d2?w=1522&h=914&f=png&s=34820
https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c4a662d2?w=1522&h=914&f=png&s=34820

除錯過程

使用debug方式啟動github.com/longfeizhen…該專案,瀏覽器輸入http://localhost:8080/persons,使用者名稱隨意,密碼123456即可;

原始碼分析

如圖所示,顯示了登入認證過程中的 filters 相關的呼叫流程,作者將幾個自認為重要的 filters 標註了出來,

https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c4868b1d?w=1062&h=933&f=png&s=306860
https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c4868b1d?w=1062&h=933&f=png&s=306860

從圖中可以看出執行的順序。來看看幾個作者認為比較重要的 Filter 的處理邏輯,UsernamePasswordAuthenticationFilterAnonymousAuthenticationFilterExceptionTranslationFilterFilterSecurityInterceptor 以及相關的處理流程如下所述;

UsernamePasswordAuthenticationFilter

整個呼叫流程是,先呼叫其父類 AbstractAuthenticationProcessingFilter.doFilter() 方法,然後再執行 UsernamePasswordAuthenticationFilter.attemptAuthentication() 方法進行驗證;

AbstractAuthenticationProcessingFilter

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		#1.判斷當前的filter是否可以處理當前請求,不可以的話則交給下一個filter處理
		if (!requiresAuthentication(request, response)) {
			chain.doFilter(request, response);

			return;
		}

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

		Authentication authResult;

		try {
			#2.抽象方法由子類UsernamePasswordAuthenticationFilter實現
			authResult = attemptAuthentication(request, response);
			if (authResult == null) {
				// return immediately as subclass has indicated that it hasn't completed
				// authentication
				return;
			}
			#2.認證成功後,處理一些與session相關的方法 
			sessionStrategy.onAuthentication(authResult, request, response);
		}
		catch (InternalAuthenticationServiceException failed) {
			logger.error(
					"An internal error occurred while trying to authenticate the user.",
					failed);
			#3.認證失敗後的的一些操作
			unsuccessfulAuthentication(request, response, failed);

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

			return;
		}

		// Authentication success
		if (continueChainBeforeSuccessfulAuthentication) {
			chain.doFilter(request, response);
		}
		#3. 認證成功後的相關回撥方法 主要將當前的認證放到SecurityContextHolder中
		successfulAuthentication(request, response, chain, authResult);
	}
複製程式碼

整個程式的執行流程如下:

  1. 判斷filter是否可以處理當前的請求,如果不可以則放行交給下一個filter
  2. 呼叫抽象方法attemptAuthentication進行驗證,該方法由子類UsernamePasswordAuthenticationFilter實現
  3. 認證成功以後,回撥一些與 session 相關的方法;
  4. 認證成功以後,認證成功後的相關回撥方法;認證成功以後,認證成功後的相關回撥方法;
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.getContext().setAuthentication(authResult);

		rememberMeServices.loginSuccess(request, response, authResult);

		// Fire event
		if (this.eventPublisher != null) {
			eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
					authResult, this.getClass()));
		}

		successHandler.onAuthenticationSuccess(request, response, authResult);
	}
複製程式碼
1. 將當前認證成功的 Authentication 放置到 SecurityContextHolder 中;
2. 將當前認證成功的 Authentication 放置到 SecurityContextHolder 中;
3. 呼叫其它可擴充套件的 handlers 繼續處理該認證成功以後的回撥事件;(實現`AuthenticationSuccessHandler`介面即可)
複製程式碼

UsernamePasswordAuthenticationFilter

public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		#1.判斷請求的方法必須為POST請求
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}
		#2.從request中獲取username和password
		String username = obtainUsername(request);
		String password = obtainPassword(request);

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

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

		username = username.trim();
		#3.構建UsernamePasswordAuthenticationToken(兩個引數的構造方法setAuthenticated(false))
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
				username, password);

		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		#4. 呼叫 AuthenticationManager 進行驗證(子類ProviderManager遍歷所有的AuthenticationProvider認證)
		return this.getAuthenticationManager().authenticate(authRequest);
	}
複製程式碼
  1. 認證請求的方法必須為POST
  2. 從request中獲取 username 和 password
  3. 封裝Authenticaiton的實現類UsernamePasswordAuthenticationToken,(UsernamePasswordAuthenticationToken呼叫兩個引數的構造方法setAuthenticated(false))
  4. 呼叫 AuthenticationManagerauthenticate 方法進行驗證;可參考ProviderManager部分;

AnonymousAuthenticationFilter

從上圖中過濾器的執行順序圖中可以看出AnonymousAuthenticationFilter過濾器是在UsernamePasswordAuthenticationFilter等過濾器之後,如果它前面的過濾器都沒有認證成功,Spring Security則為當前的SecurityContextHolder中新增一個Authenticaiton 的匿名實現類AnonymousAuthenticationToken;

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		#1.如果前面的過濾器都沒認證通過,則SecurityContextHolder中Authentication為空
		if (SecurityContextHolder.getContext().getAuthentication() == null) {
			#2.為當前的SecurityContextHolder中新增一個匿名的AnonymousAuthenticationToken
			SecurityContextHolder.getContext().setAuthentication(
					createAuthentication((HttpServletRequest) req));

			if (logger.isDebugEnabled()) {
				logger.debug("Populated SecurityContextHolder with anonymous token: '"
						+ SecurityContextHolder.getContext().getAuthentication() + "'");
			}
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("SecurityContextHolder not populated with anonymous token, as it already contained: '"
						+ SecurityContextHolder.getContext().getAuthentication() + "'");
			}
		}

		chain.doFilter(req, res);
	}

	#3.建立匿名的AnonymousAuthenticationToken
	protected Authentication createAuthentication(HttpServletRequest request) {
		AnonymousAuthenticationToken auth = new AnonymousAuthenticationToken(key,
				principal, authorities);
		auth.setDetails(authenticationDetailsSource.buildDetails(request));

		return auth;
	}
	
		/**
	 * Creates a filter with a principal named "anonymousUser" and the single authority
	 * "ROLE_ANONYMOUS".
	 *
	 * @param key the key to identify tokens created by this filter
	 */
	 ##.建立一個使用者名稱為anonymousUser 授權為ROLE_ANONYMOUS
	public AnonymousAuthenticationFilter(String key) {
		this(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
	}
複製程式碼
  1. 判斷SecurityContextHolder中Authentication為否為空;
  2. 如果空則為當前的SecurityContextHolder中新增一個匿名的AnonymousAuthenticationToken(使用者名稱為 anonymousUser 的AnonymousAuthenticationToken

ExceptionTranslationFilter

ExceptionTranslationFilter 異常處理過濾器,該過濾器用來處理在系統認證授權過程中丟擲的異常(也就是下一個過濾器FilterSecurityInterceptor),主要是 處理 AuthenticationExceptionAccessDeniedException

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		try {
			chain.doFilter(request, response);

			logger.debug("Chain processed normally");
		}
		catch (IOException ex) {
			throw ex;
		}
		catch (Exception ex) {
			// Try to extract a SpringSecurityException from the stacktrace
			#.判斷是不是AuthenticationException
			Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
			RuntimeException ase = (AuthenticationException) throwableAnalyzer
					.getFirstThrowableOfType(AuthenticationException.class, causeChain);

			if (ase == null) {
				#. 判斷是不是AccessDeniedException
				ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(
						AccessDeniedException.class, causeChain);
			}

			if (ase != null) {
				handleSpringSecurityException(request, response, chain, ase);
			}
			else {
				// Rethrow ServletExceptions and RuntimeExceptions as-is
				if (ex instanceof ServletException) {
					throw (ServletException) ex;
				}
				else if (ex instanceof RuntimeException) {
					throw (RuntimeException) ex;
				}

				// Wrap other Exceptions. This shouldn't actually happen
				// as we've already covered all the possibilities for doFilter
				throw new RuntimeException(ex);
			}
		}
	}
複製程式碼

FilterSecurityInterceptor

此過濾器為認證授權過濾器鏈中最後一個過濾器,該過濾器之後就是請求真正的/persons 服務

public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		FilterInvocation fi = new FilterInvocation(request, response, chain);
		invoke(fi);
	}

public void invoke(FilterInvocation fi) throws IOException, ServletException {
		if ((fi.getRequest() != null)
				&& (fi.getRequest().getAttribute(FILTER_APPLIED) != null)
				&& observeOncePerRequest) {
			// filter already applied to this request and user wants us to observe
			// once-per-request handling, so don't re-do security checking
			fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
		}
		else {
			// first time this request being called, so perform security checking
			if (fi.getRequest() != null) {
				fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
			}
			#1. before invocation重要
			InterceptorStatusToken token = super.beforeInvocation(fi);

			try {
				#2. 可以理解開始請求真正的 /persons 服務
				fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
			}
			finally {
				super.finallyInvocation(token);
			}
			#3. after Invocation
			super.afterInvocation(token, null);
		}
	}
複製程式碼
  1. before invocation重要
  2. 請求真正的 /persons 服務
  3. after Invocation

三個部分中,最重要的是 #1,該過程中會呼叫 AccessDecisionManager 來驗證當前已認證成功的使用者是否有許可權訪問該資源;

before invocation: AccessDecisionManager

protected InterceptorStatusToken beforeInvocation(Object object) {
		...

		Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
				.getAttributes(object);

		...
		Authentication authenticated = authenticateIfRequired();

		// Attempt authorization
		try {
			#1.重點
			this.accessDecisionManager.decide(authenticated, object, attributes);
		}
		catch (AccessDeniedException accessDeniedException) {
			publishEvent(new AuthorizationFailureEvent(object, attributes, authenticated,accessDeniedException));

			throw accessDeniedException;
		}

		...
	}
複製程式碼

authenticated就是當前認證的Authentication,那麼objectattributes又是什麼呢?

attributes和object 是什麼?

Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
				.getAttributes(object);
複製程式碼

除錯

https://user-gold-cdn.xitu.io/2018/1/5/160c51a0b928457e?w=1220&h=1005&f=png&s=452529
https://user-gold-cdn.xitu.io/2018/1/5/160c51a0b928457e?w=1220&h=1005&f=png&s=452529

我們發現object為當前請求的 url:/persons, 那麼getAttributes方法就是使用當前的訪問資源路徑去匹配我們自己定義的匹配規則。

protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//使用表單登入,不再使用預設httpBasic方式
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)//如果請求的URL需要認證則跳轉的URL
                .loginProcessingUrl(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM)//處理表單中自定義的登入URL
                .and()
                .authorizeRequests().antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM,
                SecurityConstants.DEFAULT_REGISTER_URL,
                "/**/*.js",
                "/**/*.css",
                "/**/*.jpg",
                "/**/*.png",
                "/**/*.woff2")
                .permitAll()//以上的請求都不需要認證
                .anyRequest()//剩下的請求
                .authenticated()//都需要認證
                .and()
                .csrf().disable()//關閉csrd攔截
        ;
    }
複製程式碼

0-7返回 permitALL即不需要認證 ,8對應anyRequest返回 authenticated即當前請求需要認證;

https://user-gold-cdn.xitu.io/2018/1/5/160c51a0bbef6204?w=1217&h=789&f=png&s=207895
https://user-gold-cdn.xitu.io/2018/1/5/160c51a0bbef6204?w=1217&h=789&f=png&s=207895

可以看到當前的authenticated為匿名AnonymousAuthentication使用者名稱為anonymousUser

AccessDecisionManager 是如何授權的?

Spring Security預設使用AffirmativeBased實現AccessDecisionManagerdecide 方法來實現授權

public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes) throws AccessDeniedException {
		int deny = 0;
		#1.呼叫AccessDecisionVoter 進行vote(投票)
		for (AccessDecisionVoter voter : getDecisionVoters()) {
			int result = voter.vote(authentication, object, configAttributes);

			if (logger.isDebugEnabled()) {
				logger.debug("Voter: " + voter + ", returned: " + result);
			}

			switch (result) {
			#1.1只要有voter投票為ACCESS_GRANTED,則通過 直接返回
			case AccessDecisionVoter.ACCESS_GRANTED://1
				return;
			@#1.2只要有voter投票為ACCESS_DENIED,則記錄一下
			case AccessDecisionVoter.ACCESS_DENIED://-1
				deny++;

				break;

			default:
				break;
			}
		}

		if (deny > 0) {
		#2.如果有兩個及以上AccessDecisionVoter(姑且稱之為投票者吧)都投ACCESS_DENIED,則直接就不通過了
			throw new AccessDeniedException(messages.getMessage(
					"AbstractAccessDecisionManager.accessDenied", "Access is denied"));
		}

		// To get this far, every AccessDecisionVoter abstained
		checkAllowIfAllAbstainDecisions();
	}
複製程式碼
  1. 呼叫AccessDecisionVoter 進行vote(投票)
  2. 只要有投通過(ACCESS_GRANTED)票,則直接判為通過。
  3. 如果沒有投通過則 deny++ ,最後判斷if(deny>0 丟擲AccessDeniedException(未授權)

WebExpressionVoter.vote()

public int vote(Authentication authentication, FilterInvocation fi,
			Collection<ConfigAttribute> attributes) {
		assert authentication != null;
		assert fi != null;
		assert attributes != null;

		WebExpressionConfigAttribute weca = findConfigAttribute(attributes);

		if (weca == null) {
			return ACCESS_ABSTAIN;
		}

		EvaluationContext ctx = expressionHandler.createEvaluationContext(authentication,
				fi);
		ctx = weca.postProcess(ctx, fi);

		return ExpressionUtils.evaluateAsBoolean(weca.getAuthorizeExpression(), ctx) ? ACCESS_GRANTED
				: ACCESS_DENIED;
	}
複製程式碼

到此位置authentication當前使用者資訊,fl當前訪問的資源路徑及attributes當前資源路徑的決策(即是否需要認證)。剩下就是判斷當前使用者的角色Authentication.authorites是否許可權訪問決策訪問當前資源fi

時序圖

https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c490ea00?w=2466&h=1592&f=png&s=133615
https://user-gold-cdn.xitu.io/2018/1/5/160c51a0c490ea00?w=2466&h=1592&f=png&s=133615

相關文章