feat: token 수정

This commit is contained in:
박정민 2024-08-02 17:19:17 +09:00
parent 7461977156
commit 3302c8b51e
4 changed files with 38 additions and 113 deletions

View File

@ -4,6 +4,7 @@ import com.edufocus.edufocus.user.model.entity.InfoDto;
import com.edufocus.edufocus.user.model.entity.PasswordDto; import com.edufocus.edufocus.user.model.entity.PasswordDto;
import com.edufocus.edufocus.user.model.entity.User; import com.edufocus.edufocus.user.model.entity.User;
import com.edufocus.edufocus.user.model.exception.ExpriedTokenException; import com.edufocus.edufocus.user.model.exception.ExpriedTokenException;
import com.edufocus.edufocus.user.model.exception.InvalidTokenException;
import com.edufocus.edufocus.user.model.exception.RefreshTokenExpiredException; import com.edufocus.edufocus.user.model.exception.RefreshTokenExpiredException;
import com.edufocus.edufocus.user.model.exception.UnAuthorizedException; import com.edufocus.edufocus.user.model.exception.UnAuthorizedException;
import com.edufocus.edufocus.user.model.service.UserService; import com.edufocus.edufocus.user.model.service.UserService;
@ -77,7 +78,7 @@ public class UserController {
@RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user, HttpServletRequest request, HttpServletResponse response) { @RequestBody @Parameter(description = "로그인 시 필요한 회원정보(아이디, 비밀번호).", required = true) User user, HttpServletRequest request, HttpServletResponse response) {
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
if(jwtUtil.checkToken(token, false)){ if(jwtUtil.checkToken(token)){
return new ResponseEntity<>(HttpStatus.FORBIDDEN); return new ResponseEntity<>(HttpStatus.FORBIDDEN);
} }
@ -123,35 +124,6 @@ public class UserController {
return new ResponseEntity<>(resultMap, status); return new ResponseEntity<>(resultMap, status);
} }
@Operation(summary = "회원인증", description = "회원 정보를 담은 Token 을 반환한다.")
@GetMapping("/auth/{userId}")
public ResponseEntity<Map<String, Object>> getInfo(
@PathVariable("userId") @Parameter(description = "인증할 회원의 아이디.", required = true) Long userId,
HttpServletRequest request) {
String id = String.valueOf(userId);
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
if (jwtUtil.checkToken(request.getHeader("Authorization"), false)) {
log.info("사용 가능한 토큰!!!");
try {
User member = userService.userInfo(userId);
resultMap.put("userInfo", member);
status = HttpStatus.OK;
} catch (Exception e) {
log.error("정보조회 실패 : {}", e);
resultMap.put("message", e.getMessage());
status = HttpStatus.INTERNAL_SERVER_ERROR;
}
} else {
System.out.println(jwtUtil.checkToken(request.getHeader("Authorization"), false));
log.error("사용 불가능 토큰!!!");
resultMap.put("message", "Unauthorized token");
status = HttpStatus.UNAUTHORIZED;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
}
@PostMapping("/logout") @PostMapping("/logout")
public ResponseEntity<?> removeToken(HttpServletRequest request) { public ResponseEntity<?> removeToken(HttpServletRequest request) {
@ -176,14 +148,8 @@ public class UserController {
@PostMapping("/refresh") @PostMapping("/refresh")
public ResponseEntity<?> refreshToken(HttpServletRequest request,HttpServletResponse response) public ResponseEntity<?> refreshToken(HttpServletRequest request,HttpServletResponse response)
throws Exception { throws Exception {
Map<String, Object> resultMap = new HashMap<>();
HttpStatus status = HttpStatus.ACCEPTED;
Cookie[] cookies = request.getCookies(); Cookie[] cookies = request.getCookies();
String token = null; String token = null;
if (cookies != null) { if (cookies != null) {
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
if (cookie.getName().equals("refresh-token")) { if (cookie.getName().equals("refresh-token")) {
@ -192,44 +158,36 @@ public class UserController {
} }
} }
} }
try{
jwtUtil.checkToken(token);
}catch (Exception e){
throw new InvalidTokenException();
}
Long userId = Long.parseLong(jwtUtil.getUserId(token)); Long userId = Long.parseLong(jwtUtil.getUserId(token));
if(jwtUtil.isExpired(token)){
throw new RefreshTokenExpiredException(); if (!token.equals(userService.getRefreshToken(userId))) {
throw new InvalidTokenException();
} }
try { String accessToken = jwtUtil.createAccessToken(String.valueOf(userId));
if (token == null || jwtUtil.checkToken(token, true) || !token.equals(userService.getRefreshToken(userId))) { String refreshToken = jwtUtil.createRefreshToken(String.valueOf(userId));
throw new RefreshTokenExpiredException();
}
String accessToken = jwtUtil.createAccessToken(String.valueOf(userId));
String refreshToken = jwtUtil.createRefreshToken(String.valueOf(userId));
log.debug("token : {}", accessToken);
log.debug("정상적으로 access token 재발급!!!");
resultMap.put("access-token", accessToken);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("access-token", accessToken);
userService.saveRefreshToken(userId,refreshToken); userService.saveRefreshToken(userId,refreshToken);
Cookie refreshCookie = new Cookie("refresh-token", refreshToken); Cookie refreshCookie = new Cookie("refresh-token", refreshToken);
refreshCookie.setPath("/"); refreshCookie.setPath("/");
refreshCookie.setHttpOnly(true); refreshCookie.setHttpOnly(true);
refreshCookie.setSecure(true); // HTTPS에서만 전송되도록 설정 refreshCookie.setSecure(true);
// refreshCookie.setSameSite(Cookie.SameSite.NONE); // Cross-Origin 요청에 대해 모두 전송 response.addCookie(refreshCookie);
response.addCookie(refreshCookie); return new ResponseEntity<Map<String, Object>>(resultMap, HttpStatus.CREATED);
System.out.println("바뀐 리프레쉬랑 지금꺼 비교 "+ refreshToken.equals(token));
resultMap.put("access-token", accessToken);
status = HttpStatus.CREATED;
} catch (Exception e) {
log.debug("refresh token 도 사용 불가!!!!!!!");
System.out.println("refresh token 도 사용 불가!!!!!!!");
status = HttpStatus.FORBIDDEN;
}
return new ResponseEntity<Map<String, Object>>(resultMap, status);
} }
@Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.") @Operation(summary = "회원 정보 조회", description = "토큰을 이용하여 회원 정보를 조회한다.")
@ -239,7 +197,7 @@ public class UserController {
HttpStatus status = HttpStatus.ACCEPTED; HttpStatus status = HttpStatus.ACCEPTED;
String token = request.getHeader("Authorization"); String token = request.getHeader("Authorization");
if (jwtUtil.checkToken(token, false)) { if (jwtUtil.checkToken(token)) {
String userId = jwtUtil.getUserId(token); String userId = jwtUtil.getUserId(token);
log.info("사용 가능한 토큰!!! userId: {}", userId); log.info("사용 가능한 토큰!!! userId: {}", userId);
try { try {

View File

@ -24,17 +24,11 @@ public class JWTInterceptor implements HandlerInterceptor {
} }
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
throws Exception {
final String token = request.getHeader(HEADER_AUTH); final String token = request.getHeader(HEADER_AUTH);
if (token != null && jwtUtil.checkToken(token)) { jwtUtil.checkToken(token);
log.info("토큰 사용 가능 : {}", token);
return true;
} else {
log.info("토큰 사용 불가능 : {}", token);
throw new UnAuthorizedException();
}
return true;
} }
} }

View File

@ -9,23 +9,14 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
@ExceptionHandler(InvalidTokenException.class) @ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<String> handleUnAuthorizedException(InvalidTokenException e) { public ResponseEntity<String> handleInvalidTokenException(InvalidTokenException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} }
// //
@ExceptionHandler(ExpriedTokenException.class) @ExceptionHandler(ExpriedTokenException.class)
public ResponseEntity<String> handleInvalidTokenException(ExpriedTokenException e) { public ResponseEntity<String> handleExpiredTokenException(ExpriedTokenException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
} }
@ExceptionHandler(RefreshTokenExpiredException.class)
public ResponseEntity<String> handleInvalidTokenException(RefreshTokenExpiredException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
} }

View File

@ -54,40 +54,22 @@ public class JWTUtil {
} }
public boolean checkToken(String token) { public boolean checkToken(String token) {
try {
Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(generateKey())
.build()
.parseClaimsJws(token);
log.debug("claims: {}", claims);
return true;
} catch (MalformedJwtException | UnsupportedJwtException | IllegalArgumentException | SignatureException e) {
log.error("Token validation error: {}", e.getMessage());
return false;
}
catch (Exception e) {
System.out.println(token);
System.out.println(e.getMessage());
log.error("Unexpected error while validating token: {}", e.getMessage());
throw new InvalidTokenException();
}
}
public boolean isExpired(String token) {
try { try {
Jws<Claims> claims = Jwts.parserBuilder() Jws<Claims> claims = Jwts.parserBuilder()
.setSigningKey(generateKey()) .setSigningKey(generateKey())
.build() .build()
.parseClaimsJws(token); .parseClaimsJws(token);
return false; log.debug("claims: {}", claims);
}catch(ExpiredJwtException e){
return true; return true;
}catch(Exception e){ }
catch (ExpriedTokenException e) {
throw new ExpriedTokenException();
}catch (Exception e){
throw new InvalidTokenException(); throw new InvalidTokenException();
} }
} }
public String getUserId(String authorization) { public String getUserId(String authorization) {
try { try {
Jws<Claims> claims = Jwts.parserBuilder() Jws<Claims> claims = Jwts.parserBuilder()