Skip to content

Commit

Permalink
Merge pull request #29 from LearnMate-Dev/feature/28-update-token-res…
Browse files Browse the repository at this point in the history
…ponse

[✨ FEATURE] Update Token Response
  • Loading branch information
L-U-Ready authored Dec 3, 2024
2 parents 19d34e9 + eaf07ec commit e1b2a44
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
Expand All @@ -29,15 +28,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpSession session = request.getSession(false);
String accessToken = null;

if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if ("accessToken".equals(cookie.getName())) {
accessToken = cookie.getValue();
}
}
}
String accessToken = extractAccessTokenFromHeader(request);

if (accessToken != null) {
String tokenStatus = jwtProvider.validateToken(accessToken);
Expand All @@ -52,7 +43,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
String refreshToken = (String) session.getAttribute("refreshToken");

if (refreshToken != null) {
// Account 조회 및 refreshAccessToken 호출
Long userId = jwtProvider.getUserId(refreshToken);
User user = userService.findUserById(userId);
Authentication authentication = jwtProvider.refreshAccessToken(refreshToken, response, user);
Expand All @@ -70,4 +60,16 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
filterChain.doFilter(request, response);
}

/**
* 헤더에서 AccessToken 추출
* @param request HttpServletRequest
* @return AccessToken (없으면 null)
*/
private String extractAccessTokenFromHeader(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7); // "Bearer " 이후의 토큰 값만 추출
}
return null;
}
}
48 changes: 19 additions & 29 deletions src/main/java/LearnMate/dev/security/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.security.Key;
Expand All @@ -29,7 +27,6 @@ public class JwtProvider {
private final Long ACCESS_TOKEN_EXPIRE_TIME;
private final Long REFRESH_TOKEN_EXPIRE_TIME;


public JwtProvider(@Value("${jwt.secret_key}") String secretKey,
@Value("${jwt.access_token_expire}") Long accessTokenExpire,
@Value("${jwt.refresh_token_expire}") Long refreshTokenExpire) {
Expand All @@ -39,6 +36,7 @@ public JwtProvider(@Value("${jwt.secret_key}") String secretKey,
this.REFRESH_TOKEN_EXPIRE_TIME = refreshTokenExpire;
}

// AccessToken 생성
public String generateAccessToken(User user) {
Date expiredAt = new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRE_TIME);
return Jwts.builder()
Expand All @@ -49,6 +47,7 @@ public String generateAccessToken(User user) {
.compact();
}

// RefreshToken 생성
public String generateRefreshToken(User user) {
Date expiredAt = new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRE_TIME);
return Jwts.builder()
Expand All @@ -59,25 +58,12 @@ public String generateRefreshToken(User user) {
.compact();
}

public Long getUserId(String token) {
Claims claims = getClaimsFromToken(token);
return claims.get("user_id", Long.class);
}

public void setAccessTokenInCookie(User user, String accessToken, HttpServletResponse response) {
// accessToken을 쿠키에 설정
Cookie accessTokenCookie = new Cookie("accessToken", accessToken);
accessTokenCookie.setHttpOnly(true); // 클라이언트 측 접근 방지
accessTokenCookie.setSecure(false); // HTTPS에서만 전송
accessTokenCookie.setPath("/"); // 전체 경로에서 접근 가능
response.addCookie(accessTokenCookie); // 쿠키 설정 추가
}

public void storeRefreshTokenInSession(User user, HttpSession session) {
String refreshToken = generateRefreshToken(user);
session.setAttribute("refreshToken", refreshToken);
}

// Token 검증
public String validateToken(String token) {
try {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
Expand All @@ -89,6 +75,7 @@ public String validateToken(String token) {
}
}

// Token에서 Claims 추출
public Claims getClaimsFromToken(String token) {
try {
return Jwts.parserBuilder()
Expand All @@ -101,28 +88,31 @@ public Claims getClaimsFromToken(String token) {
}
}

public Authentication getAuthenticationFromToken(String token) {
// Token에서 User ID 추출
public Long getUserId(String token) {
Claims claims = getClaimsFromToken(token);
Long userId = claims.get("user_id", Long.class);
String email = claims.get("email", String.class);

CustomUserDetails userDetails = new CustomUserDetails(userId, email, new ArrayList<>());
return new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
return claims.get("user_id", Long.class);
}


// AccessToken 갱신
public Authentication refreshAccessToken(String refreshToken, HttpServletResponse response, User user) {

if ("VALID".equals(validateToken(refreshToken))) {

// 새 accessToken 생성
// 새 AccessToken 생성
String newAccessToken = generateAccessToken(user);
setAccessTokenInCookie(user, newAccessToken, response);

// 인증 객체 생성 및 반환
// 인증 객체 생성 및 반환
return getAuthenticationFromToken(newAccessToken);
}
return null;
}

// Token에서 Authentication 객체 생성
public Authentication getAuthenticationFromToken(String token) {
Claims claims = getClaimsFromToken(token);
Long userId = claims.get("user_id", Long.class);
String email = claims.get("email", String.class);

CustomUserDetails userDetails = new CustomUserDetails(userId, email, new ArrayList<>());
return new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
}
}
3 changes: 1 addition & 2 deletions src/main/java/LearnMate/dev/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ public String signIn(UserSignInRequest request, HttpServletResponse response, Ht

// AccessToken 발급 및 응답 헤더에 추가
String accessToken = jwtProvider.generateAccessToken(user);
jwtProvider.setAccessTokenInCookie(user, accessToken, response);

// RefreshToken 발급 및 세션에 저장
jwtProvider.storeRefreshTokenInSession(user, session);

return "로그인 성공";
return "accessToken: " + accessToken;

}

Expand Down

0 comments on commit e1b2a44

Please sign in to comment.