이전에 Spring Boot 프로젝트를 진행하면서는 HTTP 헤더의 Authorization 토큰을 직접 파싱해 사용자 정보를 가져오곤 했습니다.

Spring Security를 사용한다면 컨트롤러 메서드에 Authentication 객체를 파라미터로 주입받아 사용할 수 있습니다.

1. Authorization헤더 vs. Authentication 파라미터

두 방식의 가장 큰 차이점은 인증 정보 처리의 책임이 어디에 있느냐입니다.

// 직접 Authorization 헤더를 다루는 방식
@RestController
@RequestMapping("/api/friends")
public class FriendControllerV1 {
    // ... (의존성 주입)

    @GetMapping("/search")
    public ResponseEntity<List<UserSearchResponse>> searchUsers(
        @RequestParam String keyword,
        @RequestHeader("Authorization") String token) {

        // 1. 토큰 유효성 검증 로직 (만료, 변조 등)
        if (!isValidToken(token)) {
            return ResponseEntity.status(401).build();
        }

        // 2. 토큰에서 사용자 ID 추출
        Long currentUserId = extractUserIdFromToken(token);

        // 3. 비즈니스 로직 호출
        List<User> users = friendService.searchUsers(keyword, currentUserId);

        // ...
    }

}
  • 컨트롤러가 인증과 비즈니스 로직이라는 두 가지 역할을 동시에 수행하게됩니다. 토큰 처리 로직이 모든 컨트롤러 메서드에 반복되거나, 별도의 유틸리티 클래스로 분리해야 하는 번거로움이 있습니다.
// Spring Security의 Authentication 파라미터를 사용하는 방식
@RestController
@RequestMapping("/api/friends")
public class FriendControllerV2 {

    // ... (의존성 주입)

    @GetMapping("/search")
    public ResponseEntity<List<UserSearchResponse>> searchUsers(
        @RequestParam String keyword,
        Authentication authentication) { // Spring이 인증된 사용자 정보를 자동으로 주입

        // 1. 인증된 사용자 ID를 바로 사용
        Long currentUserId = (Long) authentication.getPrincipal();

        // 2. 비즈니스 로직 호출 (깔끔해짐)
        List<User> users = friendService.searchUsers(keyword, currentUserId);

        // ...
    }
}
  • 컨트롤러는 이미 인증이 완료되었다는 것을 신뢰하고 비즈니스 로직에만 집중할 수 있습니다. 토큰 처리, 유효성 검증 같은 부가적인 관심사가 완전히 분리되어 코드가 간결해지고 유지보수성이 높아집니다.

결론적으로, Spring Security 환경에서는 Authentication 파라미터를 사용하는 것이 객체지향 원칙과 관심사 분리 측면에서 훨씬 더 좋은 설계라고 생각합니다.

'개발관련' 카테고리의 다른 글

[MySQL] 복합 인덱스 적용 및 성능테스트 트러블 슈팅  (2) 2026.01.04
WebSocket  (2) 2025.11.10
Session, JWT, OAuth  (0) 2025.08.12
static, Thread-safe  (4) 2025.08.04
[Spring Boot] OAuth 2.0 소셜 로그인 구현 흐름  (0) 2025.07.03

+ Recent posts