728x90

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

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

 

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

 

[Spring Boot] 1. Security 사용 설정, 비밀번호 인코딩

1. 의존성 추가  - build.gradle 에 다음 의존성을 추가해준다. implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.security:spring-security-test'..

black-mint.tistory.com

 

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

+ Recent posts