Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] 회원 정보 조회 및 세이프박스 금액 조회 API 구현 #31

Merged
merged 9 commits into from
Jul 29, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package umc.haruchi.apiPayload.exception.handler;

import io.jsonwebtoken.JwtException;

public class JwtExceptionHandler extends JwtException {
public JwtExceptionHandler(String message) {
super(message);
}

public JwtExceptionHandler(String message, Throwable cause) {
super(message, cause);
}
}

This file was deleted.

This file was deleted.

2 changes: 1 addition & 1 deletion src/main/java/umc/haruchi/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public OpenAPI HARUCHIOpenAPI() {
.description("HARUCHI Server API 명세서")
.version("1.0.0");

String jwtSchemeName = "JWT TOKEN";
String jwtSchemeName = "Authorization";
SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwtSchemeName);
Components components = new Components()
.addSecuritySchemes(jwtSchemeName, new SecurityScheme()
Expand Down
118 changes: 22 additions & 96 deletions src/main/java/umc/haruchi/config/login/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class SecurityConfig {

private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final JwtUtil jwtUtil;
private final JwtTokenService jwtTokenService;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final JwtExceptionHandlerFilter jwtExceptionHandlerFilter;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
Expand All @@ -39,6 +39,21 @@ public AuthenticationManager authenticationManager(AuthenticationConfiguration c
return configuration.getAuthenticationManager();
}

private static final String[] AUTH_WHITELIST = {
"/v2/api-docs",
"/v3/api-docs/**",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/file/**",
"/image/**",
"/swagger/**",
"/swagger-ui/**",
"/h2/**"
};

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
Expand Down Expand Up @@ -70,99 +85,10 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
.authorizeHttpRequests((request) -> request
.requestMatchers("/member/signup/**").permitAll()
.requestMatchers("/member/login").permitAll()
.requestMatchers("/swagger-ui/**").permitAll()
.requestMatchers("/v3/api-docs/**").permitAll()
// .requestMatchers("/member/logout").authenticated()
// .requestMatchers("/member/delete").authenticated()
.requestMatchers("/member/test").authenticated()
// .requestMatchers("/daily-budget/**").authenticated()
// .requestMatchers("/monthly-budget/**").authenticated()
// .requestMatchers("/budget-redistribution/**").authenticated()
.anyRequest().permitAll())
// .anyRequest().authenticated())
.addFilterBefore(new JwtAuthenticationFilter(jwtUtil, jwtTokenService), UsernamePasswordAuthenticationFilter.class);
.requestMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtExceptionHandlerFilter, JwtAuthenticationFilter.class);
return http.build();
}
}

//@Configuration
//@EnableWebSecurity
//@AllArgsConstructor
//public class SecurityConfig {
//
// private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
// private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
//
// @Bean
// public BCryptPasswordEncoder passwordEncoder() {
// return new BCryptPasswordEncoder();
// }
//
// @Bean
// public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
// return configuration.getAuthenticationManager();
// }
//
// @Bean
// public SecurityFilterChain securityFilterChain(HttpSecurity http,/*, DispatcherServlet dispatcherServlet*/JwtTokenProvider jwtTokenProvider) throws Exception {
//
// // CSRF, CORS
//// http.cors(cors -> cors
//// .configurationSource(CorsConfig.corsConfigurationSource()));
// http.csrf(AbstractHttpConfigurer::disable);
// //http.csrf(csrf -> csrf.disable());
// http.cors(Customizer.withDefaults());
//
// // 세션 관리 상태 없음으로 구성, Spring Security가 세션 생성 or 사용 X
// http.sessionManagement(session -> session.sessionCreationPolicy(
// SessionCreationPolicy.STATELESS));
//
// // FormLogin, BasicHttp 비활성화
// //http.formLogin((form) -> form.disable());
// http.formLogin(AbstractHttpConfigurer::disable);
// http.httpBasic(AbstractHttpConfigurer::disable);
//
//// // jwt filter with login
//// JwtAuthenticationFilter loginFilter = new JwtAuthenticationFilter(
//// authenticationManager(authenticationConfiguration), jwtUtil);
//// loginFilter.setFilterProcessesUrl("member/login");
//// http.addFilterAt(loginFilter, UsernamePasswordAuthenticationFilter.class);
//
// // JwtAuthFilter를 UsernamePasswordAuthenticationFilter 앞에 추가
// http.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
//
// http.exceptionHandling((exceptionHandling) -> exceptionHandling
// .authenticationEntryPoint(jwtAuthenticationEntryPoint)
// .accessDeniedHandler(jwtAccessDeniedHandler));
//
// // 권한 규칙 작성
// http.authorizeHttpRequests(authorize -> authorize
//// .requestMatchers("/member/signup/**").permitAll()
//// .requestMatchers("/member/login").permitAll()
// .requestMatchers("/member/logout").hasRole("USER")
// .requestMatchers("/member/delete").hasRole("USER")
// .anyRequest().permitAll()
// );
//
// return http.build();
// }
//
// private static final String[] AUTH_WHITELIST = {
// "/v2/api-docs",
// "/v3/api-docs/**",
// "/configuration/ui",
// "/swagger-resources/**",
// "/configuration/security",
// "/swagger-ui.html",
// "/webjars/**",
// "/file/**",
// "/image/**",
// "/swagger/**",
// "/swagger-ui/**",
// "/h2/**"
// };
//
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().requestMatchers(AUTH_WHITELIST);
// }
//}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
Expand All @@ -19,11 +20,13 @@ public class JwtAccessDeniedHandler implements AccessDeniedHandler {

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.error("JwtAccessDeniedHandler 실행");
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
ApiResponse<Object> apiResponse = ApiResponse.onFailure(HttpStatus.FORBIDDEN.name(), "COMMON403", "금지된 요청입니다.");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), apiResponse);
log.error("No Authorities", accessDeniedException);
ApiResponse<Object> apiResponse =
ApiResponse.onFailure(HttpStatus.FORBIDDEN.name(), "COMMON403", "금지된 요청입니다.");
String responseBody = new ObjectMapper().writeValueAsString(apiResponse);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.FORBIDDEN.value());
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseBody);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
Expand All @@ -18,12 +19,15 @@
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
log.error("JwtAuthenticationEntryPoint 실행");
response.setContentType("application/json");
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
log.error("Not Authenticated Request", authException);
ApiResponse<Object> apiResponse =
ApiResponse.onFailure(HttpStatus.NOT_FOUND.name(), "MEMBER4027", "유효한 JWT 토큰이 없습니다.");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), apiResponse);
ApiResponse.onFailure(HttpStatus.UNAUTHORIZED.name(), "COMMON401", "인증이 필요합니다.");
String responseBody = new ObjectMapper().writeValueAsString(apiResponse);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseBody);
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
package umc.haruchi.config.login.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import umc.haruchi.apiPayload.ApiResponse;
import umc.haruchi.apiPayload.exception.handler.JwtExpiredHandler;
import umc.haruchi.apiPayload.exception.handler.JwtInvalidHandler;

