Authorization by Spring Security
2024. 2. 28. 21:33ㆍSpring Boot
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true
)
public class SecurityConfig
@EnableMethodSecurity를 통하여 메소트에 권한 설정을 하겠다
@PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
@RequestMapping(path = "/user", method = RequestMethod.GET)
public @ResponseBody String check_login() {
return "you are user";
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(path = "/admin", method = RequestMethod.GET)
public @ResponseBody String check_admin() {
return "you are admin";
}
작업이 수행전에 권한 검사를 하는 @PreAuthorize와 끝난 후에 검사를 하는 @PostAuthorize가 있는데
이번 예시에서는 @PreAuthorize를 이용해서 특정 Role을 가진 경우와 여러 권한 중 하나를 가진 경우 허가하는 방식으로 예시를 구현했다.
사용자에게 Role을 부여하는 방법은
UserDetail을 설정할 때 설정한 메소드에 자신이 원하는 방식으로 Role을 주면 된다.
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> collect = new ArrayList<>();
collect.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return user.getRole();
}
});
user(String name, String password, String email) {
this.name = name;
this.password = password;
this.email = email;
this.role = "ROLE_USER";
}
단 설정한 Role에는 Role_이라는 Prefix를 붙여야 한다.
다르게 설정 할 수도 있긴 한데 기본 값은 Role_이라서 없으면 오류가 난다
'Spring Boot' 카테고리의 다른 글
| Asynchronized (0) | 2024.03.02 |
|---|---|
| Spring Boot Studying (0) | 2024.02.28 |
| Jpa 순환 참조 N + 1 문제 (0) | 2024.02.27 |
| CORS (1) | 2024.02.24 |
| Naver Login (0) | 2024.02.19 |