[Spring Boot] 3. Spring Security 권한 설정

[Spring Boot] 3. Spring Security 권한 설정

반응형

1. 시큐리티Config 파일에서 .access("hasRole('ADMIN')") 을 이용한다.

.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

* 시큐리티Config 전체 코드 참고 : https://black-mint.tistory.com/11

2. @EnableGlobalMethodSecurity를 사용한다.

@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http .authorizeRequests() .antMatchers("/css/**").permitAll() .antMatchers("/board/**").authenticated() .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") // 권한 설정 .anyRequest().permitAll() .and() .formLogin() .loginPage("/loginForm") // 로그인 페이지 .loginProcessingUrl("/login") .defaultSuccessUrl("/") .and() .logout() .permitAll(); } }

시큐리티 Config파일 상단에 @Secured 어노테이션과 @ preAuthorize 를 활성화하는 @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) 을 추가한다.

컨트롤러에 @Secured를 추가해서 페이지 권할을 설정한다.

@Secured("ADMIN") @GetMapping("/admin") public String admin() { return "/admin"; }

2개 이상 권한을 주고 싶을 때는 @PreAuthorize를 추가하면 된다.

@PreAuthorize("hasRole('ADMIN') or hasRole('MANAGER')") @GetMapping("/admin") public String admin() { return "/admin"; }

-

* 해당 글은 인프런에 게시된 '최주호'님의 강의를 듣고 개인적으로 정리한 글입니다.

강의 출처 : https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0

from http://black-mint.tistory.com/17 by ccl(A) rewrite - 2021-12-17 18:27:38