필터를 넣었는데 올바른 키에도 401
비밀 키를 확인하는 필터를 만들어 Spring Security 설정에 추가했는데, 올바른 키를 보내도 401(누구인지 모르겠다는 응답)만 돌아오는 경우가 있다. 설정에는 이렇게 적었다.
.addFilterAfter(new ApiKeyAuthFilter(), AuthorizationFilter.class)
"필터도 넣었고 키도 맞는데, 왜 401일까?"
답은 필터를 넣은 위치에 있다. 이번 포스트에서는 쉬운 필터를 하나 끼워 넣어 보고, 어디에 넣어야 하는지 알아보자.
내 필터는 보안 필터 줄 사이에 들어간다
Spring Security의 보안 필터는 정해진 순서로 줄지어 있고, 이 줄이 SecurityFilterChain이다. 직접 만든 필터는 이 줄에 있는 특정 필터의 앞이나 뒤에 끼워 넣는다.

파란 칸이 내가 끼워 넣을 필터다. 그 뒤의 AuthorizationFilter는 기본으로 줄의 맨 끝에 서서 이 요청을 들여보낼지 정하는 필터다.
가장 쉬운 필터부터 만든다
요청 주소를 출력하고 그대로 보내 주는 필터다. OncePerRequestFilter(같은 요청에서 두 번 실행되지 않도록 해 주는 필터 기반 클래스)를 상속하고, doFilterInternal에 할 일을 적는다.
public class RequestLogFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
System.out.println("RequestLogFilter: " + request.getRequestURI());
// 다음 필터로 넘긴다. 이 줄이 없으면 요청이 여기서 멈춘다
chain.doFilter(request, response);
}
}
한 줄로 끼워 넣는다
확인할 주소는 두 개다. /public/ping은 누구나, /api/hello는 로그인한 사용자만 부를 수 있게 한다. 실습은 Spring Boot 4.2.0(Spring Security 7.2.0)에 spring-boot-starter-webmvc와 spring-boot-starter-security를 넣고 했다.
@RestController
public class ApiController {
@GetMapping("/api/hello")
public String hello(Principal principal) {
return "hello " + principal.getName();
}
@GetMapping("/public/ping")
public String ping() {
return "pong";
}
}
설정은 @Configuration 클래스에 둔다. 마지막의 addFilterBefore가 필터를 끼워 넣는 줄이다.
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
// AuthorizationFilter 앞에 내 필터를 넣는다
.addFilterBefore(new RequestLogFilter(), AuthorizationFilter.class);
return http.build();
}
/public/ping과 /api/hello를 차례로 부르면 콘솔에 다음 두 줄이 찍힌다.
RequestLogFilter: /public/ping
RequestLogFilter: /api/hello
로그인하지 않았으니 /api/hello는 거절되지만 로그는 남는다. 내 필터가 거절하는 곳보다 앞에 있기 때문이다.
앞, 뒤, 같은 위치를 고를 수 있다
넣을 위치는 Spring Security에 있는 필터를 기준으로 말한다.
- addFilterBefore(내 필터, 기준.class) : 기준 필터 앞
- addFilterAfter(내 필터, 기준.class) : 기준 필터 뒤
- addFilterAt(내 필터, 기준.class) : 기준 필터와 같은 위치. 기준 필터를 대신하는 것은 아니다
addFilterAt은 이름 때문에 기준 필터를 바꿔 끼우는 것처럼 보인다. 공식 레퍼런스의 메서드 소개에도 replaces라고 적혀 있다. 하지만 HttpSecurity API 문서는 같은 위치에 필터를 여러 개 넣어도 기존 필터를 덮어쓰지 않고, 그 필터들 사이의 순서는 정해지지 않는다고 설명한다. 기준 필터를 쓰고 싶지 않다면 그 필터를 아예 등록하지 말라는 것이 API 문서의 안내다.
예를 들어 BasicAuthenticationFilter를 직접 만들어 addFilterAt으로 넣는다면 httpBasic()은 부르지 않는다. 공식문서는 httpBasic()으로 이미 BasicAuthenticationFilter가 들어간 체인에 같은 필터를 또 넣으면 예외가 난다고 설명한다.
인증하는 필터는 들여보내기 전에 넣는다
이제 처음의 필터를 보자. 요청 헤더 X-API-KEY의 키가 맞으면 "이 요청은 user1이 보냈다"고 적어 두는 필터다. 적어 두는 곳이 SecurityContextHolder이고, AuthorizationFilter는 여기를 보고 판단한다. demo-key는 실습용 값이다.
public class ApiKeyAuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String apiKey = request.getHeader("X-API-KEY");
// 키가 없으면 판단하지 않고 다음 필터로 넘긴다
if (apiKey == null) {
chain.doFilter(request, response);
return;
}
// 키가 틀리면 여기서 401로 끝낸다
if (!"demo-key".equals(apiKey)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// 키가 맞으면 인증 정보를 만들어 SecurityContextHolder에 담는다
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(
"user1", null, AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
chain.doFilter(request, response);
}
}
이 예제는 요청마다 키를 보내니, 인증 정보를 세션 같은 저장소에 남기지 않고 SecurityContextHolder에만 담는다. 로그인 상태를 다음 요청까지 남기려면 SecurityContextRepository에 따로 저장해야 한다.
이 필터는 LogoutFilter 뒤에 넣는다. LogoutFilter는 로그아웃 요청을 처리하는 Spring Security 필터이고, 그 뒤가 공식문서가 인증하는 필터에 권하는 위치다. 기본 순서는 SecurityContextHolderFilter → LogoutFilter → 아이디와 비밀번호로 인증하는 필터들 → AnonymousAuthenticationFilter → ExceptionTranslationFilter → AuthorizationFilter라서, AuthorizationFilter보다 한참 앞이다.
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 브라우저가 아닌 프로그램이 부르는 API라고 보고 CSRF 검사를 끈다
.csrf(csrf -> csrf.disable())
// 로그인 상태를 세션에 저장하지 않고 요청마다 키를 받는다
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
// 인증되지 않은 요청에는 401을 보낸다
.exceptionHandling(ex -> ex
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
// LogoutFilter 뒤에 API 키 필터를 넣는다
.addFilterAfter(new ApiKeyAuthFilter(), LogoutFilter.class);
return http.build();
}
위치만 바꿔서 /api/hello를 불러 보면 결과가 이렇게 갈린다.
| 필터를 넣은 위치 | 올바른 키로 요청 |
| LogoutFilter 뒤 | 200 hello user1 |
| AuthorizationFilter 뒤 | 401 |

