정의
장점
예시
@Configuration
@EnableMethodSecurity //메서드 보안 단위 활성화
public class SecurityConfig{
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.formLogin();
return http.build();
}
Controller에서 사용하는 예시
@RestController
@RequestMapping("/users")
public class UserController{
@GetMapping("/{id}")
@PreAuthorize("#id == authentication.principal.id or hasRole('ADMIN')")
//본인 정보는 접근 가능 and 관리자도 접근 가능
//그외는 403 Forbidden
public String getUser(@PathVariable Long id){
return "User Info";
}
}
Service 계층에서 사용하는 예시(실무에서 추천하는 것임)
//실무에서는 Controller보다 Serviced에 권한을 거는 것이 더 안전하다.
@Service
public class UserService{
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(User id){
System.out.println("삭제완료");
}
}
Bean 호출 방식 예시 (실무 추천)
@Service
public class AuthService {
public boolean isOwner(Long userId){
Long loginUserId = getLoginUserId();
return userId.equals(loginUserId);
}
private Long getLoginUserId(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
CustomUser user = {CustomUser} aitj.getPrincipal();
return user.getId();
}
}
@PreAuthorize("@authService.isOwner(#userId) or hasRole('ADMIN')")
public void updateUser(Long userId) {
}
전체 실행 흐름
클라이언트 요청
|
FilterChain (URL 보안 검사)
|
Controller 호출
|
Service 호출
|
@PreAuthorize가 프록시에서 가로채서 권한 검사
|
통과 -> 메서드 실행
거부 -> 403발생