Spring Security - 15. BasicAuthenticationFilter

하쮸·2025년 2월 24일

1. BasicAuthenticationFilter

  • BasicAuthenticationFilter는 스프링 시큐리티 의존성을 추가하면 자동으로 등록되는 시큐리티 필터체인에 소속되어 있는 필터 중 하나임.
    • 해당 필터의 목적은 Basic기반의 인증을 수행하기 위해서 등록됨.
  • 사용자가 직접 시큐리티 필터체인을 만들면 자동 등록되지 않기 때문에 아래 코드를 통해서 활성화 시켜줘야함.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    
    			.....
                
        httpSecurity.httpBasic(Customizer.withDefaults());

				.....
            
            
            
        return httpSecurity.build();
    }
}

2. Basic 인증.

  • 먼저 Form인증 방식의 경우 Form태그에 username/password를 입력한 후 브라우저에서 서버로 요청하면 서버는 상태에 알맞는 세션 or JWT를 생성해서 사용자를 기억할 수 있도록 함.

    • Form인증 방식의 경우 사용자의 정보를 입력할 HTML파일이 있어야됨.
  • Basic인증 방식의 경우 HTML파일이 없어도 됨.
    브라우저에서 username/password을 입력할 수 있는 팝업을 띄워줌.

    • 브라우저가 매 요청마다 BASE64로 인코딩해서 Authorization 헤더에 담아서 전송함. 서버는 요청에 대해 username/password만 확인한 후 사용자를 기억하지 않기 때문에 매 요청마다 Authorization 헤더가 요구됨.
    • 하지만 스프링 시큐리티의 Basic 인증 로직은 매번 재인증을 요구하는 것이 아닌 세션에 값을 저장해서 유저를 기억함.
      (하지만 Authorization 헤더는 필요.)
Authorization: Basic BASE64로인코딩한usernamepassword값

3. BasicAuthenticationFilter 코드.

  • OncePerRequestFilter를 상속받아 구현되어있음.

  • 핵심 로직.

	@Override
    // Spring Security의 필터 체인에서 호출되는 메서드.
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
            // 요청에서 Authorization: Basic ... 헤더를 읽고 Authentication 객체로 변환.
			Authentication authRequest = this.authenticationConverter.convert(request);
            // 인증 요청(authRequest)이 null일 경우.
			if (authRequest == null) {
				this.logger.trace("Did not process authentication request since failed to find "
						+ "username and password in Basic Authorization header");
				chain.doFilter(request, response);
				return;
			}
            // 사용자의 아이디(username)를 가져옴.
			String username = authRequest.getName();
			this.logger.trace(LogMessage.format("Found username '%s' in Basic Authorization header", username));
            // 현재 로그인된 사용자가 동일한 사용자 이름으로 인증된 상태인지 확인. (인증이 필요한 지 확인.)
			if (authenticationIsRequired(username)) {
                // AuthenticationManager를 사용하여 아이디/비밀번호 기반 인증 수행.
				// authResult → 인증 성공 시 Authentication 객체 반환.
				// 인증 실패 시 예외 (AuthenticationException) 발생.
				Authentication authResult = this.authenticationManager.authenticate(authRequest);
                // SecurityContext를 새로 생성. Authentication 객체를 SecurityContext에 저장.
				// SecurityContext를 현재 요청의 SecurityContextHolder에 설정. (인증 상태 유지)
				SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
				context.setAuthentication(authResult);
				this.securityContextHolderStrategy.setContext(context);
				if (this.logger.isDebugEnabled()) {
					this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult));
				}
                // RememberMeServices를 사용하여 사용자의 인증 정보를 저장. 이후 요청에서는 BASIC 인증 없이 자동 로그인 가능.
				this.rememberMeServices.loginSuccess(request, response, authResult);
                // SecurityContextRepository를 통해 SecurityContext를 세션이나 캐시에 저장. 이후 요청에서도 사용자의 인증 상태를 유지 가능.
				this.securityContextRepository.saveContext(context, request, response);
                // 성공 처리.
				onSuccessfulAuthentication(request, response, authResult);
			}
		}
        // AuthenticationException 발생 시 처리.
		catch (AuthenticationException ex) {
			this.securityContextHolderStrategy.clearContext();
			this.logger.debug("Failed to process authentication request", ex);
			this.rememberMeServices.loginFail(request, response);
			onUnsuccessfulAuthentication(request, response, ex);
			if (this.ignoreFailure) {
				chain.doFilter(request, response);
			}
			else {
				this.authenticationEntryPoint.commence(request, response, ex);
			}
			return;
		}
		// 다음 필터로 요청 전달.
		chain.doFilter(request, response);
	}