import java.io.IOException;

Expand All @@ -28,40 +23,46 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenService jwtTokenService;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// String accessToken = request.getHeader("Authorization");
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String token = resolveToken(request);
if (token == null) {
filterChain.doFilter(request, response);
return;
}
if (jwtUtil.isExpired(token)) {
filterChain.doFilter(request, response);
return;
}

try {
jwtUtil.validateToken(token);
JwtUtil.validateAccessToken(token); // 생략해도 될까?

if (token != null && jwtUtil.validateToken(token)) {
jwtTokenService.checkExpired(token); // redis 적용 시 삭제
Authentication authentication = jwtUtil.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
jwtTokenService.checkExpired(token);
} catch (JwtExpiredHandler e) {
response.setContentType("application/json");
ApiResponse<Object> apiResponse =
ApiResponse.onFailure(HttpStatus.NOT_FOUND.name(), "MEMBER4027", "Invalid token is not found.");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), apiResponse);
return;
} catch (JwtInvalidHandler e) {
response.setContentType("application/json");
ApiResponse<Object> apiResponse =
ApiResponse.onFailure(HttpStatus.UNAUTHORIZED.name(), "MEMBER4022", "Invalid token.");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), apiResponse);
return;
}
// if (token == null) {
// filterChain.doFilter(request, response);
// return;
// }
// if (jwtUtil.isExpired(token)) {
// filterChain.doFilter(request, response);
// return;
// }
//
// try {
// jwtUtil.validateToken(token);
// JwtUtil.validateAccessToken(token); // 생략해도 될까?
//
// Authentication authentication = jwtUtil.getAuthentication(token);
// SecurityContextHolder.getContext().setAuthentication(authentication);
// jwtTokenService.checkExpired(token);
// } catch (JwtExpiredHandler e) {
// response.setContentType("application/json");
// ApiResponse<Object> apiResponse =
// ApiResponse.onFailure(HttpStatus.NOT_FOUND.name(), "MEMBER4027", "Invalid token is not found.");
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.writeValue(response.getWriter(), apiResponse);
// return;
// } catch (JwtInvalidHandler e) {
// response.setContentType("application/json");
// ApiResponse<Object> apiResponse =
// ApiResponse.onFailure(HttpStatus.UNAUTHORIZED.name(), "MEMBER4022", "Invalid token.");
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.writeValue(response.getWriter(), apiResponse);
// return;
// }
filterChain.doFilter(request, response);

}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package umc.haruchi.config.login.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import umc.haruchi.apiPayload.ApiResponse;
import umc.haruchi.apiPayload.exception.handler.JwtExceptionHandler;

import java.io.IOException;

@Component
public class JwtExceptionHandlerFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch(JwtExceptionHandler ex) {
setErrorResponse(HttpStatus.UNAUTHORIZED, request, response, ex);
}
}

public void setErrorResponse(HttpStatus status, HttpServletRequest req,
HttpServletResponse res, Throwable ex) throws IOException {
ApiResponse<Object> apiResponse =
ApiResponse.onFailure(HttpStatus.UNAUTHORIZED.name(), "COMMON401", ex.getMessage());
String responseBody = new ObjectMapper().writeValueAsString(apiResponse);
res.setStatus(status.value());
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
res.getWriter().write(responseBody);
}
}
Loading