Skip to content

Commit

Permalink
🚑 Hotfix: Security 설정 변경
Browse files Browse the repository at this point in the history
인증유무만 판단
  • Loading branch information
swa07016 committed Oct 15, 2023
1 parent 6e5a2f7 commit 1fdfec5
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 38 deletions.
2 changes: 1 addition & 1 deletion src/main/java/briefing/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public enum ErrorCode {

_INTERNAL_SERVER_ERROR(INTERNAL_SERVER_ERROR, "COMMON000", "서버 에러, 관리자에게 문의 바랍니다."),
_BAD_REQUEST(BAD_REQUEST,"COMMON001","잘못된 요청입니다."),
_UNAUTHORIZED(UNAUTHORIZED,"COMMON002","권한이 잘못되었습니다"),
_UNAUTHORIZED(UNAUTHORIZED,"COMMON002","로그인이 필요합니다."),
_METHOD_NOT_ALLOWED(METHOD_NOT_ALLOWED, "COMMON003", "지원하지 않는 Http Method 입니다."),
_FORBIDDEN(FORBIDDEN, "COMMON004", "금지된 요청입니다."),

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/briefing/member/api/MemberApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import briefing.member.application.dto.MemberRequest;
import briefing.member.application.dto.MemberResponse;
import briefing.member.domain.Member;
import briefing.member.domain.MemberRole;
import briefing.member.domain.SocialType;
import briefing.redis.domain.RefreshToken;
import briefing.redis.service.RedisService;
Expand Down Expand Up @@ -62,7 +63,7 @@ public CommonResponse<MemberResponse.LoginDTO> login(
) {
Member member = memberCommandService.login(socialType, request);
// TODO - TokenProvider에서 발급해주도록 변경
String accessToken = tokenProvider.createAccessToken(member.getId(),member.getSocialType().toString() ,member.getSocialId(), Arrays.asList(new SimpleGrantedAuthority("USER")));
String accessToken = tokenProvider.createAccessToken(member.getId(),member.getSocialType().toString() ,member.getSocialId(), List.of(new SimpleGrantedAuthority(MemberRole.ROLE_USER.name())));
String refreshToken = redisService.generateRefreshToken(member.getSocialId(),member.getSocialType()).getToken();
return CommonResponse.onSuccess(MemberConverter.toLoginDTO(member, accessToken, refreshToken));
}
Expand Down
23 changes: 0 additions & 23 deletions src/main/java/briefing/security/config/JwtSecurityConfig.java

This file was deleted.

51 changes: 41 additions & 10 deletions src/main/java/briefing/security/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
Expand All @@ -20,21 +24,26 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;

import static org.springframework.security.config.Customizer.withDefaults;

@Slf4j
@EnableWebSecurity
@RequiredArgsConstructor
@Configuration
public class SecurityConfig {

private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint = new JwtAuthenticationEntryPoint();

private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler = new JwtAccessDeniedHandler();

private final TokenProvider tokenProvider;

JwtAuthenticationExceptionHandler jwtAuthenticationExceptionHandler = new JwtAuthenticationExceptionHandler();
private final JwtAuthenticationExceptionHandler jwtAuthenticationExceptionHandler = new JwtAuthenticationExceptionHandler();

private static final String[] WHITE_LIST = {

Expand All @@ -45,6 +54,11 @@ public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public RoleHierarchy roleHierarchy() {
return new NullRoleHierarchy();
}

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers(
Expand All @@ -58,20 +72,24 @@ public WebSecurityCustomizer webSecurityCustomizer() {
"/swagger-ui/**",
"/docs/**",
"/members/auth/**",
"/scraps/**","/briefings/**","/chattings/**"); // NOTE - 토큰 발급 MERGE 전 테스트를 위해 허용
"/briefings/**",
"/chattings/**");
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.httpBasic(HttpBasicConfigurer::disable)
return http
.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfiguration()))
.httpBasic(withDefaults())
.csrf(AbstractHttpConfigurer::disable) // 비활성화
.cors(AbstractHttpConfigurer::disable)
.sessionManagement(manage -> manage.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // Session 사용 안함
.formLogin(AbstractHttpConfigurer::disable) // form login 사용 안함
.httpBasic(AbstractHttpConfigurer::disable) // http basic 방식 사용 안함
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/briefings/**").permitAll() // 모두 접근 가능합니다.
)
.authorizeHttpRequests(authorize -> {
authorize.requestMatchers("/briefings/**").permitAll(); // 모두 접근 가능합니다.
authorize.requestMatchers(HttpMethod.DELETE, "/members/{memberId}").authenticated();
authorize.requestMatchers("/scraps/**").authenticated();
authorize.anyRequest().authenticated();
})
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
Expand All @@ -80,4 +98,17 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.addFilterBefore(jwtAuthenticationExceptionHandler,JwtRequestFilter.class)
.build();
}

@Bean
public CorsConfigurationSource corsConfiguration() {
return request -> {
org.springframework.web.cors.CorsConfiguration config =
new org.springframework.web.cors.CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedOriginPatterns(Collections.singletonList("*"));
config.setAllowCredentials(true);
return config;
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,21 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

private final Logger LOGGER = LoggerFactory.getLogger(JwtAccessDeniedHandler.class);

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {

response.setContentType("application/json; charset=UTF-8");
response.setStatus(403);
PrintWriter writer = response.getWriter();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import java.io.IOException;
import java.io.PrintWriter;

@Component
//@Component
public class JwtAuthenticationExceptionHandler extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ public Authentication getAuthentication(String token){
.build()
.parseClaimsJws(token)
.getBody();

Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
Expand Down

0 comments on commit 1fdfec5

Please sign in to comment.