Skip to content

Commit

Permalink
Merge pull request #287 from CaZaIt/feature-user
Browse files Browse the repository at this point in the history
jwt 토큰 수정사항 반영
  • Loading branch information
mjKim1229 authored Jun 21, 2023
2 parents aaa77f9 + b1ca0f8 commit 369d70a
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 45 deletions.
8 changes: 3 additions & 5 deletions src/main/java/shop/cazait/domain/auth/api/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,23 +61,21 @@ public SuccessResponse<PostLoginRes> logIn(


@NoAuth
@GetMapping(value = "/refresh/{userIdx}")
@GetMapping(value = "/refresh")
@Operation(summary = "토큰 재발급", description = "인터셉터에서 accesstoken이 만료되고 난 후 클라이언트에서 해당 api로 토큰 재발급 요청 필요")
@Parameters({
@Parameter(name = "role", description = "유저인지 마스터인지(user/master)",example = "user"),
@Parameter(name = "Authorization", description = "발급 받은 accesstoken"),
@Parameter(name = "REFRESH-TOKEN", description = "발급 받은 refreshtoken"),
@Parameter(name = "userIdx", description = "response로 발급 받은 계정 ID번호",example="1"),
})
public SuccessResponse<PostLoginRes> refreshToken(
@PathVariable(name = "userIdx") Long userIdx,
@RequestParam @NotBlank String role,
@RequestHeader(value = "Authorization") String accessToken,
@RequestHeader(value = "REFRESH-TOKEN") String refreshToken) throws UserException, BaseException, MasterException {

jwtService.isValidAccessTokenId(userIdx);
System.out.println("accessToken = " + accessToken);
Role exactRole = Role.of(role);
PostLoginRes postLoginRes = authService.reIssueTokensByRole(exactRole, accessToken, refreshToken, userIdx);
PostLoginRes postLoginRes = authService.reIssueTokensByRole(exactRole, accessToken, refreshToken);
return new SuccessResponse<>(SUCCESS, postLoginRes);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ public class AuthService {

private final UserRepository userRepository;

public PostLoginRes reIssueTokensByRole(Role exactRole, String accessToken, String refreshToken, Long userIdx) throws MasterException, UserException {
public PostLoginRes reIssueTokensByRole(Role exactRole, String accessToken, String refreshToken) throws MasterException, UserException {
if (exactRole.equals(USER)) {
return userService.reIssueTokens(accessToken, refreshToken, userIdx);
return userService.reIssueTokens(accessToken, refreshToken);
} else {
return masterService.issueAccessToken(accessToken, refreshToken);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,10 @@ public SuccessResponse<String> checkduplicateNickname(PostCheckDuplicateNickname
// return PostLoginRes.of(user,accessToken,refreshToken,USER);
// }

public PostLoginRes reIssueTokens(String accessToken,String refreshToken, Long userIdx) throws UserException{
public PostLoginRes reIssueTokens(String accessToken,String refreshToken) throws UserException{

User user = null;

Long userIdx = jwtService.getUserIdx(accessToken);
log.info("accessToken = " + accessToken);
log.info("refreshToken = " + refreshToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,21 @@
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.objenesis.strategy.BaseInstantiatorStrategy;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import shop.cazait.domain.user.exception.UserException;
import shop.cazait.global.error.exception.BaseException;

import javax.persistence.Basic;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;

Expand All @@ -27,10 +32,12 @@ public class AuthenticationInterceptor implements HandlerInterceptor {
private final JwtService jwtService;

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

System.out.println("request.pathinfo = " + request.getPathInfo());
System.out.println("request.getRequestURI() = " + request.getRequestURI());
System.out.println("request.getRequestURL() = " + request.getRequestURL());
System.out.println("request = " + request);
System.out.println("request.getServletPath() = " + request.getServletPath());
System.out.println("handler = " + handler);
// if(BasicErrorController.class == handlerMethod.getBeanType()){
// return true;
// }
Expand All @@ -42,37 +49,19 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
String accessToken = request.getHeader("Authorization");
log.info("AccessToken in interceptor prehandle = "+accessToken);

// if(jwtService.isValidToken(accessToken)){
// return true;
// }
// else {
// return false;
// }
final Map<String, String> pathVariables = (Map<String, String>) request
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
System.out.println("pathVariables = " + pathVariables);

Optional<String> masterId = Optional.ofNullable(pathVariables.get("masterId"));
Optional<String> userId = Optional.ofNullable(pathVariables.get("userId"));

if(jwtService.isValidToken(accessToken)) {
if (!masterId.isEmpty()) {
jwtService.isValidAccessTokenId(Long.valueOf(masterId.get()));
}
if (!userId.isEmpty()) {
jwtService.isValidAccessTokenId(Long.valueOf(userId.get()));
}
return true;
}
else {
return false;
}
return true;
}


private boolean checkAnnotation(Object handler,Class cls){

HandlerMethod handlerMethod=(HandlerMethod) handler;
System.out.println("handlerMethod.getBean() = " + handlerMethod.getBean());
System.out.println("handlerMethod = " + handlerMethod);
System.out.println("handlerMethod.getMethodAnnotation(cls) = " + handlerMethod.getMethodAnnotation(cls));
if(handlerMethod.getMethodAnnotation(cls)!=null){ //해당 어노테이션이 존재하면 true.
return true;
Expand Down
25 changes: 13 additions & 12 deletions src/main/java/shop/cazait/global/config/encrypt/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,20 @@ public JwtBuilder makeCommonTokenSource(Date now, Date expirationDate) {
.setIssuedAt(now)
.setExpiration(expirationDate)
.signWith(key);

}

//accessToken 발행 함수
public String createJwt(Long userIdx) {
log.info("Created token userIdx = " + userIdx);
Date now = new Date();
Date expirationDate = new Date(now.getTime() + ACCESS_TOKEN_VALID_TIME);

System.out.println("key = " + key);
return makeCommonTokenSource(now, expirationDate)
.claim("userIdx", userIdx)
.compact();
// return makeCommonTokenSource(now, expirationDate)
// .setSubject(String.valueOf(userIdx))
// .compact();
}

//refreshToken 발행 함수
Expand Down Expand Up @@ -106,17 +108,16 @@ public Jws<Claims> parseTokenWithAllException(String token) throws UserException
try {
Jws<Claims> parsedToken = parseJwt(token);
return parsedToken;
} catch (ExpiredJwtException exception) {
log.error("Token Expired UserID : " + exception.getClaims().get("userIdx"));
throw new UserException(EXPIRED_JWT);
} catch (JwtException exception) {
log.error("RefreshToken Tampered.");
throw new UserException(INVALID_JWT);
} catch (NullPointerException exception) {
} catch (NullPointerException e) {
log.error("Token is null.");
throw new UserException(EMPTY_JWT);
} catch (ExpiredJwtException e) {
log.error("Token Expired UserID : " + e.getClaims().get("userIdx"));
throw new UserException(EXPIRED_JWT);
} catch (JwtException | IllegalArgumentException e) {
log.error("Token tampered");
throw new UserException(INVALID_JWT);
}

}

public Jws<Claims> parseRefreshTokenWithAllException(String token) throws UserException {
Expand Down Expand Up @@ -148,7 +149,7 @@ public Long getUserIdx(String token) throws UserException {
} catch (ExpiredJwtException exception) {
Long userIdx = exception.getClaims().get("userIdx", Long.class);
return userIdx;
} catch (JwtException exception) {
} catch (JwtException | IllegalArgumentException exception) {
log.error("Token tampered.");
throw new UserException(INVALID_JWT);
} catch (NullPointerException exception) {
Expand Down Expand Up @@ -216,7 +217,7 @@ public boolean isValidAccessTokenInRefresh(String token) throws UserException {
} catch (ExpiredJwtException exception) {
log.error("Token Expired UserID = " + exception.getClaims().get("userIdx"));
return false;
} catch (JwtException exception) {
} catch (JwtException | IllegalArgumentException exception) {
log.error("accessToken Tampered.");
throw new UserException(INVALID_JWT);
} catch (NullPointerException exception) {
Expand Down

0 comments on commit 369d70a

Please sign in to comment.