Skip to content

인터셉터에서 request jwt를 활용하도록 수정 #95

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 5 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
58 changes: 58 additions & 0 deletions be/src/main/java/yeonba/be/config/AuthInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package yeonba.be.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yeonba.be.exception.GeneralException;
import yeonba.be.exception.UtilException;
import yeonba.be.user.entity.User;
import yeonba.be.user.repository.user.UserQuery;
import yeonba.be.util.JwtUtil;

@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

private final UserQuery userQuery;
private final JwtUtil jwtUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

if (request.getMethod().equals("OPTIONS")) {
return true;
}

String header = request.getHeader("Authorization");
if (header == null) {
throw new GeneralException(UtilException.NOT_FOUND_AUTHORIZATION_HEADER);
}

Pattern pattern = Pattern.compile("^Bearer\\s(.+)$");
Matcher matcher = pattern.matcher(header);
if (!matcher.matches()) {
throw new GeneralException(UtilException.INVALID_AUTHORIZATION_FORMAT);
}

String token = matcher.group(1);



Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

토큰을 추출하고 검증하는 과정은 한 흐름으로 보아 구분을 위한 줄바꿈이 따로 필요 없다고 생각하는데 따로 세 번의 줄바꿈을 두신 이유가 있을까요?

if (!jwtUtil.validateTokenIsExpired(token)) {
throw new GeneralException(UtilException.INVALID_JWT);
}

if (!jwtUtil.validateTokenIsManipulated(token)) {
throw new GeneralException(UtilException.INVALID_JWT);
}

long userId = jwtUtil.getUserIdFromJwt(token);
request.setAttribute("userId", userId);

return true;
}
}
26 changes: 0 additions & 26 deletions be/src/main/java/yeonba/be/config/DevAuthInterceptor.java

This file was deleted.

2 changes: 1 addition & 1 deletion be/src/main/java/yeonba/be/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private final DevAuthInterceptor devAuthInterceptor;
private final AuthInterceptor devAuthInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
Expand Down
8 changes: 8 additions & 0 deletions be/src/main/java/yeonba/be/exception/UtilException.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
@AllArgsConstructor
public enum UtilException implements BaseException {

INVALID_AUTHORIZATION_FORMAT(
HttpStatus.BAD_REQUEST,
"Authorization 헤더가 올바른 형식이 아닙니다."),

NOT_FOUND_AUTHORIZATION_HEADER(
HttpStatus.BAD_REQUEST,
"Authorization 헤더가 존재하지 않습니다."),

INVALID_JWT(
HttpStatus.BAD_REQUEST,
"유효하지 않은 JWT입니다. 다시 로그인 해주세요."),
Expand Down
2 changes: 1 addition & 1 deletion be/src/main/java/yeonba/be/login/service/LoginService.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ private void validateLoginInfo(User user, long socialId, LoginType loginType) {
@Transactional
public UserRefrehJwtResponse refreshJwt(UserRefreshJwtRequest request) {

long userId = jwtUtil.getUserIdFromToken(request.getRefreshToken());
long userId = jwtUtil.getUserIdFromJwt(request.getRefreshToken());

User user = userQuery.findById(userId);
user.validateRefreshToken(request.getRefreshToken());
Expand Down
37 changes: 36 additions & 1 deletion be/src/main/java/yeonba/be/util/JwtUtil.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package yeonba.be.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.Key;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.Date;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import yeonba.be.user.entity.User;
Expand Down Expand Up @@ -33,7 +39,7 @@ public String generateRefreshToken(User user, Date generatedAt) {
return generateUserJwt(user, generatedAt, expiredAt);
}

public long getUserIdFromToken(String token) {
public long getUserIdFromJwt(String token) {

Object userIdObject = Jwts.parser()
.setSigningKey(jwtSecret)
Expand Down Expand Up @@ -68,4 +74,33 @@ private String generateUserJwt(User user, Date issuedAt, Date generatedAt) {
.signWith(SignatureAlgorithm.HS256, jwtSecret)
.compact();
}

public boolean validateTokenIsExpired(String token) {

try {
Jws<Claims> claimsJws = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token);

return !claimsJws.getBody().getExpiration().before(new Date());
} catch (Exception e) {
return false;
}
}

public boolean validateTokenIsManipulated(String token) {

try {
byte[] decodedSecretKey = Base64.getDecoder().decode(jwtSecret);
Key key = new SecretKeySpec(decodedSecretKey, 0, decodedSecretKey.length, "HmacSHA256");

Jwts.parser()
.setSigningKey(key) // 비밀 키를 사용하여 서명을 검증
.parseClaimsJws(token);

return true;
} catch (JwtException e) {
return false;
}
}
}
Loading