Skip to content

Commit

Permalink
fix : JwtFilter 예외 엔드포인트 추가 (#274)
Browse files Browse the repository at this point in the history
* refactor : 토큰 resolve 시, null 반환을 예외 throw로 수정

* refactor : JwtFilter 거치지 않는 엔드포인트 추가

* refactor : JwtFilter 거치지 않는 엔드포인트 추가

- /api/users/{userNickname}
- /api/users/{userNickname}/groups

* refactor : 불필요한 shouldNotFilter 호출 제거
  • Loading branch information
rladmstn authored Jan 8, 2025
1 parent 50b8406 commit 1730dce
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -21,22 +22,34 @@
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final TokenProvider tokenProvider;
private final List<String> excludedPaths = Arrays.asList("/api/auth/sign-in", "/api/auth/sign-up",
"/api/auth/reissue-token");
private final List<String> excludedPaths = Arrays.asList(
"/swagger-ui",
"/v3/api-docs",
"/api/auth/sign-in",
"/api/auth/sign-up",
"/api/auth/reissue-token",
"/api/users/check-email",
"/api/users/check-nickname",
"/api/users/check-baekjoon-nickname");

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
return excludedPaths.stream().anyMatch(path::startsWith);
if (excludedPaths.stream().anyMatch(path::startsWith))
return true;

return isOtherUserInfoEndpoint(path);
}

private static boolean isOtherUserInfoEndpoint(String path) {
Pattern infoPattern = Pattern.compile("^/api/users/(?!me$)[^/]+$");
Pattern groupsPattern = Pattern.compile("^/api/users/(?!me)[^/]+/groups$");
return infoPattern.matcher(path).matches() || groupsPattern.matcher(path).matches();
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (shouldNotFilter(request)) {
filterChain.doFilter(request, response);
return;
}
try {
String token = tokenProvider.resolveToken(request);
if (token != null && tokenProvider.validateToken(token)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public String resolveToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (StringUtils.hasValue(token) && token.startsWith("Bearer"))
return token.substring(7);
return null;
throw new JwtRequestException(HttpStatus.BAD_REQUEST.value(), "BAD_REQUEST", "유효한 형태의 토큰이 존재하지 않습니다.");
}

private Claims getClaims(String expiredToken) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import com.gamzabat.algohub.common.redis.RedisService;
import com.gamzabat.algohub.enums.ImageType;
import com.gamzabat.algohub.enums.Role;
import com.gamzabat.algohub.exception.JwtRequestException;
import com.gamzabat.algohub.exception.UserValidationException;
import com.gamzabat.algohub.feature.group.studygroup.exception.CannotFoundUserException;
import com.gamzabat.algohub.feature.image.service.ImageService;
Expand Down Expand Up @@ -168,9 +167,6 @@ public void deleteUser(User user, DeleteUserRequest deleteUserRequest) {
@Transactional
public void logout(HttpServletRequest request) {
String accessToken = tokenProvider.resolveToken(request);
if (accessToken == null)
throw new JwtRequestException(HttpStatus.BAD_REQUEST.value(), "BAD_REQUEST", "토큰이 비어있습니다.");

long tokenExpiration = tokenProvider.getAccessTokenExpirationTime();
redisService.setValues(accessToken, "logout", Duration.ofMillis(tokenExpiration));
log.info("success to logout");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@

import java.lang.reflect.Field;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -39,7 +37,6 @@
import com.gamzabat.algohub.common.redis.RedisService;
import com.gamzabat.algohub.enums.ImageType;
import com.gamzabat.algohub.enums.Role;
import com.gamzabat.algohub.exception.JwtRequestException;
import com.gamzabat.algohub.exception.UserValidationException;
import com.gamzabat.algohub.feature.group.studygroup.exception.CannotFoundUserException;
import com.gamzabat.algohub.feature.image.service.ImageService;
Expand Down Expand Up @@ -261,20 +258,6 @@ void logout() {
verify(redisService, times(1)).setValues(eq(token), eq("logout"), eq(Duration.ofMillis(6000L)));
}

@Test
@DisplayName("로그아웃 실패 : 비어있는 토큰")
void logoutFailed() {
// given
HttpServletRequest request = mock(HttpServletRequest.class);
when(tokenProvider.resolveToken(request)).thenReturn(null);
// when, then
assertThatThrownBy(() -> userService.logout(request))
.isInstanceOf(JwtRequestException.class)
.hasFieldOrPropertyWithValue("code", HttpStatus.BAD_REQUEST.value())
.hasFieldOrPropertyWithValue("error", "BAD_REQUEST")
.hasFieldOrPropertyWithValue("messages", new ArrayList<>(List.of("토큰이 비어있습니다.")));
}

@Test
@DisplayName("백준 닉네임 유효성 검증 : 사용 가능한 백준 닉네임")
void checkBjNickname_1() {
Expand Down

0 comments on commit 1730dce

Please sign in to comment.