안녕하세요. 강사님께서는 2.6 버전을 사용 권장 하셨지만 왠지 모를 궁금함에
2.7에서 사용하는 spring security 5.7 이상에서 바뀐 부분으로 한번 적용을 해보고 싶었습니다.
인프런에 올라온 많은 분들의 질문을 정리 하여
만들어 보았습니다.
package com.example.userservice.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import com.example.userservice.service.UserService;
import lombok.RequiredArgsConstructor;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurity {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final Environment env;
AuthenticationManager authenticationManager;
// spring.boot 2.7 부터는 WebSecurityConfigurerAdapter가 아닌
// SecurityFilterChain 을 사용 합니다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
authenticationManager = authenticationManagerBuilder.build();
//AuthenticationFilter authenticationFilter = new AuthenticationFilter();
//authenticationFilter.setAuthenticationManager(authenticationManager);
AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager , userService , env);
http.csrf().disable();
http.authorizeRequests()
//.antMatchers("/error/**").permitAll() // public abstract java.lang.String javax.servlet.ServletRequest.getRemoteAddr() is not supported 보기 싫을때 활성화
.antMatchers("/**")
.hasIpAddress("127.0.0.1")
.and()
.authenticationManager(authenticationManager)
.addFilter(authenticationFilter)
;
http.headers().frameOptions().disable();
return http.build();
}
//ex) 기존의 경우 AuthenticationManagerBuilder 를 오버라이드 하여 사용 하였지만 filterChain 안에서 호출 하여 설정 합니다.
/*
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
}
*/
//ex)filter를 authenticationAmanger에 주입 하던 getAuthenticationFilter역시 filterChain 내부에서 사용 합니다.
/*
private AuthenticationFilter getAuthenticationFilter() throws Exception {
AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(authenticationManager);
return authenticationFilter;
}
*/
}