본문 바로가기

Study Information Technology

Spring Boot와 OAuth2 Resource Server 통합하기

728x90
반응형

Spring Boot와 OAuth2 Resource Server 통합하기

Overview

Spring Boot와 OAuth2 Resource Server를 통합하면, 애플리케이션이 보안적으로 API를 제공하고, 승인된 요청에 대해 액세스 토큰을 검증할 수 있습니다. 이 글에서는 Spring Boot를 사용해 OAuth2 Resource Server를 설정하고, API 요청을 안전하게 처리하는 방법에 대해 자세히 설명하겠습니다.

1. OAuth2 Resource Server란?

OAuth2 Resource Server는 클라이언트가 API에 접근할 때 필요한 액세스 토큰을 검증하여 요청의 유효성을 판단하는 서버입니다. 이 시스템은 보안을 강화하고, 인증된 사용자만 API에 접근할 수 있도록 합니다. OAuth2는 인증과 권한 부여를 위한 프로토콜로, 사용자의 리소스에 접근하기 위해 클라이언트가 서버로부터 토큰을 발급받는 과정을 포함합니다.

2. Spring Boot 프로젝트 설정하기

Spring Boot로 OAuth2 Resource Server를 구현하기 위해서는 먼저 Spring Initializr를 사용해 프로젝트를 생성합니다.

2.1. Spring Initializr 사용하기

  1. Spring Initializr에 접속합니다.
  2. 다음과 같은 의존성을 추가합니다:
  • Spring Web
  • Spring Security
  • Spring Boot OAuth2 Resource Server
  1. 프로젝트 메타데이터를 입력한 후, 프로젝트를 생성하고 다운로드합니다.

2.2. 프로젝트 구조

프로젝트의 구조는 다음과 같을 것입니다:

src
└── main
├── java
│   └── com
│       └── example
│           └── oauth2server
│               ├── OAuth2ResourceServerApplication.java
│               └── SecurityConfig.java
└── resources
└── application.yml

3. 애플리케이션 설정

이제 application.yml 파일을 수정하여 OAuth2 Resource Server를 설정합니다. 아래는 기본적인 설정 예시입니다.

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

여기서 issuer-uri는 JWT 토큰의 발급자를 나타냅니다. 이는 클라이언트가 토큰을 검증할 때 필요한 정보입니다.

4. Spring Security 설정

이제 SecurityConfig.java 파일을 생성하여 Spring Security를 구성합니다.

package com.example.oauth2server;

import org.springframework.context.annotation.Bean;
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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public").permitAll() // 공개 API
.anyRequest().authenticated() // 인증이 필요한 모든 요청
.and()
.oauth2ResourceServer()
.jwt(); // JWT를 사용하여 인증
}
}

5. API 엔드포인트 구현

이제 실제 API를 구현해 보겠습니다. /api/private/api/public 두 개의 엔드포인트를 만들어 보겠습니다.

package com.example.oauth2server;

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

@RestController
public class ApiController {
@GetMapping("/api/public")
public String publicApi() {
return "This is a public API";
}

@GetMapping("/api/private")
public String privateApi() {
return "This is a private API, accessible only to authenticated users";
}
}

6. JWT 토큰 발급과 검증

이제 클라이언트가 API에 접근할 때 필요한 JWT 토큰을 발급받고, 이를 검증하는 과정을 설명하겠습니다. JWT는 JSON Web Token의 약자로, 사용자 정보를 안전하게 전송하기 위한 표준입니다.

클라이언트는 인증 서버에 요청을 보내 JWT를 발급받습니다. 예를 들어, 다음과 같은 POST 요청을 보낼 수 있습니다:

POST /oauth/token
Host: example.com
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=user&password=pass

인증 서버는 클라이언트의 요청을 검증하고, 유효하다면 JWT를 응답합니다.

7. API 요청하기

이제 클라이언트가 JWT를 가지고 API에 요청할 수 있습니다. 다음과 같은 GET 요청을 통해 /api/private에 접근할 수 있습니다.

GET /api/private
Host: localhost:8080
Authorization: Bearer {your_jwt_token}

여기서 {your_jwt_token} 부분에 실제 JWT를 입력해야 합니다.

8. 에러 처리

API 요청 시 문제가 발생할 수 있으며, 일반적인 에러 메시지와 그 해결책은 다음과 같습니다:

  • 401 Unauthorized: JWT가 없거나 잘못된 경우 발생합니다. 이 경우 클라이언트는 유효한 JWT를 요청해야 합니다.
  • 403 Forbidden: JWT는 유효하나 해당 리소스에 대한 접근 권한이 없는 경우 발생합니다. 이 경우 리소스에 대한 접근 권한을 확인해야 합니다.

9. 참고 문서

이와 같이 Spring Boot와 OAuth2 Resource Server를 통합하여 안전한 API를 제공하는 방법에 대해 알아보았습니다. 추가적인 질문이나 세부 사항에 대한 설명이 필요하다면 언제든지 말씀해 주세요!

반응형