Skip to content

[BE/feat] 익명 사용자일 경우 예외 처리 #309

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

Merged
merged 4 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.gaebaljip.exceed.common.annotation.Timer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.gaebaljip.exceed.common.annotation.Timer;
import com.gaebaljip.exceed.common.exception.DecryptionErrorException;
import com.gaebaljip.exceed.common.exception.EncryptionErrorException;

Expand Down Expand Up @@ -47,6 +47,7 @@ public String encrypt(String value) {
throw EncryptionErrorException.EXECPTION;
}
}

@Timer
public String decrypt(final String encryptedValue) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@
import com.gaebaljip.exceed.common.ApiResponse;
import com.gaebaljip.exceed.common.ApiResponseGenerator;
import com.gaebaljip.exceed.common.Error;
import com.gaebaljip.exceed.security.exception.ExpiredJwtException;
import com.gaebaljip.exceed.security.exception.InvalidJwtException;
import com.gaebaljip.exceed.security.exception.SecurityErrorCode;
import com.gaebaljip.exceed.security.exception.UnSupportedJwtException;
import com.gaebaljip.exceed.security.exception.*;

import lombok.extern.slf4j.Slf4j;

Expand All @@ -32,21 +29,33 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ExpiredJwtException.class)
protected ApiResponse<?> handleExpiredJwtAuthenticationException(ExpiredJwtException e) {
return ApiResponseGenerator.fail(
SecurityErrorCode.EXPIRED_JWT.getCode(), e.getMessage(), HttpStatus.UNAUTHORIZED);
SecurityErrorCode.EXPIRED_JWT.getCode(),
SecurityErrorCode.EXPIRED_JWT.getReason(),
HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(UnSupportedJwtException.class)
protected ApiResponse<?> handleUnsupportedJwtException(UnSupportedJwtException e) {
return ApiResponseGenerator.fail(
SecurityErrorCode.UNSUPPORTED_JWT.getCode(),
e.getMessage(),
SecurityErrorCode.UNSUPPORTED_JWT.getReason(),
HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(InvalidJwtException.class)
protected ApiResponse<?> handleInvalidJwtException(InvalidJwtException e) {
return ApiResponseGenerator.fail(
SecurityErrorCode.INVALID_JWT.getCode(), e.getMessage(), HttpStatus.UNAUTHORIZED);
SecurityErrorCode.INVALID_JWT.getCode(),
SecurityErrorCode.UNSUPPORTED_JWT.getReason(),
HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(SignatureJwtException.class)
protected ApiResponse<?> handleSignatureJwtException(SignatureJwtException e) {
return ApiResponseGenerator.fail(
SecurityErrorCode.SIGNATURE_JWT.getCode(),
SecurityErrorCode.SIGNATURE_JWT.getReason(),
HttpStatus.UNAUTHORIZED);
}

@ExceptionHandler(HttpMessageNotReadableException.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
@Component
@Slf4j
public class LoggingFilter extends OncePerRequestFilter {
private final List<String> excludeUrl = List.of("/actuator/health", "/actuator/prometheus");
private final List<String> excludeUrl =
List.of("/actuator/health", "/actuator/prometheus", "/v1/health");

@Override
protected void doFilterInternal(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.gaebaljip.exceed.member.adapter.out.persistence;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.time.LocalDateTime;
import java.util.Optional;

import com.gaebaljip.exceed.common.annotation.Timer;
import org.springframework.stereotype.Component;

import com.gaebaljip.exceed.auth.exception.MemberNotCheckedException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import java.util.Optional;

import com.gaebaljip.exceed.common.annotation.Timer;
import org.springframework.stereotype.Component;

import com.gaebaljip.exceed.common.annotation.Timer;
import com.gaebaljip.exceed.common.redis.RedisUtils;
import com.gaebaljip.exceed.member.application.port.out.TimeOutPort;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.gaebaljip.exceed.member.application;

import com.gaebaljip.exceed.common.annotation.Timer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gaebaljip.exceed.common.Encryption;
import com.gaebaljip.exceed.common.annotation.Timer;
import com.gaebaljip.exceed.dto.request.CheckMemberRequest;
import com.gaebaljip.exceed.member.adapter.out.persistence.MemberEntity;
import com.gaebaljip.exceed.member.application.port.in.CheckCodeUsecase;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ public boolean validateAccessToken(String accessToken, HttpServletRequest reques
LocalDateTime.now(),
e.getMessage());
throw UnSupportedJwtException.EXECPTION; // 지원되지 않는 토큰
} catch (io.jsonwebtoken.security.SignatureException e) {
log.error(
"method ={}, URL = {}, time={}, errorMessage={}",
request.getMethod(),
request.getRequestURL(),
LocalDateTime.now(),
e.getMessage());
throw UnSupportedJwtException.EXECPTION; // 지원되지 않는 토큰
} catch (IllegalArgumentException e) {
log.error(
"method ={}, URL = {}, time={}, errorMessage={}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Qualifier;
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;
import org.springframework.web.servlet.HandlerExceptionResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaebaljip.exceed.common.ApiResponse;
import com.gaebaljip.exceed.common.Error;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class JwtAuthenticationPoint implements AuthenticationEntryPoint {

private final HandlerExceptionResolver resolver;
Expand All @@ -27,7 +36,28 @@ public void commence(
HttpServletResponse response,
AuthenticationException authException)
throws IOException {
resolver.resolveException(
request, response, null, (Exception) request.getAttribute("exception"));
if (request.getAttribute("exception") == null) {
handleAuthenticationException(response);
} else {
resolver.resolveException(
request, response, null, (Exception) request.getAttribute("exception"));
}
}

private void handleAuthenticationException(HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.isCommitted();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(
response.getWriter(),
new ApiResponse.CustomBody<>(
false,
null,
new Error(
SecurityErrorCode.NEED_AUTHENTICATION.getCode(),
SecurityErrorCode.NEED_AUTHENTICATION.getReason(),
HttpStatus.BAD_REQUEST.toString())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
public enum SecurityErrorCode {
INVALID_JWT(401, "5000", "잘못된 토큰입니다."),
EXPIRED_JWT(401, "5001", "만료된 토큰입니다."),
UNSUPPORTED_JWT(401, "5002", "지원되지 않는 토큰입니다.");
UNSUPPORTED_JWT(401, "5002", "지원되지 않는 토큰입니다."),
SIGNATURE_JWT(401, "5003", "토큰의 형식이 잘못 됬습니다."),
NEED_AUTHENTICATION(401, "5004", "인증이 필요합니다.");

private final Integer status;
private final String code;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.gaebaljip.exceed.security.exception;

import org.springframework.security.core.AuthenticationException;

import lombok.Getter;

@Getter
public class SignatureJwtException extends AuthenticationException {

public static AuthenticationException EXECPTION = new SignatureJwtException();

public SignatureJwtException() {
super(SecurityErrorCode.SIGNATURE_JWT.getReason());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
Expand Down Expand Up @@ -29,19 +30,19 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtManager jwtManager;
private final JwtResolver jwtResolver;
private final MemberDetailService memberDetailService;
private final List<String> excludeUrl = List.of("/actuator", "/v1/health");

@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

final String bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION);

log.info("bearerToken : {}", bearerToken);
if (bearerToken == null || !bearerToken.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}

String accessToken = jwtResolver.extractToken(bearerToken);
try {
if (jwtManager.validateAccessToken(accessToken, request)) {
Expand Down Expand Up @@ -72,4 +73,16 @@ protected void doFilterInternal(
}
filterChain.doFilter(request, response);
}

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
boolean flag = false;
for (String url : excludeUrl) {
if (path.startsWith(url)) {
flag = true;
}
}
return flag;
}
}
Loading