컨트롤러에서 권한 체크 방식 비교

haruceki·2025년 2월 11일

1️⃣ #username == authentication.name
→ 컨트롤러 메서드에 username 매개변수가 있을 때!

uthentication.name이 자동으로 SecurityContext에서 가져온 유저네임과 비교되므로 간단하지만 컨트롤러 메서드에서 매개변수를 꼭 받아와야 한다.

@GetMapping("/user/{username}")
@PreAuthorize("hasAuthority('ROLE_MASTER') or #username == authentication.name")
public String getUserInfo(@PathVariable String username) {
    return "User Info";
}

2️⃣ principal instanceof UserDetails and principal.username == #username
→ principal을 UserDetails로 안전하게 변환해서 사용할 때!

principal이 UserDetails인지 먼저 체크해서 타입 오류를 방지하며, username을 UserDetails에서 직접 가져와서 비교하므로 유연한 코드이나, 코드가 살짝 길어질 수 있다.

@PreAuthorize("hasAuthority('ROLE_MASTER') or (principal instanceof UserDetails and principal.username == #username)")
public String getUserInfo(@PathVariable String username) {
    return "User Info";
}
profile
희망도 절망도 없이 매일 코딩을 한다.

0개의 댓글