2.메서드에 권한 부여하기
Security 구성 클래스에 @EnableMethodSecurity가 작성되어 있을 경우, 아래의 Annotation을 적용할 수 있음
1-1. @PreAuthorize
@PreAuthorize 적용 예시
→ readAccount(Long id) 메서드는 ADMIN 권한이 있는 사용자만 호출할 수 있음
BankService.java
@Component
public class BankService {
@PreAuthorize("hasRole('ADMIN')")
public Account readAccount(Long id) {
// ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
}
}1-2. @PostAuthorize
@PostAuthorize 적용 예시
→ readAccount(Long id) 메서드는 @PreAuthorize() 내에 작성된 표현식을 만족해야만 Account 객체를 반환할 수 있음
returnObject.owner == authentication.name
메서드의 반환 값(returnObject)인 Account 객체의 owner 필드의 값이
인증된 사용자의 name(authentication.name)과 일치하는지?
BankService.java
@Component
public class BankService {
@PostAuthorize("returnObject.owner == authentication.name")
public Account readAccount(Long id) {
// ... is only returned if the `Account` belongs to the logged in user
}
}Last updated on