Skip to content

Commit

Permalink
#187 Refactor: 쿠키에 samsite 보안 설정
Browse files Browse the repository at this point in the history
  • Loading branch information
betgws committed Nov 12, 2024
1 parent ae36037 commit ddb2fd4
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 20 deletions.
2 changes: 2 additions & 0 deletions src/main/java/com/drinkeg/drinkeg/jwt/JWTException.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public class JWTException {

public static void jwtExceptionHandler(HttpServletResponse response, ErrorStatus errorStatus) {

System.out.println("----------jwt exception handler---------------");

response.setStatus(errorStatus.getHttpStatus().value());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Expand Down
5 changes: 0 additions & 5 deletions src/main/java/com/drinkeg/drinkeg/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

System.out.println("cookie = " + cookie.getName() + "= " + cookie.getValue());
if (cookie.getName().equals("accessToken")) {

accessToken = cookie.getValue();
}
}
Expand All @@ -60,7 +59,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if (accessToken == null) {
filterChain.doFilter(request, response);
//조건이 해당되면 메소드 종료 (필수)
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return ;
}

Expand All @@ -69,15 +67,13 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

System.out.println("token expired");
filterChain.doFilter(request, response);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//조건이 해당되면 메소드 종료 (필수)
return;
}

//토큰이 access 토큰인지 확인
String category = jwtUtil.getCategory(accessToken);
if(!category.equals("access")){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}

Expand All @@ -100,7 +96,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
//스프링 시큐리티 인증 토큰 생성
Authentication authToken = new UsernamePasswordAuthenticationToken(principalDetail, null, principalDetail.getAuthorities());

//세션에 사용자 등록
SecurityContextHolder.getContext().setAuthentication(authToken);
filterChain.doFilter(request, response);
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/com/drinkeg/drinkeg/jwt/LoginFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public class LoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {


// 클라이언트 요청에서 username, password 추출
ObjectMapper objectMapper = new ObjectMapper();
Map<String, String> requestBody;
Expand Down Expand Up @@ -88,8 +89,8 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR


// 토큰을 쿠키에 저장하여 응답 (access 의 경우 추후 프론트와 협의하여 헤더에 넣어서 반환할 예정)
response.addCookie(tokenService.createCookie("accessToken", accessToken));
response.addCookie(tokenService.createCookie("refreshToken", refreshToken));
tokenService.createCookie(response, "accessToken", accessToken); // Access Token 쿠키 추가
tokenService.createCookie(response, "refreshToken", refreshToken); // refresh token 쿠키 추가
response.setStatus(HttpStatus.OK.value());

// redis에 refresh 토큰 저장
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo


// 토큰을 쿠키에 저장하여 응답 (access 의 경우 추후 프론트와 협의하여 헤더에 넣어서 반환할 예정)
response.addCookie(tokenService.createCookie("accessToken", accessToken));
response.addCookie(tokenService.createCookie("refreshToken", refreshToken));
tokenService.createCookie(response, "accessToken", accessToken); // Access Token 쿠키 추가
tokenService.createCookie(response, "refreshToken", refreshToken); // refresh token 쿠키 추가
response.setStatus(HttpStatus.OK.value());

// redis에 refresh 토큰 저장
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ public void jwtProvider(Member member, HttpServletResponse response) {
String refreshToken = jwtUtil.createJwt("refresh",member.getUsername(), member.getRole(),864000000L);

// 토큰을 쿠키에 저장하여 응답
response.addCookie(tokenService.createCookie("accessToken", accessToken));
response.addCookie(tokenService.createCookie("refreshToken", refreshToken));
tokenService.createCookie(response, "accessToken", accessToken); // Access Token 쿠키 추가
tokenService.createCookie(response, "refreshToken", refreshToken); // refresh token 쿠키 추가
response.setStatus(HttpStatus.OK.value());

// redis에 refresh 토큰 저장
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

Expand All @@ -29,17 +30,20 @@ public class TokenService {
private final JWTUtil jwtUtil;
private final RedisClient redisClient;

public Cookie createCookie(String key, String value) {
public void createCookie(HttpServletResponse response, String key, String value) {

Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(24*60*60);
//cookie.setSecure(true); //https를 사용할 경우
cookie.setPath("/"); // 쿠키가 적용될 경로
cookie.setHttpOnly(true);
ResponseCookie cookie = ResponseCookie.from(key, value)
.httpOnly(true)
.secure(true) // HTTPS만 허용
.path("/")
.sameSite("Strict") // SameSite 설정
.maxAge(24 * 60 * 60) // 1일
.build();
response.addHeader("Set-Cookie", cookie.toString());

return cookie;
}


public void reissueRefreshToken(HttpServletRequest request, HttpServletResponse response) {

//get refresh token
Expand Down Expand Up @@ -99,8 +103,8 @@ public void reissueRefreshToken(HttpServletRequest request, HttpServletResponse
redisClient.setValue(username, newRefresh, 864000000L);

//response
response.addCookie(createCookie("accessToken", newAccess));
response.addCookie(createCookie("refreshToken", newRefresh));
createCookie(response, "accessToken", newAccess); // Access Token 쿠키 추가
createCookie(response, "refreshToken", newRefresh); // refresh token 쿠키 추가
response.setStatus(HttpStatus.OK.value());
}

Expand Down

0 comments on commit ddb2fd4

Please sign in to comment.