티스토리 뷰

반응형

인가(Authorization) 설정입니다.

 

이번 단계에서는

  1. hasRole() vs hasAuthority() 차이
  2. URL 기반 권한 설정
  3. 메서드 기반 권한(@PreAuthorize)
  4. 다중 권한 처리

를 정리합니다.

 

4-1. hasRole() vs hasAuthority() 차이

메서드 내부 동작 예시
hasRole("ADMIN") 내부적으로 "ROLE_ADMIN" 권한이 있는지 검사 roles("ADMIN") 로 만든 계정만 통과
hasAuthority("ROLE_ADMIN") "ROLE_ADMIN" 권한이 있는지 그대로 검사 DB에서 ROLE_ 접두사 포함한 권한 직접 체크

 

중요: hasRole() 은 자동으로 "ROLE_" prefix를 붙입니다.

그래서 DB에 ROLE_ADMIN을 저장했다면,

hasRole("ADMIN") 또는 hasAuthority("ROLE_ADMIN") 둘 다 가능하지만 혼용 시 주의해야 합니다.

 

4-2. URL 기반 권한 설정 예시

📂 파일명: SecurityConfig.java

package com.example.security;


import lombok.RequiredArgsConstructor;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@RequiredArgsConstructor
public class SecurityConfig {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")      // ROLE_ADMIN 필요
                .requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER") // ROLE_ADMIN 또는 ROLE_MANAGER
                .requestMatchers("/api/**").hasAuthority("ROLE_API") // ROLE_ 접두사까지 명시
                .anyRequest().authenticated()
            )
            .formLogin(form -> form.permitAll())
            .logout(logout -> logout.permitAll())
            .csrf(csrf -> csrf.disable());


        return http.build();
    }
}

 

4-3. 메서드 보안(@PreAuthorize) 사용

스프링 시큐리티는 URL 보안뿐만 아니라, 메서드 호출 시점에서도 권한 체크를 할 수 있습니다.

예를 들어 Controller, Service, Repository 메서드에 권한을 걸 수 있습니다.

 

1. 설정 클래스에 @EnableMethodSecurity 추가

import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;


@Configuration
@EnableMethodSecurity // 메서드 보안 활성화
public class SecurityConfig {
    // ... 기존 설정
}

 

2. 컨트롤러 예시

package com.example.controller;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class AdminController {


    @PreAuthorize("hasRole('ADMIN')") // ROLE_ADMIN 필요
    @GetMapping("/admin/data")
    public String adminData() {
        return "관리자 전용 데이터";
    }


    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    @GetMapping("/admin/manager/data")
    public String adminOrManagerData() {
        return "관리자 또는 매니저 데이터";
    }


    @PreAuthorize("hasAuthority('ROLE_API')")
    @GetMapping("/api/data")
    public String apiData() {
        return "API 전용 데이터";
    }
}

 

4-4. 다중 권한 처리

URL 방식

.requestMatchers("/reports/**").hasAnyRole("ADMIN", "MANAGER")

 

@PreAuthorize 방식

@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_MANAGER')")

 

4-5. 정리

  • hasRole() : 내부적으로 ROLE_ prefix를 붙이므로 "ADMIN"만 적어도 "ROLE_ADMIN" 권한을 찾음
  • hasAuthority() : 전체 권한 문자열을 그대로 비교 (ex. "ROLE_ADMIN")
  • URL 보안과 메서드 보안을 병행하면 더 안전한 설계 가능
  • 실무에서는 API 서버인 경우, URL 기반 보안 + JWT 기반 인가 조합이 일반적
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함