Spring Security Web 5.1.2ソース解析-BaicAuthentication Filter


概要
処理HTTPは、要求されたBASIC authorizationのヘッダに、認証結果をSecurityContextHolderに書き込む.HTTPの要求にAuthorizationという名前のヘッダが含まれており、その値フォーマットがBasic xxxである場合、FilterBASIC authorizationの頭部であると考えられ、xxxの部分はbase64の符号化された{username}:{password}文字列であるべきである.例えば、ユーザ名/パスワードがそれぞれadmin/secretである場合、対応するヘッダはBasic YWRtaW46c2VjcmV0である.
このフィルタは、HTTP BASIC authorizationのヘッダからそれぞれのユーザ名とパスワードを解析し、AuthenticationManagerを呼び出して認証し、成功すれば、認証された結果をSecurityContextHolderSecurityContextの属性authenticationに書き込む.また、Remember Meなどの他の処理も行われる.
頭の解析が失敗したら、このフィルタは異常BadCredentialsExceptionを投げます.
認証に失敗した場合、SecurityContextHolderSecurityContextが消去される.そして、filter chainの実行を続行しない.
ソースコード解析
package org.springframework.security.web.authentication.www;

import java.io.IOException;
import java.util.Base64;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;


public class BasicAuthenticationFilter extends OncePerRequestFilter {

	// ~ Instance fields
	// ================================================================================================

	//   Authentication     details          	
	private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = 
		new WebAuthenticationDetailsSource();
	private AuthenticationEntryPoint authenticationEntryPoint;
	private AuthenticationManager authenticationManager;
	private RememberMeServices rememberMeServices = new NullRememberMeServices();
	private boolean ignoreFailure = false;
	private String credentialsCharset = "UTF-8";

	/**
	 * Creates an instance which will authenticate against the supplied
	 *  AuthenticationManager and which will ignore failed authentication attempts,
	 * allowing the request to proceed down the filter chain.
	 *
	 * @param authenticationManager the bean to submit authentication requests to
	 */
	public BasicAuthenticationFilter(AuthenticationManager authenticationManager) {
		Assert.notNull(authenticationManager, "authenticationManager cannot be null");
		this.authenticationManager = authenticationManager;
		this.ignoreFailure = true;
	}

	/**
	 * Creates an instance which will authenticate against the supplied
	 *  AuthenticationManager and use the supplied  AuthenticationEntryPoint
	 * to handle authentication failures.
	 *
	 * @param authenticationManager the bean to submit authentication requests to
	 * @param authenticationEntryPoint will be invoked when authentication fails.
	 * Typically an instance of  BasicAuthenticationEntryPoint.
	 */
	public BasicAuthenticationFilter(AuthenticationManager authenticationManager,
			AuthenticationEntryPoint authenticationEntryPoint) {
		Assert.notNull(authenticationManager, "authenticationManager cannot be null");
		Assert.notNull(authenticationEntryPoint,
				"authenticationEntryPoint cannot be null");
		this.authenticationManager = authenticationManager;
		this.authenticationEntryPoint = authenticationEntryPoint;
	}

	// ~ Methods
	// ========================================================================================================

	@Override
	public void afterPropertiesSet() {
		Assert.notNull(this.authenticationManager,
				"An AuthenticationManager is required");

		if (!isIgnoreFailure()) {
			Assert.notNull(this.authenticationEntryPoint,
					"An AuthenticationEntryPoint is required");
		}
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		final boolean debug = this.logger.isDebugEnabled();

		//        Authorization
		String header = request.getHeader("Authorization");

		if (header == null || !header.toLowerCase().startsWith("basic ")) {
			//      Authorization         basic     ,   
			//              ,    ,  filter chain    
			chain.doFilter(request, response);
			return;
		}

		//      http basic authentication      ,    ,     
		//      Authorization       (      ) : "basic xxxxxx"
		try {
			//      Authorization         
			String[] tokens = extractAndDecodeHeader(header, request);
			assert tokens.length == 2;

			//    tokens[0]      , tokens[1]     
			String username = tokens[0];

			if (debug) {
				this.logger
						.debug("Basic Authentication Authorization header found for user '"
								+ username + "'");
			}

			//             username       
			if (authenticationIsRequired(username)) {
				//       ,          /       UsernamePasswordAuthenticationToken,
				//         
				UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
						username, tokens[1]);
				authRequest.setDetails(
						this.authenticationDetailsSource.buildDetails(request));
				
				//     		
				Authentication authResult = this.authenticationManager
						.authenticate(authRequest);

				if (debug) {
					this.logger.debug("Authentication success: " + authResult);
				}
				
				//     ,      Authentication authRequest    SecurityContextHolder 
				//    SecurityContext  。
				SecurityContextHolder.getContext().setAuthentication(authResult);

				//       RememberMe      
				this.rememberMeServices.loginSuccess(request, response, authResult);

				//           :         ,     
				onSuccessfulAuthentication(request, response, authResult);
			}

		}
		catch (AuthenticationException failed) {
			//     ,   SecurityContextHolder       
			SecurityContextHolder.clearContext();

			if (debug) {
				this.logger.debug("Authentication request for failed: " + failed);
			}

			//      RememberMe      
			this.rememberMeServices.loginFail(request, response);

			//           :         ,     
			onUnsuccessfulAuthentication(request, response, failed);

			if (this.ignoreFailure) {
				chain.doFilter(request, response);
			}
			else {
				this.authenticationEntryPoint.commence(request, response, failed);
			}

			return;
		}

