반응형

오늘은 전자정부프레임워크 기반 프로젝트에서 API 인증 및 보안을 설정하는 방법을 다룹니다. RESTful API는 외부 접근이 용이하므로 적절한 인증 및 보안 설정이 필수적입니다.


1. API 보안의 중요성

API는 클라이언트와 서버 간 데이터를 교환하는 중요한 통로입니다. 보안이 설정되지 않으면 다음과 같은 위험이 발생할 수 있습니다:

  • 데이터 유출: 민감한 데이터가 노출될 가능성이 높아짐.
  • 무단 액세스: 인증되지 않은 사용자나 애플리케이션의 API 사용.
  • 악성 요청: DDoS 공격 또는 악의적인 요청에 의한 서비스 장애.

2. Spring Security 설정

전자정부프레임워크는 Spring 기반이므로, Spring Security를 사용해 인증과 권한 관리를 구현할 수 있습니다.

2-1. Maven 의존성 추가

pom.xml 파일에 Spring Security 의존성을 추가합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2-2. SecurityConfig 작성

Spring Security를 구성하는 설정 파일을 작성합니다.

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.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // CSRF 비활성화 (테스트용)
            .authorizeRequests()
                .antMatchers("/api/public/**").permitAll() // 공개 API
                .antMatchers("/api/private/**").authenticated() // 인증 필요
            .and()
            .httpBasic(); // 기본 인증
        return http.build();
    }
}

3. 공개 및 인증 API 구현

3-1. 공개 API

공개 API는 모든 사용자가 접근할 수 있는 엔드포인트입니다.

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

@RestController
public class PublicApiController {

    @GetMapping("/api/public/hello")
    public String publicHello() {
        return "공개 API입니다.";
    }
}

3-2. 인증 API

인증 API는 인증된 사용자만 접근할 수 있습니다.

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

@RestController
public class PrivateApiController {

    @GetMapping("/api/private/hello")
    public String privateHello() {
        return "인증된 사용자만 접근 가능합니다.";
    }
}

4. Postman을 활용한 테스트

4-1. 공개 API 테스트

  • URL: http://localhost:8080/api/public/hello
  • 인증 정보 없이도 응답을 받을 수 있습니다.

4-2. 인증 API 테스트

  • URL: http://localhost:8080/api/private/hello
  • 인증 정보를 제공하지 않으면 401 Unauthorized 응답을 받습니다.
  • 인증 정보(username과 password)를 제공하면 정상적으로 접근 가능합니다.

5. 추가적인 보안 기능

  • JWT(Json Web Token): 인증 정보를 토큰으로 관리하여 stateless 인증 구현.
  • OAuth 2.0: 외부 서비스 연동을 위한 표준 인증 프로토콜.
  • CSRF 보호: CSRF 공격을 방지하기 위한 추가 설정.

6. 마무리

오늘은 전자정부프레임워크에서 Spring Security를 활용하여 API 인증과 보안을 설정하는 방법을 배웠습니다. 기본 인증을 넘어 JWT, OAuth 2.0 같은 고급 인증 방법도 고려해 보안을 강화할 수 있습니다.

다음 시간에는 JWT 기반 인증 구현을 다뤄보겠습니다.

반응형

+ Recent posts