Skip to content

Commit

Permalink
Merge pull request #54 from dnd-side-project/feature/#45
Browse files Browse the repository at this point in the history
refresh token 쿠키 배포 에러
  • Loading branch information
strangehoon authored Apr 19, 2024
2 parents e6114c3 + 03aab69 commit a80ec39
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.*;

Expand All @@ -24,46 +25,47 @@ public class AuthController {
private final GoogleService googleService;
private final AuthService authService;
private final static String REFRESH_TOKEN = "refreshToken";

@Value("${jwt.refresh-token-cookie-name}")
private String COOKIE_NAME;
@GetMapping("/kakao/callback")
public ApiResponse<TokensResponseDto> loginKakao(@RequestParam String code, HttpServletResponse response) throws JsonProcessingException {
Token tokens = kakaoService.loginKakao(code);
ResponseCookie cookie = ResponseCookie.from(REFRESH_TOKEN, tokens.refreshToken())
.maxAge(60*60*24*7)
.maxAge(604800)
.path("/")
.secure(true)
.sameSite("None")
.domain(".sendback.co.kr")
.httpOnly(true)
.build();
response.setHeader("set-cookie", cookie.toString());
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return ApiResponse.success(new TokensResponseDto(tokens.accessToken()));
}

@GetMapping("/google/callback")
public ApiResponse<TokensResponseDto> loginGoogle(@RequestParam String code, HttpServletResponse response) throws JsonProcessingException {
Token tokens = googleService.loginGoogle(code);
ResponseCookie cookie = ResponseCookie.from(REFRESH_TOKEN, tokens.refreshToken())
.maxAge(60*60*24*7)
.maxAge(604800)
.path("/")
.secure(true)
.sameSite("None")
.domain(".sendback.co.kr")
.httpOnly(true)
.build();
response.setHeader("set-cookie", cookie.toString());
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return ApiResponse.success(new TokensResponseDto(tokens.accessToken()));
}

@PostMapping("/reissue")
public ApiResponse<TokensResponseDto> reissueToken(@RequestBody RefreshTokenRequestDto refreshTokenDto, HttpServletResponse response){
Token tokens = authService.reissueToken(refreshTokenDto.refreshToken());
ResponseCookie cookie = ResponseCookie.from(REFRESH_TOKEN, tokens.refreshToken())
.maxAge(60*60*24*7)
.maxAge(604800)
.path("/")
.secure(true)
.sameSite("None")
.domain(".sendback.co.kr")
.httpOnly(true)
.build();
response.setHeader("set-cookie", cookie.toString());
response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return ApiResponse.success(new TokensResponseDto(tokens.accessToken()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public ApiResponse<TokensResponseDto> signUpUser(@RequestBody @Valid SignUpReque
.maxAge(60*60*24*7)
.path("/")
.secure(true)
.sameSite("None")
.domain(".sendback.co.kr")
.httpOnly(true)
.build();
response.setHeader("set-cookie", cookie.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,62 +3,64 @@
import com.sendback.domain.auth.dto.Token;
import com.sendback.domain.auth.dto.request.RefreshTokenRequestDto;
import com.sendback.domain.auth.dto.response.SignTokenResponseDto;
import com.sendback.domain.auth.dto.response.TokensResponseDto;
import com.sendback.global.ControllerTest;
import com.sendback.global.WithMockCustomUser;
import static org.hamcrest.Matchers.containsString;
import com.sendback.global.exception.type.SignInException;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static com.sendback.domain.auth.exception.AuthExceptionType.NEED_TO_SIGNUP;
import static org.mockito.BDDMockito.given;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.headers.HeaderDocumentation;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.test.web.servlet.ResultActions;

import static org.mockito.Mockito.verify;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class AuthControllerTest extends ControllerTest {


@Nested
@DisplayName("카카오 로그인")
@DisplayName("카카오 로그인 api")
class loginKakao {

@Test
@DisplayName("카카오 로그인을 성공하면(기존 회원) 200 상태코드와 함께 access token, refresh token을 반환한다.")
@WithMockCustomUser
@Disabled
void loginKakao_success() throws Exception {


// given
String code = "valid code";
String accessToken = "valid accessToken";
String refreshToken = "valid refreshToken";
String accessToken = "validAccessToken";
String refreshToken = "validRefreshToken";
given(kakaoService.loginKakao(code)).willReturn(
new Token(accessToken, refreshToken)
);

// when &then
mockMvc.perform(
get("/api/auth/kakao/callback").param("code", code))
// when
ResultActions resultActions = mockMvc.perform(
get("/api/auth/kakao/callback")
.param("code", code))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("200"))
.andExpect(jsonPath("$.message").value("성공"))
.andExpect(jsonPath("$.data.accessToken").value(accessToken))
.andExpect(jsonPath("$.data.refreshToken").value(refreshToken))
.andDo(document("login-kakao-success",
.andExpect(header().string("Set-Cookie", containsString("refreshToken="+refreshToken)));

// then
resultActions.andDo(document("login-kakao-success",
customRequestPreprocessor(),
preprocessResponse(prettyPrint()),
queryParameters(
Expand All @@ -71,11 +73,13 @@ void loginKakao_success() throws Exception {
.description("응답 데이터"),
fieldWithPath("data.accessToken").type(JsonFieldType.STRING)
.description("access 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING)
.description("refresh 토큰"),
fieldWithPath("message").type(JsonFieldType.STRING)
.description("메시지")
)));
),
responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.SET_COOKIE)
.description("refreshToken"))

));

verify(kakaoService).loginKakao(code);
}
Expand All @@ -90,14 +94,16 @@ void loginKakao_fail1() throws Exception {
given(kakaoService.loginKakao(code))
.willThrow(new SignInException(NEED_TO_SIGNUP, new SignTokenResponseDto("test_sign_token")));

// when &then
mockMvc.perform(
// when
ResultActions resultActions = mockMvc.perform(
get("/api/auth/kakao/callback").param("code", code))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value("1080"))
.andExpect(jsonPath("$.message").value("추가 정보를 입력하세요."))
.andExpect(jsonPath("$.data.signToken").value("test_sign_token"))
.andDo(document("login-kakao-failure",
.andExpect(jsonPath("$.data.signToken").value("test_sign_token"));

// then
resultActions.andDo(document("login-kakao-failure",
customRequestPreprocessor(),
preprocessResponse(prettyPrint()),
queryParameters(
Expand All @@ -120,7 +126,6 @@ void loginKakao_fail1() throws Exception {

@Nested
@DisplayName("구글 로그인")
@Disabled
class loginGoogle {

@Test
Expand All @@ -129,23 +134,24 @@ class loginGoogle {
void loginGoogle_success() throws Exception {

// given
String code = "123456";
String accessToken = "abcdefg";
String refreshToken = "qwerstu";
String code = "valid code";
String accessToken = "validAccessToken";
String refreshToken = "validRefreshToken";
given(googleService.loginGoogle(code)).willReturn(
new Token(accessToken, refreshToken)
);

// when &then
mockMvc.perform(
// when
ResultActions resultActions = mockMvc.perform(
get("/api/auth/google/callback").param("code", code))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("200"))
.andExpect(jsonPath("$.message").value("성공"))
.andExpect(jsonPath("$.data.accessToken").value(accessToken))
.andExpect(jsonPath("$.data.refreshToken").value(refreshToken))
.andDo(print())
.andDo(document("login-google-success",
.andExpect(header().string("Set-Cookie", containsString("refreshToken="+refreshToken)));

// then
resultActions.andDo(document("login-google-success",
customRequestPreprocessor(),
preprocessResponse(prettyPrint()),
queryParameters(
Expand All @@ -158,13 +164,12 @@ void loginGoogle_success() throws Exception {
.description("응답 데이터"),
fieldWithPath("data.accessToken").type(JsonFieldType.STRING)
.description("access 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING)
.description("refresh 토큰"),
fieldWithPath("message").type(JsonFieldType.STRING)
.description("메시지")
)));


),
responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.SET_COOKIE)
.description("refreshToken"))
));
verify(googleService).loginGoogle(code);
}

Expand Down Expand Up @@ -215,12 +220,11 @@ class reissueToken {
@Test
@DisplayName("refresh token을 정상적으로 재발급하면 200 상태코드를 반환한다.")
@WithMockCustomUser
@Disabled
void reissueToken_success() throws Exception {

// given
String accessToken = "abcdefg";
String refreshToken = "qwerstu";
String accessToken = "validAccessToken";
String refreshToken = "validRefreshToken";
RefreshTokenRequestDto refreshTokenRequestDto = new RefreshTokenRequestDto("qwer");
given(authService.reissueToken(refreshTokenRequestDto.refreshToken())).willReturn(
new Token(accessToken, refreshToken)
Expand All @@ -236,8 +240,7 @@ void reissueToken_success() throws Exception {
.andExpect(jsonPath("$.code").value("200"))
.andExpect(jsonPath("$.message").value("성공"))
.andExpect(jsonPath("$.data.accessToken").value(accessToken))
.andExpect(jsonPath("$.data.refreshToken").value(refreshToken))
.andDo(print());
.andExpect(header().string("Set-Cookie", containsString("refreshToken="+refreshToken)));

// then
resultActions.andDo(document("reissue-token",
Expand All @@ -254,11 +257,13 @@ void reissueToken_success() throws Exception {
.description("응답 데이터"),
fieldWithPath("data.accessToken").type(JsonFieldType.STRING)
.description("access 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING)
.description("refresh 토큰"),

fieldWithPath("message").type(JsonFieldType.STRING)
.description("메시지")
)));
),
responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.SET_COOKIE)
.description("refreshToken"))
));

verify(authService).reissueToken(refreshTokenRequestDto.refreshToken());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.headers.HeaderDocumentation;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.restdocs.snippet.Attributes;
import org.springframework.test.web.servlet.ResultActions;
Expand All @@ -21,9 +22,11 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
Expand All @@ -34,8 +37,7 @@
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class UserControllerTest extends ControllerTest {

Expand Down Expand Up @@ -65,7 +67,7 @@ void signUpKakao_success() throws Exception {
.andExpect(jsonPath("$.code").value("200"))
.andExpect(jsonPath("$.message").value("성공"))
.andExpect(jsonPath("$.data.accessToken").value(accessToken))
.andExpect(jsonPath("$.data.refreshToken").value(refreshToken))
.andExpect(header().string("Set-Cookie", containsString("refreshToken="+refreshToken)))
.andDo(print());

// then
Expand Down Expand Up @@ -93,11 +95,12 @@ void signUpKakao_success() throws Exception {
.description("응답 데이터"),
fieldWithPath("data.accessToken").type(JsonFieldType.STRING)
.description("access 토큰"),
fieldWithPath("data.refreshToken").type(JsonFieldType.STRING)
.description("refresh 토큰"),
fieldWithPath("message").type(JsonFieldType.STRING)
.description("메시지")
)));
),
responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.SET_COOKIE)
.description("refreshToken"))
));

verify(userService).signUpUser(signUpRequestDto);
}
Expand Down

0 comments on commit a80ec39

Please sign in to comment.