[SpringSecurity] Method Security

해니·2024년 9월 5일
0

SpringBoot

목록 보기
15/24
post-thumbnail

메소드별 권한 설정을 할 순 없을까? 🧐
가계부 앱 관련 프로젝트를 진행하던 중, 카테고리 조회는 모든 계정이 카테고리 생성은 관리자 권한만 가능하게 하고 싶었다. 스프링 시큐리티 설정에서 엔드포인트별 권한 설정을 하는 방법만 알아서 .. 방법이 있나 찾아보던 중 Method Security를 알게되어 정리하고자 한다 !



Method Security 란?

  • Spring Security는 웹 애플리케이션에서 API 경로나 URL에 대한 권한을 부여하는 것 외에도, 메소드 레벨의 보안을 제공한다.
  • 대표적으로 @PreAuthorize, @PostAuthorize, @Secured와 같은 어노테이션으로 제어 할 수 있다.



의존성 추가

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-security")
}



SecurityConfig 설정

  • @EnableWebSecurity
    • 스프링 시큐리티 필터가 스프링 필터 체인에 등록되도록 한다.
      @EnableMethodSecurity
    • securedEnabled: @Secure 애노테이션 사용가능 여부에 대한 속성
      • defaultfalse
    • prePostEnabled: @PreAuthorize, @PostAuthorize 애노테이션 사용가능 여부에 대한 속성
      • defaulttrue
  • authorizeRequest에서의 permitAll()은 명시적인 선언에 불과하며, 이후 접근 제어는 각 api 메소드 별로 수행한다.

// SecurityConfig.kt
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
class SecurityConfig {
       @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
    	http
             /* 
              ... 
            */
                .authorizeHttpRequests { authorizeHttpRequests ->
                    authorizeHttpRequests
                            .requestMatchers("/api/v1/category/**")
                            .permitAll()
                }
    }
}



@Secured

   @Secured("ROLE_ADMIN")
    @GetMapping("/info")
    public @ResponseBody String info() {
        return "개인정보";
    }
  • 어노테이션에 인자로 받은 권한이 유저에게 있을 때만 실행하도록 할 수 있다.
  • 표현식을 사용할 수 없다.



@PreAuthorize , @PostAuthorize

@PreAuthorize("hasAnyRole('ROLE_MANAGER', 'ROLE_ADMIN')")
    @GetMapping("/data")
    public @ResponseBody String data() {
        return "데이터정보";
    }
  • @PreAuthorize: 메서드가 실행되기 전에 인증을 거친다.
  • @PostAuthorize: 메서드가 실행되고 나서 응답을 보내기 전에 인증을 거친다.
  • 표현식 사용이 가능하다.

사용 가능한 표현식

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





출처

SecurityConfig Spring Method Security 적용하기
스프링 시큐리티에서의 메소드 레벨 보안
[Spring Security] 4. 권한 처리
[공부정리] @Secured(), @PreAuthorize, @PostAuthorize

profile
💻 ⚾️ 🐻

0개의 댓글