|
| 1 | +package com.gdsc_teamb.servertoyproject.jwt; |
| 2 | + |
| 3 | +import org.springframework.context.annotation.Bean; |
| 4 | +import org.springframework.context.annotation.Configuration; |
| 5 | +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; |
| 6 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 7 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 8 | +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; |
| 9 | +import org.springframework.security.config.http.SessionCreationPolicy; |
| 10 | +import org.springframework.security.crypto.factory.PasswordEncoderFactories; |
| 11 | +import org.springframework.security.crypto.password.PasswordEncoder; |
| 12 | +import org.springframework.security.web.SecurityFilterChain; |
| 13 | +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; |
| 14 | +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; |
| 15 | + |
| 16 | +@Configuration |
| 17 | +@EnableWebSecurity // 웹 보안 활성화 (CSRF 공격 방지) |
| 18 | +@EnableMethodSecurity // 메서드 레벨의 보안 설정 활성화 |
| 19 | +public class SecurityConfig { |
| 20 | + private JwtTokenProvider jwtTokenProvider; |
| 21 | + |
| 22 | + @Bean |
| 23 | + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ |
| 24 | + http |
| 25 | + .httpBasic(AbstractHttpConfigurer::disable) // rest api 이므로 basic auth 및 csrf 보안을 사용 X |
| 26 | + .csrf(AbstractHttpConfigurer::disable) |
| 27 | + .sessionManagement(config -> config.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 세션 사용 X |
| 28 | + .authorizeRequests() |
| 29 | + .requestMatchers(new AntPathRequestMatcher("/members/login")).permitAll() // 모든 요청 허가 |
| 30 | + .requestMatchers(new AntPathRequestMatcher("/members/test")).hasRole("USER") // USER 권한 확인 |
| 31 | + .anyRequest().authenticated() // 이 밖에 모든 요청에 대해 인증 필요 |
| 32 | + .and() |
| 33 | + .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); |
| 34 | + return http.build(); |
| 35 | + } |
| 36 | + |
| 37 | + @Bean |
| 38 | + public PasswordEncoder passwordEncoder() { |
| 39 | + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); |
| 40 | + } |
| 41 | +} |
0 commit comments