Skip to content

AOP를 활용한 리소스 소유자 권한 체크 가이드 #7

@Tae4an

Description

@Tae4an

📌 개요

리소스(시험/문제)에 대한 수정/삭제 권한을 소유자로 제한하기 위한 AOP 기반 권한 체크 시스템입니다.

⚙️ 주요 컴포넌트 설명

1️⃣ @ResourceOwner 어노테이션

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResourceOwner {
    String idParameter();     // 검사할 리소스 ID 파라미터 이름
}
  • @Target(ElementType.METHOD): 메서드 레벨에만 적용 가능
  • idParameter: 권한 체크할 리소스의 ID가 있는 파라미터 이름 지정

2️⃣ ResourceOwnerAspect

@Aspect
@Component
@RequiredArgsConstructor
public class ResourceOwnerAspect {
    @Before("@annotation(resourceOwner)")
    public void checkResourceOwnership(...) {
        // 권한 체크 로직
    }
}
  • @Before: 메서드 실행 전 권한 체크
  • SecurityContext에서 현재 사용자 정보 추출
  • 리소스 ID와 사용자 ID를 비교하여 권한 검증

3️⃣ SecurityConfig 설정

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableAspectJAutoProxy
public class SecurityConfig {
    // ...
}
  • @EnableAspectJAutoProxy: AOP 활성화
  • @EnableGlobalMethodSecurity: Spring Security 메서드 보안 활성화

🔒 사용 예시

API Controller

@PutMapping("/{id}")
@ResourceOwner(idParameter = "id")
public ResponseEntity<Void> updateExam(...) {
    // 권한 체크 후 실행됨
}

View Controller

@GetMapping("/{id}/edit")
@ResourceOwner(idParameter = "id")
public String examEdit(...) {
    // 권한 체크 후 실행됨
}

⚠️ 에러 처리

public enum ErrorCode {
    RESOURCE_ACCESS_DENIED(403, "리소스에 대한 접근 권한이 없습니다")
}
  • 권한 없는 접근 시 403 Forbidden 응답
  • GlobalExceptionHandler에서 일관된 에러 응답 형식 제공

🔍 동작 프로세스

  1. Controller 메서드 호출
  2. @ResourceOwner 어노테이션 감지
  3. ResourceOwnerAspect에서 권한 체크
  4. 권한 있음 → 메서드 실행
  5. 권한 없음 → RESOURCE_ACCESS_DENIED 예외 발생

💡 장점

  • 선언적 권한 체크 가능
  • 권한 체크 로직 중앙화
  • 비즈니스 로직과 권한 체크 로직 분리
  • 일관된 에러 처리

📋 적용 대상

  • 리소스 수정/삭제 API
  • 수정 페이지 접근
  • 기타 소유자 권한이 필요한 기능

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions