Skip to content

Commit

Permalink
[refactor] #211 Code Smell 잡기
Browse files Browse the repository at this point in the history
  • Loading branch information
HYG committed Feb 7, 2024
1 parent 4c31e88 commit 9408b0e
Showing 1 changed file with 103 additions and 65 deletions.
168 changes: 103 additions & 65 deletions src/main/java/com/dmarket/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,69 +36,107 @@
@RequiredArgsConstructor
public class SecurityConfig {

private final AuthenticationConfiguration authenticationConfiguration;
private final JWTUtil jwtUtil;
private final RefreshTokenRepository refreshTokenRepository;
private final UserRepository userRepository;
private final LogoutService logoutService;

@Value("${spring.cors.path}")
private List<String> corsPath;

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {

return configuration.getAuthenticationManager();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// CORS 설정
http
.cors(corsCustomizer -> corsCustomizer.configurationSource(request -> {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(
Collections.singletonList("http://localhost:3000"));
configuration.setAllowedOriginPatterns(corsPath); // 2024-02-02 수정
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
configuration.setExposedHeaders(Collections.singletonList("Authorization"));
return configuration;
}));

// CSRF 비활성화
http.csrf(auth -> auth.disable());

// Form 로그인 비활성화
http.formLogin(auth -> auth.disable());

// HTTP Basic 인증 비활성화
http.httpBasic(auth -> auth.disable());

// 접근 권한 설정
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/api/users/login", "/api/users/email/**", "/api/users/join")
.permitAll()
.anyRequest().permitAll());

// JWT 필터 추가
http.addFilterBefore(new JWTFilter(jwtUtil, userRepository, refreshTokenRepository), LoginFilter.class);

// 로그인 필터 추가
http.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil,
refreshTokenRepository), UsernamePasswordAuthenticationFilter.class);

// 로그아웃 설정
http.logout(logout -> logout.logoutUrl("/api/users/logout")
.addLogoutHandler(logoutService)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder
.clearContext()));

// 세션 정책 설정
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

return http.build();
}
private final AuthenticationConfiguration authenticationConfiguration;
private final JWTUtil jwtUtil;
private final RefreshTokenRepository refreshTokenRepository;
private final UserRepository userRepository;
private final LogoutService logoutService;

@Value("${spring.cors.path}")
private List<String> corsPath;

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {

return configuration.getAuthenticationManager();
}

// 계층 권한 설정
@Bean
public RoleHierarchy roleHierarchy() {

RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();

hierarchy.setHierarchy("ROLE_GM > ROLE_PM\n" +
"ROLE_GM > ROLE_SM\n" +
"ROLE_PM > ROLE_USER\n" +
"ROLE_SM > ROLE_USER"
);

return hierarchy;
}

//패스워드 인코딩
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors((corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {

@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {

CorsConfiguration configuration = new CorsConfiguration();

configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedOriginPatterns(corsPath); //2024-02-02 수정
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);

configuration.setExposedHeaders(Collections.singletonList("Authorization"));

return configuration;
}
})));

//csrf disable
http
.csrf((auth) -> auth.disable());

//From 로그인 방식 disable
http
.formLogin((auth) -> auth.disable());

//http basic 인증 방식 disable
http
.httpBasic((auth) -> auth.disable());

// 접근 권한 설정
// 계층 권한으로 페이지 접근 제한
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/", "/api/users/login", "/api/users/email/**", "/api/users/join").permitAll()
// .requestMatchers("/api/admin/**").hasAnyRole("GM", "SM", "PM")
// .anyRequest().authenticated());
.anyRequest().permitAll());


// 커스텀 필터 적용
http
.addFilterBefore(new JWTFilter(jwtUtil, userRepository, refreshTokenRepository), LoginFilter.class);

// 커스텀 필터 적용
http
.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil, refreshTokenRepository), UsernamePasswordAuthenticationFilter.class);

// 로그아웃 접근 경로 설정, 접근 시 동작할 서비스(logoutService) 지정
http
.logout((logout) -> logout.logoutUrl("/api/users/logout")
.addLogoutHandler(logoutService)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
);

//세션 설정
http
.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

return http.build();
}
}

0 comments on commit 9408b0e

Please sign in to comment.