인프런 커뮤니티 질문&답변
Security 설정
작성
·
136
0
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final AuthenticationConfiguration authenticationConfiguration;
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
;
http
.headers().frameOptions().disable()
;
http
.authorizeHttpRequests(authorize -> {
try {
authorize
.requestMatchers(new IpAddressMatcher("127.0.0.1")).permitAll();
} catch (Exception e) {
e.printStackTrace();
}
}
)
;
http
.formLogin().disable()
.httpBasic().disable()
;
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
;
http
.addFilterBefore(new CustomAuthenticationFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class)
;
return http.build();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
-- custofilter
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
setFilterProcessesUrl("/login"); // 로그인 경로 설정
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
RequestLogin requestLogin = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class);
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(requestLogin.getEmail(), requestLogin.getPassword());
Authentication authenticate = getAuthenticationManager().authenticate(authenticationToken);
AccountContext principal = (AccountContext) authenticate.getPrincipal();
return authenticate;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
}
@Override
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
}
-- customuserdetailservice
@Service
@RequiredArgsConstructor
public class CustomUserDetailService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByEmail(username).orElseThrow(
() -> new UsernameNotFoundException("user not found exception"));
return new AccountContext(userEntity, List.of(new SimpleGrantedAuthority("ROLE_USER")));
}
}
답변 1
0
안녕하세요, 인프런 AI 인턴입니다.
도루크막토님의 코드를 잘 확인했습니다. SecurityConfig 클래스에서 스프링 시큐리티의 설정을 커스터마이징하여 사용 중이시군요. 필터 체인을 설정하는 부분에서 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)를 사용해 세션을 사용하지 않는 STATELESS 정책을 설정하셨고, 커스텀 인증 필터인 CustomAuthenticationFilter를 UsernamePasswordAuthenticationFilter 전에 추가하셨네요. 또한 CustomUserDetailService를 통해 UserDetailsService를 직접 구현하여 사용자 정보를 불러오는 로직을 구현하셨습니다.
스프링 시큐리티를 강의하거나 스터디에서 다룰 때 이 코드를 예로 들어 설명하시면 이해하는 데 큰 도움이 될 것 같습니다. 특히 IP 주소로 접근 제어를 하는 부분이나 커스텀 인증 로직을 구현한 부분은 실무에서도 유용하게 쓰일 수 있습니다.
추가적으로 스프링 시큐리티의 다양한 설정을 학습하시면서 설정에 대한 이해를 더 넓히고싶으시다면, 스프링 부트 레퍼런스 문서를 참조하실 수 있습니다. 예를 들어, 실제 프로덕션 환경에서 스프링 애플리케이션을 배포할 때는 보안 설정을 좀 더 세부적으로 다루어야 하는데, 문서에는 UserDetailsService, SecurityFilterChain 등의 컴포넌트를 어떻게 사용해야 하는지에 대한 유용한 정보들이 있습니다.
다음은 스프링 부트 레퍼런스 문서의 일부 링크들입니다:
- 액추에이터 엔드포인트 보안 설정 (Spring Boot Reference Documentation v3.1.5)
- WebFlux 보안 설정 (Spring Boot Reference Documentation v3.1.5)
- MVC 보안 설정 (Spring Boot Reference Documentation v3.1.5)
이 문서들을 통해 스프링 시큐리티의 다양한 설정 옵션들과 사용 방법에 대해 자세히 알아볼 수 있습니다. 공부하시는 데 큰 도움이 되길 바랍니다!




