Skip to content

Commit

Permalink
Merge pull request #204 from prgrms-web-devcourse-final-project/develop
Browse files Browse the repository at this point in the history
배포2
  • Loading branch information
Dom1046 authored Dec 6, 2024
2 parents 8615021 + c6c0e73 commit db1e90d
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 106 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -191,18 +191,18 @@ public ResponseEntity<?> login(HttpServletResponse response,
AccessPayloadMap.put("category", TokenCategory.ACCESS_TOKEN.name());
String accessToken = jwtUtil.createAccessToken(AccessPayloadMap, accessTokenValidity);

//리프레시 토큰 생성 ( 난수를 입력, 의미없는 토큰 생성 )
Map<String, Object> refreshPayloadMap = new HashMap<>();
refreshPayloadMap.put("userId", userId);

//식별 위한 UserID 입력
String randomUUID = UUID.randomUUID().toString();
refreshPayloadMap.put("randomUUID", randomUUID);
String refreshToken = jwtUtil.createRefreshToken(refreshPayloadMap, accessRefreshTokenValidity);
log.info("컨트롤러 로그인, 토큰만듬: {}, refresh: {}", accessToken, refreshToken);

//리프레시 토큰 레디스에 저장하기
refreshTokenService.insertInRedis(refreshPayloadMap, refreshToken);
// //리프레시 토큰 생성 ( 난수를 입력, 의미없는 토큰 생성 )
// Map<String, Object> refreshPayloadMap = new HashMap<>();
// refreshPayloadMap.put("userId", userId);
//
// //식별 위한 UserID 입력
// String randomUUID = UUID.randomUUID().toString();
// refreshPayloadMap.put("randomUUID", randomUUID);
// String refreshToken = jwtUtil.createRefreshToken(refreshPayloadMap, accessRefreshTokenValidity);
// log.info("컨트롤러 로그인, 토큰만듬: {}, refresh: {}", accessToken, refreshToken);
//
// //리프레시 토큰 레디스에 저장하기
// refreshTokenService.insertInRedis(refreshPayloadMap, refreshToken);

//로그인 시간 저장
Member foundMember = memberRepository.findByUserId(new UserId(userId))
Expand All @@ -226,8 +226,8 @@ public ResponseEntity<?> login(HttpServletResponse response,

// 응답 반환
return ResponseEntity.ok(Map.of(
"AccessToken", accessToken,
"RefreshToken", refreshToken
"AccessToken", accessToken
// "RefreshToken", refreshToken
));
} catch (AuthenticationException ex) {
// 인증 실패 시 401 반환
Expand All @@ -244,59 +244,62 @@ public ResponseEntity<?> login(HttpServletResponse response,
})
public ResponseEntity<?> loginOut(HttpServletRequest request, HttpServletResponse response) {
log.info("커스텀 로그아웃 실행");

// Refresh Token 없다면 오류
String refreshTokenFromCookies = getRefreshTokenFromCookies(request);
log.info("refreshTokenFromCookies : {}", refreshTokenFromCookies);
if (refreshTokenFromCookies == null || refreshTokenFromCookies.trim().isEmpty()) {
log.warn("No refresh token found");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "Refresh token is missing"));
}

// Access Token 없다면 오류
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
log.warn("No access token found");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "Access token is missing"));
}

String accessToken = authorizationHeader.substring(7);
// 블랙리스트 등록
try {
if (!jwtUtil.isExpired(accessToken)) {
if (!jwtUtil.isExpired(refreshTokenFromCookies)) {
accessTokenBlackList.registerBlackList(accessToken, refreshTokenFromCookies);
log.info("Tokens are registered to BlackList");
} else {
log.info("RefreshToken is expired");
}
} else {
log.info("AccessToken is expired");

}
// 리프레시 토큰 삭제
Map<String, Object> payloadMap = jwtUtil.validateRefreshToken(refreshTokenFromCookies);
refreshTokenService.deleteRefreshTokenInRedis(payloadMap);

} catch (Exception e) {
log.error("토큰 블랙리스트 처리에 실패하였습니다 : {}", e.getMessage());
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Token processing failed"));
}

// 쿠키 비우기
Cookie cookie = new Cookie("refreshToken", null);
// cookie.setSecure(true); // HTTPS 환경에서만 전송
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setMaxAge(0);
response.addCookie(cookie);

response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");

//
// // Refresh Token 없다면 오류
// String refreshTokenFromCookies = getRefreshTokenFromCookies(request);
// log.info("refreshTokenFromCookies : {}", refreshTokenFromCookies);
// if (refreshTokenFromCookies == null || refreshTokenFromCookies.trim().isEmpty()) {
// log.warn("No refresh token found");
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
// .body(Map.of("error", "Refresh token is missing"));
// }
//
// // Access Token 없다면 오류
// String authorizationHeader = request.getHeader("Authorization");
// if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
// log.warn("No access token found");
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
// .body(Map.of("error", "Access token is missing"));
// }
//
// String accessToken = authorizationHeader.substring(7);
// // 블랙리스트 등록
// try {
// if (!jwtUtil.isExpired(accessToken)) {
// if (!jwtUtil.isExpired(refreshTokenFromCookies)) {
// accessTokenBlackList.registerBlackList(accessToken, refreshTokenFromCookies);
// log.info("Tokens are registered to BlackList");
// } else {
// log.info("RefreshToken is expired");
// }
// } else {
// log.info("AccessToken is expired");
//
// }
// // 리프레시 토큰 삭제
// Map<String, Object> payloadMap = jwtUtil.validateRefreshToken(refreshTokenFromCookies);
// refreshTokenService.deleteRefreshTokenInRedis(payloadMap);
//
// } catch (Exception e) {
// log.error("토큰 블랙리스트 처리에 실패하였습니다 : {}", e.getMessage());
// ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
// .body(Map.of("error", "Token processing failed"));
// }
//
// // 쿠키 비우기
// Cookie cookie = new Cookie("refreshToken", null);
//// cookie.setSecure(true); // HTTPS 환경에서만 전송
// cookie.setPath("/");
// cookie.setHttpOnly(true);
// cookie.setMaxAge(0);
// response.addCookie(cookie);
//
//
// response.addHeader("accessToken",null);
// response.setStatus(HttpServletResponse.SC_OK);
// response.setContentType("application/json");

