Skip to content

Commit

Permalink
Merge pull request #64 from H-Hive/feature/user
Browse files Browse the repository at this point in the history
Refactor: token과 유저 정보를 쿠키에 담아 반환하도록 수정
  • Loading branch information
wkdehdgk159 authored Jan 16, 2024
2 parents b541af1 + e7cfcc1 commit b4b9440
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import com.HHive.hhive.domain.user.entity.User;
import com.HHive.hhive.domain.user.service.UserService;
import com.HHive.hhive.global.common.CommonResponse;
import com.HHive.hhive.global.exception.common.CustomException;
import com.HHive.hhive.global.jwt.JwtUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -38,8 +38,11 @@ public ResponseEntity<CommonResponse<UserInfoResponseDTO>> login(

UserInfoResponseDTO userInfo = userService.login(requestDTO);

String token = jwtUtil.createToken(requestDTO.getUsername());
response.setHeader(JwtUtil.AUTHORIZATION_HEADER, token);
Cookie tokenCookie = jwtUtil.createTokenCookie(requestDTO.getUsername());
Cookie userInfoCookie = jwtUtil.createUserInfoCookie(userInfo);

response.addCookie(tokenCookie);
response.addCookie(userInfoCookie);

return ResponseEntity.ok()
.body(CommonResponse.of(HttpStatus.OK.value(), "로그인 성공", userInfo));
Expand Down
64 changes: 62 additions & 2 deletions src/main/java/com/HHive/hhive/global/jwt/JwtUtil.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.HHive.hhive.global.jwt;

import com.HHive.hhive.domain.user.dto.UserInfoResponseDTO;
import com.HHive.hhive.global.exception.jwt.ExpiredJwtTokenException;
import com.HHive.hhive.global.exception.jwt.InvalidJwtSignatureException;
import com.HHive.hhive.global.exception.jwt.InvalidJwtTokenException;
import com.HHive.hhive.global.exception.jwt.UnsupportedJwtTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
Expand All @@ -13,8 +16,10 @@
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -30,7 +35,14 @@ public class JwtUtil {
public static final String AUTHORIZATION_HEADER = "Authorization";

// Token 식별자
public static final String BEARER_PREFIX = "Bearer ";
public static final String BEARER_PREFIX = "Bearer%";

// 쿠키 이름
public static final String USER_INFO_COOKIE_NAME = "userinfo";

public static final String JWT_COOKIE_NAME = "token";

private final ObjectMapper objectMapper = new ObjectMapper();

@Value("${jwt.secret.key}") // Base64 Encode 한 SecretKey
private String secretKey;
Expand All @@ -46,10 +58,23 @@ public void init() {
}

public String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);

Cookie[] cookies = request.getCookies();

if (cookies == null) {
return null;
}

String bearerToken = Arrays.stream(cookies)
.filter(cookie -> cookie.getName().equals(JWT_COOKIE_NAME))
.findFirst()
.map(Cookie::getValue)
.orElse(null);

if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
return bearerToken.substring(7);
}

return null;
}

Expand All @@ -72,6 +97,41 @@ public Claims getUserInfoFromToken(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
}

public Cookie createTokenCookie(String username) {

long EXPIRED_TIME = 60 * 60;

String jwtToken = createToken(username);

Cookie cookie = new Cookie(JWT_COOKIE_NAME, jwtToken);
cookie.setPath("/api");
cookie.setMaxAge((int) EXPIRED_TIME);
cookie.setHttpOnly(true);

return cookie;
}

public Cookie createUserInfoCookie(UserInfoResponseDTO responseDTO) {

long EXPIRED_TIME = 60 * 60;

String responseToString = null;

try {
responseToString = objectMapper.writeValueAsString(responseDTO);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}

String encodedUserInfo = Base64.getEncoder().encodeToString(responseToString.getBytes());

Cookie cookie = new Cookie(USER_INFO_COOKIE_NAME, encodedUserInfo);
cookie.setPath("/");
cookie.setMaxAge((int) EXPIRED_TIME);

return cookie;
}

public String createToken(String username) {
Date date = new Date();

Expand Down

0 comments on commit b4b9440

Please sign in to comment.