3-1. 전체 코드.

package org.springframework.security.web.authentication.www;

import java.io.IOException;
import java.nio.charset.Charset;

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

import org.springframework.core.log.LogMessage;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Processes a HTTP request's BASIC authorization headers, putting the result into the
 * <code>SecurityContextHolder</code>.
 *
 * <p>
 * For a detailed background on what this filter is designed to process, refer to
 * <a href="https://tools.ietf.org/html/rfc1945">RFC 1945, Section 11.1</a>. Any realm
 * name presented in the HTTP request is ignored.
 *
 * <p>
 * In summary, this filter is responsible for processing any request that has a HTTP
 * request header of <code>Authorization</code> with an authentication scheme of
 * <code>Basic</code> and a Base64-encoded <code>username:password</code> token. For
 * example, to authenticate user "Aladdin" with password "open sesame" the following
 * header would be presented:
 *
 * <pre>
 *
 * Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
 * </pre>
 *
 * <p>
 * This filter can be used to provide BASIC authentication services to both remoting
 * protocol clients (such as Hessian and SOAP) as well as standard user agents (such as
 * Internet Explorer and Netscape).
 * <p>
 * If authentication is successful, the resulting {@link Authentication} object will be
 * placed into the <code>SecurityContextHolder</code>.
 *
 * <p>
 * If authentication fails and <code>ignoreFailure</code> is <code>false</code> (the
 * default), an {@link AuthenticationEntryPoint} implementation is called (unless the
 * <tt>ignoreFailure</tt> property is set to <tt>true</tt>). Usually this should be
 * {@link BasicAuthenticationEntryPoint}, which will prompt the user to authenticate again
 * via BASIC authentication.
 *
 * <p>
 * Basic authentication is an attractive protocol because it is simple and widely
 * deployed. However, it still transmits a password in clear text and as such is
 * undesirable in many situations.
 * <p>
 * Note that if a {@link RememberMeServices} is set, this filter will automatically send
 * back remember-me details to the client. Therefore, subsequent requests will not need to
 * present a BASIC authentication header as they will be authenticated using the
 * remember-me mechanism.
 *
 * @author Ben Alex
 */
public class BasicAuthenticationFilter extends OncePerRequestFilter {

	private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
		.getContextHolderStrategy();

	private AuthenticationEntryPoint authenticationEntryPoint;

	private AuthenticationManager authenticationManager;

	private RememberMeServices rememberMeServices = new NullRememberMeServices();

	private boolean ignoreFailure = false;

	private String credentialsCharset = "UTF-8";

	private AuthenticationConverter authenticationConverter = new BasicAuthenticationConverter();

	private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();

