티스토리 뷰
반응형
인가(Authorization) 설정입니다.
이번 단계에서는
- hasRole() vs hasAuthority() 차이
- URL 기반 권한 설정
- 메서드 기반 권한(@PreAuthorize)
- 다중 권한 처리
를 정리합니다.
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 기반 인가 조합이 일반적
반응형
'Spring Security' 카테고리의 다른 글
[Spring Security] 스프링 시큐리티 사용자 인증 구현하기 (3) | 2025.08.13 |
---|---|
[Spring Security] 스프링 시큐리티 적용하기 (0) | 2025.08.13 |
[Spring Security] 스프링 시큐리티 기본 개념 익히기 (1) | 2025.08.13 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 리액트
- HTML
- script element
- 서블릿
- Redux
- Session
- 네트워크
- Java Server Page
- Spring
- httpServletRequest
- el
- CSS
- CSS 속성
- 미들웨어
- javaserverpage
- react
- 스프링 시큐리티
- Binding
- 제이쿼리
- 인가
- 내장객체
- 세션
- Network
- JSP
- nodejs
- html css
- Servlet
- 서브넷팅
- 스프링
- Spring Security
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함