이제, manager와 admin의 권한 처리를 구현해보자.
먼저, 기존에 데이터베이스에 있는 회원들의 권한을 바꿔보자

update user set role='ROLE_ADMIN' where id = 2;
update user set role='ROLE_MANAGER' where id = 3;
id 가 2번, 3번인 유저의 ROLE을 바꾸어주었다.

이제, localhost:8080/manager에서 회원 2번, 3번의 아이디로 로그인하면 접근이 허락된다.
마찬가지로, localhost:8080/admin에서 회원 2번의 아이디로 로그인하면 접근이 허락된다.
기존의 사용하던 SecurityConfig 외에도 어노테이션으로 각 API별로 접근 권한을 설정할 수 있다.
- 기존 SecurityConfig
package com.example.SpringSecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록이 됨.
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true) // @Secured 활성화, @preAuthorize 활성화
public class SecurityConfig {
@Bean
public BCryptPasswordEncoder encodePwd(){
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable) // 사이트 위변조 요청 방지
.authorizeHttpRequests((authorizeRequests) -> { // 특정 URL에 대한 권한 설정.
authorizeRequests.requestMatchers("/user/**").authenticated();
authorizeRequests.requestMatchers("/manager/**")
.hasAnyRole("ADMIN", "MANAGER"); // ROLE_은 붙이면 안 된다. hasAnyRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.requestMatchers("/admin/**")
.hasRole("ADMIN"); // ROLE_은 붙이면 안 된다. hasRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.anyRequest().permitAll();
})
.formLogin((formLogin) -> {
formLogin
.loginPage("/loginForm") // 권한이 필요한 요청은 해당 url로 리다이렉트
.loginProcessingUrl("/login") // login 주소가 호출되면 시큐리티가 낚아채서 대신 로그인을 해준다.
.defaultSuccessUrl("/"); //로그인 성공시 /주소로 이동
})
.build();
}
}
2. @Secured, @PreAuthorized 사용하기

SecurityConfig 파일에 @EnabledMethodSecurity(securedEnabled = true, prePostEnabled = true) 를 통해 각각 @Secured, @preAuthorize를 활성화 시킨 후, Contoller 파일에서 아래와 같이 어노테이션을 사용할 수 있다.
@Secured("ROLE_ADMIN")
@GetMapping("/info")
public @ResponseBody String info(){
return "개인정보";
}
@PreAuthorize("hasROLE('ROLE_ADMIN') or hasROLE('ROLE_MANAGER')")
@GetMapping("/data")
public @ResponseBody String data(){
return "데이터 정보";
}
'SpringSecurity' 카테고리의 다른 글
스프링 시큐리티 복습 2 - 주요 아키텍처 이해 (0) | 2023.08.18 |
---|---|
스프링 시큐리티 복습 1 - 시큐리티 기본 API 및 Filter 이해 (0) | 2023.08.18 |
[4강] Security 로그인 (0) | 2023.07.26 |
[3강] Security 회원 가입 (0) | 2023.07.26 |
[2강] SecurityConfig 설정 (Spring Security v6.1) - (0) | 2023.07.26 |
댓글