AuthorizationFilter 뒤에 넣으면, 누구인지 적기도 전에 들여보낼지부터 정한다. 적힌 사람이 없으니 익명 사용자로 보고 거절한다. 그러면 설정에 넣은 HttpStatusEntryPoint가 401을 보내고, 내 필터는 실행되지 않는다. 처음에 말한 401이 바로 이것이다.
그렇다고 맨 앞이 좋은 것도 아니다. SecurityContextHolderFilter는 요청마다 저장소에서 인증 정보를 꺼내 SecurityContextHolder를 새로 채우는 필터다. 그래서 이 필터보다 앞에서 적으면, 뒤이어 실행되는 SecurityContextHolderFilter가 저장소의 값으로 바꿔 놓는다. 이 예제는 STATELESS라 저장소가 세션이 아니라 RequestAttributeSecurityContextRepository다. 인증 정보를 요청 객체에 붙여 두고 그 요청 안에서만 쓰는 저장소라서, 요청이 막 들어온 이때는 비어 있다. 결국 적어 둔 내용이 지워져 역시 401이 된다.
정리하면 필터를 끼워 넣는 것은 한 줄이고, 중요한 것은 그 필터가 무엇보다 먼저 끝나야 하는가다. 인증하는 필터라면 들여보낼지 정하기 전이다.
참고
Spring Security - Adding a Custom Filter
Spring Security - SecurityContextHolder
'Java > security' 카테고리의 다른 글
| [06] 403이 401로 바뀌는 이유 - sendError와 ERROR 디스패치 (0) | 2026.11.30 |
|---|---|
| [04] 역할은 어떻게 붙이고 검사할까 - roles, hasRole, @PreAuthorize, RoleHierarchy (0) | 2026.11.26 |
| [03] 필터로 다 하기엔 너무 많다 - SecurityFilterChain 만들기와 주요 설정 (0) | 2026.11.26 |
| [02] 필터는 어떻게 요청을 넘기고 막을까 - chain.doFilter와 기본 필터 16개 (0) | 2026.11.17 |
| [01] 요청 하나로 따라가 보는 Spring Security 전체 흐름 (0) | 2026.11.17 |
