Skip to content

Commit

Permalink
feat: JWT 로직 관련 예외처리 추가 #8
Browse files Browse the repository at this point in the history
feat: JWT 관련 예외처리 추가 #8
  • Loading branch information
PgmJun committed Jan 24, 2024
1 parent 071ef8d commit e961e29
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.nice.petudio.common.config.redis.constant.RedisKey;
import com.nice.petudio.common.exception.error.ErrorCode;
import com.nice.petudio.common.exception.model.UnAuthorizedException;
import com.nice.petudio.common.exception.model.ValidationException;
import com.nice.petudio.domain.member.Member;
import com.nice.petudio.domain.member.repository.MemberRepository;
import java.util.List;
Expand Down Expand Up @@ -35,7 +36,8 @@ public TokenVO createTokenInfo(Long memberId) {

public TokenVO reissueToken(ReissueRequest request) {
Long memberId = jwtUtils.parseMemberId(request.getAccessToken())
.orElseThrow();
.orElseThrow(() -> new ValidationException(ErrorCode.INVALID_JWT_TOKEN_EXCEPTION,
String.format("JWT AccessToken 내에 MemberId가 존재하지 않습니다.")));
Member member = MemberServiceUtils.findMemberById(memberRepository, memberId);

if (!jwtUtils.validateToken(request.getRefreshToken())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
@RestControllerAdvice
public class ExceptionControllerAdvice {

/**
* 400 Bad Request
*/
// 사용자가 요청 값 전달은 성공했지만, 해당 값이 유효하지 않은 경우 발생
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
Expand Down Expand Up @@ -76,7 +79,7 @@ protected ApiResponse<Object> handleInvalidFormatException(final Exception excep
* 401 UnAuthorized
*/
// 회원 인증에 실패했을 경우 발생
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnAuthorizedException.class)
protected ApiResponse<Object> handleUnAuthorizedException(
UnAuthorizedException exception) {
Expand All @@ -88,7 +91,7 @@ protected ApiResponse<Object> handleUnAuthorizedException(
* 403 Forbidden
*/
// 요청에 대한 권한이 존재하지 않는 경우 발생
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
protected ApiResponse<Object> handleForbiddenException(
ForbiddenException exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public boolean hasAuthority(String jwtAccessToken, List<MemberRole> requiredRole
this.memberId = memberId.get();
return isRoleMatch(member, requiredRoles);
}
throw new ValidationException(ErrorCode.INVALID_JWT_TOKEN_EXCEPTION,
String.format("JWT AccessToken 내에 MemberId가 존재하지 않습니다."));
}
throw new UnAuthorizedException(ErrorCode.UNAUTHORIZED_JWT_EXCEPTION,
ErrorCode.UNAUTHORIZED_JWT_EXCEPTION.getMessage());
Expand Down
13 changes: 10 additions & 3 deletions src/main/java/com/nice/petudio/common/auth/jwt/JwtUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.nice.petudio.common.auth.jwt.constant.JwtKey;
import com.nice.petudio.common.config.redis.constant.RedisKey;
import com.nice.petudio.common.exception.error.ErrorCode;
import com.nice.petudio.common.exception.model.UnAuthorizedException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
Expand All @@ -11,6 +13,7 @@
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.DecodingException;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import java.util.Date;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -56,7 +59,8 @@ public List<String> createTokenInfo(Long memberId) {
.compact();

redisTemplate.opsForValue()
.set(RedisKey.REFRESH_TOKEN.getKey() + memberId, refreshToken, REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);
.set(RedisKey.REFRESH_TOKEN.getKey() + memberId, refreshToken, REFRESH_TOKEN_EXPIRE_TIME,
TimeUnit.MILLISECONDS);

return List.of(accessToken, refreshToken);
}
Expand All @@ -74,8 +78,11 @@ private Claims parseClaims(String token) {
try {
return Jwts.parserBuilder().setSigningKey(secretKey).build()
.parseClaimsJws(token).getBody();
} catch (ExpiredJwtException e) {
return e.getClaims();
} catch (ExpiredJwtException exception) {
return exception.getClaims();
} catch (SignatureException exception) {
throw new UnAuthorizedException(ErrorCode.UNAUTHORIZED_JWT_EXCEPTION,
String.format("입력받은 JWT 토큰의 Signature가 잘못되었습니다. (TOKEN: %s)", token));
}
}

Expand Down

0 comments on commit e961e29

Please sign in to comment.