Spring Boot · 2026-02-08

Spring Boot: OAuth2 리소스 서버와 JWT 검증

Spring Boot 애플리케이션에서 OAuth2 리소스 서버를 구성하고 JWT를 검증하는 핵심 개념과 설정 예시, 테스트 방법을 쉽게 정리한 기술자료

작성일 : 2026-02-08 ㆍ 작성자 : 관리자
post
목차

소개

API를 보호할 때 OAuth2 리소스 서버 구성은 필수다. 특히 JWT(Json Web Token)를 사용하는 경우 토큰 서명과 클레임 검증이 중요하다. 이 글에서는 spring security oauth2 resource server 관점에서 Spring Boot 환경에 JWT 검증을 간단하고 실용적으로 적용하는 방법을 설명한다. 처음 접하는 경우에도 따라할 수 있도록 설정, 코드 예제, 테스트 절차를 순서대로 제시한다.

기본 개념

리소스 서버는 클라이언트가 전달한 액세스 토큰을 검증해 요청을 허용한다. JWT는 자체적으로 서명 정보를 포함하므로 공개키로 서명을 검증하면 토큰 신뢰성을 확인할 수 있다. 보통 인증 서버는 JWKS 엔드포인트(jwk-set-uri)를 제공하며 리소스 서버는 이를 사용해 서명을 검증한다. 관련 키워드로 spring boot resource server jwt, oauth2 jwt 검증 spring boot, spring security oauth2 resource server가 있다.

프로젝트 의존성

Spring Boot에서 리소스 서버 기능은 starter로 쉽게 추가된다. Gradle 예시는 다음과 같다.

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-web'

애플리케이션 설정 (application.yml)

가장 간단한 설정은 인증 서버의 JWKS URI를 지정하는 것이다. 리소스 서버는 이 주소에서 공개키를 가져와 JWT 서명을 검증한다.

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri: https://auth-server.example.com/.well-known/jwks.json

Security 구성

Spring Security 구성을 통해 모든 요청에 대해 JWT 검증을 적용한다. SecurityFilterChain을 등록하면 세부 인증 흐름을 제어할 수 있다.

@Configuration
public class SecurityConfig {

  @Bean
  public org.springframework.security.config.annotation.web.builders.HttpSecurityFilterChain securityFilterChain(org.springframework.security.config.annotation.web.builders.HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth
        .requestMatchers("/public").permitAll()
        .anyRequest().authenticated()
      )
      .oauth2ResourceServer(oauth -> oauth.jwt());
    return http.build();
  }

  @Bean
  public org.springframework.security.oauth2.jwt.JwtDecoder jwtDecoder() {
    return org.springframework.security.oauth2.jwt.NimbusJwtDecoder
      .withJwkSetUri("https://auth-server.example.com/.well-known/jwks.json")
      .build();
  }
}

설명

  • authorizeHttpRequests: 공개 경로와 보호할 경로를 분리한다.
  • oauth2ResourceServer(...).jwt(): JWT 방식으로 토큰을 검증하도록 설정한다.
  • JwtDecoder: 기본 동작을 오버라이드하거나 커스터마이즈할 때 빈으로 등록한다.

토큰 클레임과 검증 포인트

검증 시 다음 항목들을 확인해야 한다.

  • 서명(Signature): JWKS 공개키로 서명이 유효한지 확인.
  • 만료(Expiration): exp 클레임으로 토큰 만료 여부 확인.
  • 발행자(Issuer): iss 클레임으로 신뢰할 수 있는 발행자인지 확인.
  • 대상(Audience): aud 클레임이 자원 서버를 위한 토큰인지 확인.

필요하면 JwtAuthenticationConverter를 사용해 클레임을 권한(GrantedAuthority)으로 매핑할 수 있다.

JWT 로더 커스터마이징 예

aud, iss 확인을 추가하는 JwtDecoder 커스터마이징 예시는 다음과 같다.

@Bean
public org.springframework.security.oauth2.jwt.JwtDecoder jwtDecoder() {
  NimbusJwtDecoder decoder = NimbusJwtDecoder
    .withJwkSetUri("https://auth-server.example.com/.well-known/jwks.json")
    .build();

  org.springframework.security.oauth2.jwt.OAuth2TokenValidator<org.springframework.security.oauth2.jwt.Jwt> withIssuer =
    new org.springframework.security.oauth2.jwt.JwtIssuerValidator("https://auth-server.example.com");
  org.springframework.security.oauth2.jwt.OAuth2TokenValidator<org.springframework.security.oauth2.jwt.Jwt> defaultValidators = org.springframework.security.oauth2.jwt.JwtValidators.createDefault();
  org.springframework.security.oauth2.jwt.OAuth2TokenValidator<org.springframework.security.oauth2.jwt.Jwt> combined =
    new org.springframework.security.oauth2.jwt.DelegatingOAuth2TokenValidator<>(defaultValidators, withIssuer);
  decoder.setJwtValidator(combined);
  return decoder;
}

테스트 방법

로컬에서 리소스 서버가 토큰을 잘 검증하는지 확인하려면 curl로 Authorization 헤더를 전송한다.

curl -H "Authorization: Bearer YOUR_JWT_HERE" http://localhost:8080/api/resource

성공하면 200 응답과 리소스 데이터를 받는다. 실패하면 401 또는 403 상태가 반환된다. 응답 로그와 스프링 시큐리티 디버그를 통해 검증 과정을 확인할 수 있다.

문제 해결 팁

  • jwks URI가 올바른지 브라우저에서 확인. JSON Web Key들이 노출되어야 한다.
  • 시간 동기화: 서버 시간과 토큰 발행 시간 차이로 exp 검증 실패 가능.
  • 발행자(iss)와 audience(aud) 값이 기대값과 일치하는지 확인.
  • 로깅을 통해 JwtDecoder 예외 메시지를 확인하면 원인 파악에 도움이 된다.

결론

Spring Boot에서 spring security oauth2 resource server 기능을 사용하면 JWT 검증을 표준 방식으로 구현할 수 있다. JWKS 기반 검증과 JwtDecoder 커스터마이징을 통해 발행자, 만료, 대상 등을 엄격히 검사하면 보안성을 높일 수 있다. 위 구성 예시와 절차를 따라하면 spring boot resource server jwt 적용을 빠르게 마무리할 수 있다.

spring boot resource server jwt spring security oauth2 resource server oauth2 jwt 검증 spring boot spring boot jwt oauth2 resource server jwks jwt 검증 spring security