response.setHeader("accessToken", null);
return ResponseEntity.status(HttpStatus.CREATED).body("message : 로그아웃 성공");
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/mallangs/global/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ public enum ErrorCode {

//Token
FAILED_TO_CHECK_TOKENS(UNAUTHORIZED, "토큰이 존재하지 않습니다."),
REFRESH_TOKEN_EXPIRED(NOT_FOUND, "리프레시 토큰이 만료되었습니다."),
REFRESH_TOKEN_EXPIRED(UNAUTHORIZED, "리프레시 토큰이 만료되었습니다."),
TOKEN_EXPIRED(UNAUTHORIZED, "토큰이 만료되었습니다."),
TOKEN_IS_BLOCKED(UNAUTHORIZED, "토큰이 차단되었습니다."),
REFRESH_TOKEN_MISSING(NOT_FOUND, "리프레시 토큰이 존재하지 않습니다.");

Expand Down
77 changes: 39 additions & 38 deletions src/main/java/com/mallangs/global/jwt/filter/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,46 +135,47 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
String accessToken = authorizationHeader.substring(7);
Map<String, Object> claims = jwtUtil.validateToken(accessToken);

//블랙리스트에 있는지 확인
if (accessTokenBlackList.checkBlackList(accessToken)) {
handleException(response, new Exception("ACCESS TOKEN IS BLOCKED"));
return;
}
// //블랙리스트에 있는지 확인
// if (accessTokenBlackList.checkBlackList(accessToken)) {
// handleException(response, new Exception("ACCESS TOKEN IS BLOCKED"));
// return;
// }
//Access Token 만료 확인
if (jwtUtil.isExpired(accessToken)) {
String refreshTokenFromCookies = getRefreshTokenFromCookies(request);

if (refreshTokenFromCookies != null) {
try {
Map<String, Object> RefreshPayloadMap = jwtUtil.validateRefreshToken(
refreshTokenFromCookies);
String refreshTokenInRedis = refreshTokenService.readRefreshTokenInRedis(
RefreshPayloadMap);

if ((refreshTokenFromCookies.equals(refreshTokenInRedis)
&& (!jwtUtil.isExpired(refreshTokenFromCookies)))) {

//userId로 맴버 찾기
Member foundMember = memberRepository.findByUserId(new UserId((String) RefreshPayloadMap.get("userId")))
.orElseThrow(() -> new MallangsCustomException(ErrorCode.MEMBER_NOT_FOUND));

//SecurityContextHolder 에 회원 등록
CustomMemberDetails customUserDetails = new CustomMemberDetails(foundMember);
Authentication authToken = new UsernamePasswordAuthenticationToken(
customUserDetails, null, customUserDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);

filterChain.doFilter(request, response);
} else {
handleException(response, new Exception("INVALID REFRESH TOKEN"));
}
} catch (Exception e) {
handleException(response, new Exception("REFRESH TOKEN VALIDATION FAILED"));
}
} else {
handleException(response, new Exception("REFRESH TOKEN NOT FOUND"));
}
filterChain.doFilter(request, response);
throw new MallangsCustomException(ErrorCode.TOKEN_EXPIRED);
// String refreshTokenFromCookies = getRefreshTokenFromCookies(request);

// if (refreshTokenFromCookies != null) {
// try {
// Map<String, Object> RefreshPayloadMap = jwtUtil.validateRefreshToken(
// refreshTokenFromCookies);
// String refreshTokenInRedis = refreshTokenService.readRefreshTokenInRedis(
// RefreshPayloadMap);
//
// if ((refreshTokenFromCookies.equals(refreshTokenInRedis)
// && (!jwtUtil.isExpired(refreshTokenFromCookies)))) {
//
// //userId로 맴버 찾기
// Member foundMember = memberRepository.findByUserId(new UserId((String) RefreshPayloadMap.get("userId")))
// .orElseThrow(() -> new MallangsCustomException(ErrorCode.MEMBER_NOT_FOUND));
//
// //SecurityContextHolder 에 회원 등록
// CustomMemberDetails customUserDetails = new CustomMemberDetails(foundMember);
// Authentication authToken = new UsernamePasswordAuthenticationToken(
// customUserDetails, null, customUserDetails.getAuthorities());
// SecurityContextHolder.getContext().setAuthentication(authToken);
//
// filterChain.doFilter(request, response);
// } else {
// handleException(response, new Exception("INVALID REFRESH TOKEN"));
// }
// } catch (Exception e) {
// handleException(response, new Exception("REFRESH TOKEN VALIDATION FAILED"));
// }
// } else {
// handleException(response, new Exception("REFRESH TOKEN NOT FOUND"));
// }
// filterChain.doFilter(request, response);
} else {
log.info("Claims: {}", claims);
if (claims.get("category") == null || !(claims.get("category")).equals(
Expand Down

0 comments on commit db1e90d

Please sign in to comment.