SpringSecurity 이용시, 로그인 페이지와 로그아웃 페이지는 이미 만들어져 있고,
SecurityConfig 파일 생성 전에는 http://localhost:8080/login은 SpringSecurity가 다음과 같이 낚아 챈다.
이제, SecurityConfig 파일을 생성해보자
WebSecurityConfigurerAdapter가 지원이 중단되면서, 기존과 달리 SecurityFilterChain을 사용해서 SecurityConfig를 설정해야한다.
<기존 방식>
@Configuration // IoC 빈(bean)을 등록
public class SecurityConfig {
@Autowired
private PrincipalOauth2UserService principalOauth2UserService;
@Bean
public BCryptPasswordEncoder encodePwd() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
// .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN') or
// hasRole('ROLE_USER')")
// .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN') and
// hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/loginProc")
.defaultSuccessUrl("/")
.and()
.oauth2Login()
.loginPage("/login")
.userInfoEndpoint()
.userService(principalOauth2UserService);
return http.build();
}
}
< SpringSecurity v6.1 이후>
@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록이 됨.
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(); // /user/**의 주소가 들어오면 인증이 필요함
authorizeRequests.requestMatchers("/manager/**")
.hasAnyRole("ADMIN", "MANAGER"); // ROLE_은 붙이면 안 된다. hasAnyRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.requestMatchers("/admin/**")
.hasRole("ADMIN"); // ROLE_은 붙이면 안 된다. hasRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다.
authorizeRequests.anyRequest().permitAll();
})
.formLogin((formLogin) -> {
formLogin.loginPage("/login"); /* 권한이 필요한 요청은 해당 url로 리다이렉트 */
})
.build();
}
}
- /user/** 경로의 경우, 인증이 필요하다.
- /manager/** 경로의 경우, ADMIN이나, MANAGER의 ROLE을 가지고 있어야 한다.
- /admin/** 경로의 경우, ADMIN의 ROLE을 가지고 있어야 한다.
- login 하지 않고 /user, /manager, /admin 등의 경로를 검색하면 403 에러가 떠야하지만, formLogin.loginPage("/login")을 통해 로그인 페이지로 이동하도록 하였다.
Authorize HttpServletRequests :: Spring Security
Authorize HttpServletRequests :: Spring Security
While using a concrete AuthorizationManager is recommended, there are some cases where an expression is necessary, like with or with JSP Taglibs. For that reason, this section will focus on examples from those domains. Given that, let’s cover Spring Secu
docs.spring.io
최근 SpringSecurity 문서를 통해 변화를 확인할 수 있다.
SecurityConfig 파일 생성 후에는 http://localhost:8080/login은 SpringSecurity가 낚아채지 않는 것도 확인할 수 있다.
'SpringSecurity' 카테고리의 다른 글
스프링 시큐리티 복습 1 - 시큐리티 기본 API 및 Filter 이해 (0) | 2023.08.18 |
---|---|
[5강] 시큐리티 권한처리 (0) | 2023.07.27 |
[4강] Security 로그인 (0) | 2023.07.26 |
[3강] Security 회원 가입 (0) | 2023.07.26 |
[1강] SpringSecurity DB 적용 (0) | 2023.07.26 |
댓글