		//            http basic authentication      ,     ,  filter chain   
		chain.doFilter(request, response);
	}

	/**
	 * Decodes the header into a username and password.
	 *      http basic authentication                
	 *
	 * @throws BadCredentialsException if the Basic header is not present or is not valid
	 * Base64
	 */
	private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
			throws IOException {

		// 	     6          ,         UTF-8
		//   :        "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
		//             "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="  
		byte[] base64Token = header.substring(6).getBytes("UTF-8");
		
		
		//    Base64          base64Token
		byte[] decoded;
		try {
			decoded = Base64.getDecoder().decode(base64Token);
		}
		catch (IllegalArgumentException e) {
			throw new BadCredentialsException(
					"Failed to decode basic authentication token");
		}

		//         credentialsCharset    "{   }:{  }"   
		// credentialsCharset      UTF-8
		String token = new String(decoded, getCredentialsCharset(request));

		//      ,      
		int delim = token.indexOf(":");

		if (delim == -1) {
			throw new BadCredentialsException("Invalid basic authentication token");
		}
		return new String[] { token.substring(0, delim), token.substring(delim + 1) };
	}

	private boolean authenticationIsRequired(String username) {
		// Only reauthenticate if username doesn't match SecurityContextHolder and user
		// isn't authenticated
		// (see SEC-53)
		Authentication existingAuth = SecurityContextHolder.getContext()
				.getAuthentication();

		//    SecurityContextHolder   SecurityContext   Authentication,
		//      null       ,       
		if (existingAuth == null || !existingAuth.isAuthenticated()) {
			return true;
		}

		// Limit username comparison to providers which use usernames (ie
		// UsernamePasswordAuthenticationToken)
		// (see SEC-348)

		//    SecurityContextHolder   SecurityContext   Authentication  
		//       ,             username    ,       
		if (existingAuth instanceof UsernamePasswordAuthenticationToken
				&& !existingAuth.getName().equals(username)) {
			return true;
		}

		// Handle unusual condition where an AnonymousAuthenticationToken is already
		// present
		// This shouldn't happen very often, as BasicProcessingFitler is meant to be
		// earlier in the filter
		// chain than AnonymousAuthenticationFilter. Nevertheless, presence of both an
		// AnonymousAuthenticationToken
		// together with a BASIC authentication request header should indicate
		// reauthentication using the
		// BASIC protocol is desirable. This behaviour is also consistent with that
		// provided by form and digest,
		// both of which force re-authentication if the respective header is detected (and
		// in doing so replace
		// any existing AnonymousAuthenticationToken). See SEC-610.
		
		//    SecurityContextHolder   SecurityContext   Authentication      ,
		//        
		if (existingAuth instanceof AnonymousAuthenticationToken) {
			return true;
		}

		//    SecurityContextHolder   SecurityContext   Authentication       ,
		//        username ,        
		return false;
	}

	
	protected void onSuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult) throws IOException {
	}

	protected void onUnsuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException failed)
					throws IOException {
	}

	protected AuthenticationEntryPoint getAuthenticationEntryPoint() {
		return this.authenticationEntryPoint;
	}

	protected AuthenticationManager getAuthenticationManager() {
		return this.authenticationManager;
	}

	protected boolean isIgnoreFailure() {
		return this.ignoreFailure;
	}

	public void setAuthenticationDetailsSource(
			AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
		Assert.notNull(authenticationDetailsSource,
				"AuthenticationDetailsSource required");
		this.authenticationDetailsSource = authenticationDetailsSource;
	}

	public void setRememberMeServices(RememberMeServices rememberMeServices) {
		Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
		this.rememberMeServices = rememberMeServices;
	}

	public void setCredentialsCharset(String credentialsCharset) {
		Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
		this.credentialsCharset = credentialsCharset;
	}

	protected String getCredentialsCharset(HttpServletRequest httpRequest) {
		return this.credentialsCharset;
	}
}

参考文献
  • Spring Security Web 5.1.2ソース解析-安全関連Filterリスト