본문 바로가기

Study Information Technology

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

728x90
반응형

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

Overview

Spring Boot와 OAuth2 리소스 서버를 통합하면 애플리케이션이 안전하게 API를 제공하고, 인증된 요청에 대한 액세스 토큰을 검증할 수 있습니다. 이 과정은 애플리케이션의 보안을 강화하고, 다양한 클라이언트 애플리케이션과의 상호 작용을 용이하게 만들어 줍니다.

1. OAuth2의 기본 개념

OAuth2는 인증 및 권한 부여 프로토콜로, 클라이언트 애플리케이션이 자원 소유자(사용자)의 권한을 위임받아 보호된 자원에 접근할 수 있도록 합니다. 리소스 서버는 보호된 자원을 호스팅하며, 클라이언트는 유효한 액세스 토큰을 통해 이 자원에 접근합니다.

예시

  • 사용자가 Google 계정을 통해 로그인을 하면, 클라이언트 애플리케이션은 Google의 OAuth2 서버에서 액세스 토큰을 받아 이를 통해 사용자 정보에 접근합니다.

2. Spring Boot 설정하기

Spring Boot에서 OAuth2 리소스 서버를 설정하려면, 먼저 spring-boot-starter-oauth2-resource-server 의존성을 추가해야 합니다. Maven 또는 Gradle을 통해 프로젝트에 추가할 수 있습니다.

Maven 의존성 추가

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

Gradle 의존성 추가

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

3. 프로퍼티 파일 설정

application.yml 또는 application.properties 파일에서 OAuth2 리소스 서버의 JWT 설정을 추가합니다. 여기에서는 JWT를 사용한다고 가정합니다.

spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com

4. 리소스 서버 설정 클래스 만들기

Spring Security를 사용하여 리소스 서버를 구성합니다. SecurityConfig 클래스를 생성하고, JWT를 기반으로 인증을 설정합니다.

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;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated() // 모든 요청은 인증이 필요
.and()
.oauth2ResourceServer()
.jwt(); // JWT 사용 설정
}

@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setPrincipalExtractor(jwt -> {
// 사용자 정의 Principal 변환 로직
return jwt.getClaimAsString("sub");
});
return jwtConverter;
}
}

5. API 엔드포인트 생성

이제 리소스 서버가 설정되었으므로, 보호된 API 엔드포인트를 생성할 수 있습니다. 예를 들어, 사용자의 정보를 제공하는 RESTful API를 만들어보겠습니다.

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

@RestController
public class UserController {

@GetMapping("/user")
public String getUserInfo() {
// 실제 사용자 정보를 반환하는 로직
return "User Info";
}
}

6. 에러 처리

JWT를 사용할 때는 유효하지 않은 토큰이나 만료된 토큰에 대한 에러 처리가 필요합니다. Spring Security는 기본적으로 AuthenticationEntryPoint를 제공하여 에러 응답을 처리할 수 있습니다.

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
}
}

이제 이 EntryPoint를 SecurityConfig에 추가하여 에러 처리를 할 수 있습니다.

7. 테스트하기

이제 OAuth2 리소스 서버가 설정되었으므로 Postman과 같은 도구를 사용하여 API를 테스트할 수 있습니다. 유효한 JWT를 포함하여 /user 엔드포인트에 요청하면 사용자 정보를 반환받을 수 있습니다. 만약 유효하지 않은 토큰을 사용하면 401 Unauthorized 에러가 발생합니다.

참고 문서

이렇게 Spring Boot와 OAuth2 리소스 서버를 통합하여 안전한 API를 제공하는 방법을 살펴보았습니다. 궁극적으로, 이를 통해 사용자의 권한을 안전하게 관리하고, 서비스 간의 데이터 흐름을 보다 안전하게 유지할 수 있습니다.

반응형