본문 바로가기

Study Information Technology

Spring Boot와 OAuth2 리소스 서버 통합하기

728x90
반응형

Spring Boot와 OAuth2 리소스 서버 통합하기

Overview

Spring Boot와 OAuth2 리소스 서버를 통합하면 애플리케이션이 안전하게 API를 제공할 수 있으며, 인증된 요청에 대해 액세스 토큰을 검증할 수 있습니다. 이 과정은 클라이언트가 요청하는 데이터에 대한 접근 권한을 관리하는 데 필수적입니다. 이 글에서는 OAuth2 리소스 서버를 설정하는 방법과 Spring Boot에서 이를 구현하는 구체적인 예시를 다뤄보겠습니다.

1. OAuth2 개요

OAuth2는 리소스 소유자가 자원에 대한 접근 권한을 제3자에게 부여할 수 있도록 하는 프로토콜입니다. 이 프로토콜은 다양한 인증 플로우를 지원하며, 특히 API와의 상호작용에서 널리 사용됩니다. 기본적으로 OAuth2는 다음과 같은 주요 구성 요소를 포함합니다:

  • 클라이언트(Client): 리소스 소유자를 대신해 API에 접근하는 애플리케이션입니다.
  • 리소스 서버(Resource Server): 보호된 자원을 호스팅하며, 액세스 토큰을 통해 요청의 유효성을 검증합니다.
  • 인증 서버(Authorization Server): 클라이언트에게 액세스 토큰을 발급하는 서버입니다.

2. Spring Boot 애플리케이션 설정하기

Spring Boot 애플리케이션을 OAuth2 리소스 서버로 설정하려면, spring-boot-starter-oauth2-resource-server 의존성을 추가해야 합니다. 다음은 Maven을 사용하는 경우의 pom.xml 설정 예시입니다:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Gradle을 사용하는 경우는 build.gradle에 아래를 추가합니다:

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

3. application.yml 설정하기

리소스 서버의 기본 설정을 위해 application.yml 파일에 다음과 같은 설정을 추가합니다. 여기서는 JWT를 사용하는 예시를 보여줍니다.

spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://your-auth-server.com/realms/your-realm

이 설정에서 issuer-uri는 인증 서버의 URI를 나타내며, 해당 URI에서 JWT의 유효성을 검증하는 데 필요한 공개 키를 가져옵니다.

4. 보안 설정하기

이제 Spring Security를 사용하여 API 엔드포인트에 대한 보안을 설정할 수 있습니다. SecurityConfig 클래스를 생성하고 다음과 같이 설정합니다:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll() // 공개된 엔드포인트
.anyRequest().authenticated() // 모든 다른 요청은 인증 필요
.and()
.oauth2ResourceServer()
.jwt(); // JWT 인증 사용
}
}

5. API 엔드포인트 구현하기

이제 보호된 API 엔드포인트를 구현해 보겠습니다. @RestController를 사용하여 간단한 API를 작성할 수 있습니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

@GetMapping("/api/data")
public String getData() {
return "Protected data";
}
}

6. 액세스 토큰 검증하기

클라이언트가 /api/data 엔드포인트에 접근하려면 유효한 액세스 토큰을 포함해야 합니다. 예를 들어, Postman을 사용하여 API를 호출할 때는 Authorization 헤더에 Bearer {access_token} 형식으로 토큰을 포함해야 합니다.

7. 에러 처리

클라이언트가 잘못된 토큰을 사용하면 다음과 같은 에러 메시지를 받을 수 있습니다:

{
"error": "invalid_token",
"error_description": "The access token expired"
}

이런 에러를 처리하기 위해 @ControllerAdvice를 사용하여 글로벌 예외 처리를 추가할 수 있습니다:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
}
}

8. 결론

Spring Boot와 OAuth2 리소스 서버를 통합하면 API의 보안을 강화할 수 있습니다. 위의 예시를 통해 설정 과정을 단계별로 살펴보았고, 보안 및 예외 처리에 대한 이해를 높일 수 있었습니다. 이러한 통합은 현대 애플리케이션에서 필수적이며, 다양한 보안 요구 사항을 충족하는 데 도움을 줄 수 있습니다.

참고문서

728x90
반응형