	/**
	 * Creates an instance which will authenticate against the supplied
	 * {@code 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
	 * {@code AuthenticationManager} and use the supplied {@code 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 {@link 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;
	}

	/**
	 * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
	 * authentication success. The default action is not to save the
	 * {@link SecurityContext}.
	 * @param securityContextRepository the {@link SecurityContextRepository} to use.
	 * Cannot be null.
	 */
	public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
		Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
		this.securityContextRepository = securityContextRepository;
	}

	/**
	 * Sets the
	 * {@link org.springframework.security.web.authentication.AuthenticationConverter} to
	 * use. Defaults to {@link BasicAuthenticationConverter}
	 * @param authenticationConverter the converter to use
	 * @since 6.2
	 */
	public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) {
		Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
		this.authenticationConverter = authenticationConverter;
	}

	@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 {
		try {
			Authentication authRequest = this.authenticationConverter.convert(request);
			if (authRequest == null) {
				this.logger.trace("Did not process authentication request since failed to find "
						+ "username and password in Basic Authorization header");
				chain.doFilter(request, response);
				return;
			}
			String username = authRequest.getName();
			this.logger.trace(LogMessage.format("Found username '%s' in Basic Authorization header", username));
			if (authenticationIsRequired(username)) {
				Authentication authResult = this.authenticationManager.authenticate(authRequest);
				SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
				context.setAuthentication(authResult);
				this.securityContextHolderStrategy.setContext(context);
				if (this.logger.isDebugEnabled()) {
					this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult));
				}
				this.rememberMeServices.loginSuccess(request, response, authResult);
				this.securityContextRepository.saveContext(context, request, response);
				onSuccessfulAuthentication(request, response, authResult);
			}
		}
		catch (AuthenticationException ex) {
			this.securityContextHolderStrategy.clearContext();
			this.logger.debug("Failed to process authentication request", ex);
			this.rememberMeServices.loginFail(request, response);
			onUnsuccessfulAuthentication(request, response, ex);
			if (this.ignoreFailure) {
				chain.doFilter(request, response);
			}
			else {
				this.authenticationEntryPoint.commence(request, response, ex);
			}
			return;
		}

		chain.doFilter(request, response);
	}

	protected boolean authenticationIsRequired(String username) {
		// Only reauthenticate if username doesn't match SecurityContextHolder and user
		// isn't authenticated (see SEC-53)
		Authentication existingAuth = this.securityContextHolderStrategy.getContext().getAuthentication();
		if (existingAuth == null || !existingAuth.getName().equals(username) || !existingAuth.isAuthenticated()) {
			return true;
		}
		// Handle unusual condition where an AnonymousAuthenticationToken is already
		// present. This shouldn't happen very often, as BasicAuthenticationFilter 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.
		return (existingAuth instanceof AnonymousAuthenticationToken);
	}

	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;
	}

	/**
	 * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
	 * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
	 *
	 * @since 5.8
	 */
	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
		Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
		this.securityContextHolderStrategy = securityContextHolderStrategy;
	}

	/**
	 * Sets the {@link AuthenticationDetailsSource} to use. By default, it is set to use
	 * the {@link WebAuthenticationDetailsSource}. Note that this configuration applies
	 * exclusively when the {@link #authenticationConverter} is set to
	 * {@link BasicAuthenticationConverter}. If you are utilizing a different
	 * implementation, you will need to manually specify the authentication details on it.
	 * @param authenticationDetailsSource the {@link AuthenticationDetailsSource} to use.
	 */
	public void setAuthenticationDetailsSource(
			AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
		if (this.authenticationConverter instanceof BasicAuthenticationConverter basicAuthenticationConverter) {
			basicAuthenticationConverter.setAuthenticationDetailsSource(authenticationDetailsSource);
		}
	}

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

	/**
	 * Sets the charset to use when decoding credentials to {@link String}s. By default,
	 * it is set to {@code UTF-8}. Note that this configuration applies exclusively when
	 * the {@link #authenticationConverter} is set to
	 * {@link BasicAuthenticationConverter}. If you are utilizing a different
	 * implementation, you will need to manually specify the charset on it.
	 * @param credentialsCharset the charset to use.
	 */
	public void setCredentialsCharset(String credentialsCharset) {
		Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
		this.credentialsCharset = credentialsCharset;
		if (this.authenticationConverter instanceof BasicAuthenticationConverter basicAuthenticationConverter) {
			basicAuthenticationConverter.setCredentialsCharset(Charset.forName(credentialsCharset));
		}
	}

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

}
profile
Every cloud has a silver lining.

0개의 댓글