본문 바로가기

Spring Boot

[Spring Boot] Spring Security @EnableMethodSecurity 설명 및 예제

728x90

설명

@EnableMethodSecurity는 Spring Security의 메서드 수준 보안을 활성화하는 데 사용되는 어노테이션입니다. 이 어노테이션을 통해 특정 메서드 또는 클래스에 접근 제어를 적용할 수 있습니다. @EnableMethodSecurity는 다양한 메서드 보안 어노테이션(@PreAuthorize, @PostAuthorize, @Secured 등)을 사용할 수 있게 해줍니다.

주요 기능

  • @PreAuthorize: 메서드가 호출되기 전에 접근을 허용할지 결정합니다.
  • @PostAuthorize: 메서드가 호출된 후에 접근을 허용할지 결정합니다.
  • @Secured: 특정 롤(role)로 접근을 제한합니다.
  • @RolesAllowed: 특정 롤(role)로 접근을 제한합니다 (JSR-250).

 

예제

 

다음은 @EnableMethodSecurity를 사용하여 메서드 수준 보안을 설정하는 예제입니다.

Gradle 설정

먼저 Spring Security 의존성을 추가합니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.security:spring-security-config'
    implementation 'org.springframework.security:spring-security-core'
}

Spring Security 설정

@EnableMethodSecurity를 사용하여 메서드 보안을 활성화합니다.


@Configuration
@EnableWebSecurity
@EnableMethodSecurity // (securedEnabled = true, prePostEnabled = true) // securedEnabled => Secured 애노테이션 사용 여부, prePostEnabled => PreAuthorize 어노테이션 사용 여부.
public class SecurityConfig {
	//...
}

 

 

컨트롤러 클래스에 @PreAuthorize, @PostAuthorize, @Secured 등을 사용하여 메서드 보안을 설정합니다.

 

어노테이션 내 사용 가능한 함수는 아래와 같다.

  • hasRole([role]) : 현재 사용자의 권한이 파라미터의 권한과 동일한 경우 true
  • hasAnyRole([role1,role2 ...]) : 현재 사용자의 권한 파라미터의 권한 중 일치하는 것이 있는 경우 true
  • principal: 사용자를 증명하는 주요객체(User)를 직접 접근할 수 있다.
  • authentication : SecurityContext에 있는 authentication 객체에 접근 할 수 있다.
  • permitAll : 모든 접근 허용
  • denyAll : 모든 접근 비허용
  • isAnonymous() : 현재 사용자가 익명(비로그인)인 상태인 경우 true
  • isRememberMe() : 현재 사용자가 RememberMe 사용자라면 true
  • isAuthenticated() : 현재 사용자가 익명이 아니라면 (로그인 상태라면) true
  • isFullyAuthenticated() : 현재 사용자가 익명이거나 RememberMe 사용자가 아니라면 true

 

컨트롤러 호출

 

컨트롤러 호출하여 메서드 보안을 테스트합니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyController {

    @Autowired
    private MyService myService;

//    @Secured("ROLE_USER")
    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("/user")
    public String userEndpoint() {
        return myService.userMethod();
    }

//    @Secured("ROLE_ADMIN")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/admin")
    public String adminEndpoint() {
        return myService.adminMethod();
    }

    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
    @GetMapping("/both")
    public String bothEndpoint() {
        return myService.bothMethod();
    }
    
}

 

주요 코드 설명

 

이 설정을 통해 사용자는 /api/user 엔드포인트에 접근할 때 ROLE_USER 권한이 필요하고, /api/admin 엔드포인트에 접근할 때 ROLE_ADMIN 권한이 필요합니다. /api/both 엔드포인트는 ROLE_USER 또는 ROLE_ADMIN 권한이 있는 사용자가 접근할 수 있습니다.

 

이와 같이 @EnableMethodSecurity와 다양한 메서드 보안 어노테이션을 사용하여 Spring Security의 메서드 수준 보안을 설정하고 관리할 수 있습니다.