Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 토큰 반환 시 body가 아닌 cookie로 반환하도록 원상복구 #223

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions backend/http/offering.http
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@
GET {{base-url}}/offerings/1

### 공모 목록 조회 API
GET {{base-url}}/offerings?filter=IMMINENT&page-size=3&last-id=






GET {{base-url}}/offerings?filter=IMMINENT&page-size=3&last-id=10

### 공모 필터 목록 조회 API
GET {{base-url}}/offerings/filters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import com.zzang.chongdae.auth.service.AuthService;
import com.zzang.chongdae.auth.service.dto.LoginRequest;
import com.zzang.chongdae.auth.service.dto.LoginResponse;
import com.zzang.chongdae.auth.service.dto.RefreshRequest;
import com.zzang.chongdae.auth.service.dto.RefreshResponse;
import com.zzang.chongdae.auth.service.dto.SignupRequest;
import com.zzang.chongdae.auth.service.dto.SignupResponse;
import com.zzang.chongdae.auth.service.dto.TokenDto;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -19,12 +21,16 @@
public class AuthController {

private final AuthService authService;
private final CookieProducer cookieExtractor;
private final CookieConsumer cookieConsumer;

@PostMapping("/auth/login")
public ResponseEntity<LoginResponse> login(
@RequestBody @Valid LoginRequest request) {
LoginResponse response = authService.login(request);
return ResponseEntity.ok(response);
public ResponseEntity<Void> login(
@RequestBody @Valid LoginRequest request, HttpServletResponse servletResponse) {
TokenDto tokenDto = authService.login(request);
List<Cookie> cookies = cookieExtractor.extractAuthCookies(tokenDto);
cookieConsumer.addCookies(servletResponse, cookies);
return ResponseEntity.ok().build();
}

@PostMapping("/auth/signup")
Expand All @@ -35,9 +41,11 @@ public ResponseEntity<SignupResponse> signup(
}

@PostMapping("/auth/refresh")
public ResponseEntity<RefreshResponse> refresh(
@RequestBody RefreshRequest request) {
RefreshResponse response = authService.refresh(request);
return ResponseEntity.ok(response);
public ResponseEntity<Void> refresh(
@RequestBody RefreshRequest request, HttpServletResponse servletResponse) {
TokenDto tokenDto = authService.refresh(request);
List<Cookie> cookies = cookieExtractor.extractAuthCookies(tokenDto);
cookieConsumer.addCookies(servletResponse, cookies);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import com.zzang.chongdae.auth.exception.AuthErrorCode;
import com.zzang.chongdae.global.exception.MarketException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
Expand All @@ -12,6 +14,12 @@ public class CookieConsumer {
private static final String ACCESS_TOKEN_COOKIE_NAME = "access_token";
private static final String REFRESH_TOKEN_COOKIE_NAME = "refresh_token";

public void addCookies(HttpServletResponse servletResponse, List<Cookie> cookies) {
for (Cookie cookie : cookies) {
servletResponse.addCookie(cookie);
}
}

public String getAccessToken(Cookie[] cookies) {
return getTokenByCookieName(ACCESS_TOKEN_COOKIE_NAME, cookies);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.zzang.chongdae.auth.controller;

import com.zzang.chongdae.auth.service.dto.TokenDto;
import jakarta.servlet.http.Cookie;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
public class CookieProducer {

private static final String ACCESS_TOKEN_COOKIE_NAME = "access_token";
private static final String REFRESH_TOKEN_COOKIE_NAME = "refresh_token";

public List<Cookie> extractAuthCookies(TokenDto tokenDto) {
List<Cookie> cookies = new ArrayList<>();
cookies.add(createCookie(ACCESS_TOKEN_COOKIE_NAME, tokenDto.accessToken()));
cookies.add(createCookie(REFRESH_TOKEN_COOKIE_NAME, tokenDto.refreshToken()));
return cookies;
}

private Cookie createCookie(String tokenName, String token) {
Cookie cookie = new Cookie(tokenName, token);
cookie.setHttpOnly(true);
cookie.setPath("/");
return cookie;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

import com.zzang.chongdae.auth.exception.AuthErrorCode;
import com.zzang.chongdae.auth.service.dto.LoginRequest;
import com.zzang.chongdae.auth.service.dto.LoginResponse;
import com.zzang.chongdae.auth.service.dto.RefreshRequest;
import com.zzang.chongdae.auth.service.dto.RefreshResponse;
import com.zzang.chongdae.auth.service.dto.SignupRequest;
import com.zzang.chongdae.auth.service.dto.SignupResponse;
import com.zzang.chongdae.auth.service.dto.TokenDto;
Expand All @@ -26,12 +24,11 @@ public class AuthService {
private final JwtTokenProvider jwtTokenProvider;
private final NicknameGenerator nickNameGenerator;

public LoginResponse login(LoginRequest request) {
public TokenDto login(LoginRequest request) {
String password = passwordEncoder.encode(request.ci());
MemberEntity member = memberRepository.findByPassword(password)
.orElseThrow(() -> new MarketException(AuthErrorCode.INVALID_PASSWORD));
TokenDto tokenDto = jwtTokenProvider.createAuthToken(member.getId().toString());
return new LoginResponse(tokenDto);
return jwtTokenProvider.createAuthToken(member.getId().toString());
}

@Transactional
Expand All @@ -46,10 +43,9 @@ public SignupResponse signup(SignupRequest request) {
return new SignupResponse(savedMember, tokenDto);
}

public RefreshResponse refresh(RefreshRequest request) {
public TokenDto refresh(RefreshRequest request) {
Long memberId = jwtTokenProvider.getMemberIdByRefreshToken(request.refreshToken());
TokenDto tokenDto = jwtTokenProvider.createAuthToken(memberId.toString());
return new RefreshResponse(tokenDto);
return jwtTokenProvider.createAuthToken(memberId.toString());
}

public MemberEntity findMemberByAccessToken(String token) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.zzang.chongdae.auth.integration;

import static com.epages.restdocs.apispec.ResourceDocumentation.headerWithName;
import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static com.epages.restdocs.apispec.ResourceSnippetParameters.builder;
import static com.epages.restdocs.apispec.Schema.schema;
import static io.restassured.RestAssured.given;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document;

import com.epages.restdocs.apispec.HeaderDescriptorWithType;
import com.epages.restdocs.apispec.ResourceSnippetParameters;
import com.zzang.chongdae.auth.service.dto.LoginRequest;
import com.zzang.chongdae.auth.service.dto.RefreshRequest;
Expand Down Expand Up @@ -35,17 +37,18 @@ class Login {
List<FieldDescriptor> requestDescriptors = List.of(
fieldWithPath("ci").description("회원 식별자 인증 정보")
);
List<FieldDescriptor> responseDescriptors = List.of(
fieldWithPath("accessToken").description("accessToken"),
fieldWithPath("refreshToken").description("refreshToken")
List<HeaderDescriptorWithType> responseHeaderDescriptors = List.of(
headerWithName("Set-Cookie").description("""
access_token=a.b.c; Path=/; HttpOnly \n
refresh_token=a.b.c; Path=/; HttpOnly
""")
);
ResourceSnippetParameters successSnippets = builder()
.summary("회원 로그인")
.description("회원 식별자 인증 정보로 로그인 합니다.")
.requestFields(requestDescriptors)
.responseFields(responseDescriptors)
.responseHeaders(responseHeaderDescriptors)
.requestSchema(schema("LonginRequest"))
.responseSchema(schema("LoginResponse"))
.build();

MemberEntity member;
Expand Down Expand Up @@ -145,17 +148,18 @@ class Refresh {
List<FieldDescriptor> requestDescriptors = List.of(
fieldWithPath("refreshToken").description("재발급에 필요한 refreshToken")
);
List<FieldDescriptor> responseDescriptors = List.of(
fieldWithPath("accessToken").description("재발급한 accessToken"),
fieldWithPath("refreshToken").description("재발급한 refreshToken")
List<HeaderDescriptorWithType> responseHeaderDescriptors = List.of(
headerWithName("Set-Cookie").description("""
access_token=a.b.c; Path=/; HttpOnly \n
refresh_token=a.b.c; Path=/; HttpOnly
""")
);
ResourceSnippetParameters successSnippets = builder()
.summary("토큰 재발급")
.description("토큰을 재발급합니다.")
.requestFields(requestDescriptors)
.responseFields(responseDescriptors)
.responseHeaders(responseHeaderDescriptors)
.requestSchema(schema("RefreshRequest"))
.requestSchema(schema("RefreshResponse"))
.build();
ResourceSnippetParameters failedSnippets = builder()
.requestFields(requestDescriptors)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,30 @@
package com.zzang.chongdae.global.helper;

import com.zzang.chongdae.auth.service.dto.TokenDto;
import io.restassured.http.Cookie;
import com.zzang.chongdae.auth.service.dto.LoginRequest;
import io.restassured.RestAssured;
import io.restassured.http.Cookies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;


@Component
public class CookieProvider {

private final TestTokenProvider tokenProvider;

@Autowired
public CookieProvider(TestTokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}

public Cookies createCookies() {
TokenDto tokenDto = tokenProvider.createTokens();
return createCookiesFromTokenDto(tokenDto);
return RestAssured.given().log().all()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(new LoginRequest("dora1234"))
.when().post("/auth/login")
.then().log().all()
.extract().detailedCookies();
}

public Cookies createCookiesWithCi(String ci) {
TokenDto tokenDto = tokenProvider.createTokensWithCi(ci);
return createCookiesFromTokenDto(tokenDto);
}

private Cookies createCookiesFromTokenDto(TokenDto tokenDto) {
Cookie accessToken = new Cookie.Builder("access_token", tokenDto.accessToken()).build();
Cookie refreshToken = new Cookie.Builder("refresh_token", tokenDto.refreshToken()).build();
return new Cookies(accessToken, refreshToken);
return RestAssured.given().log().all()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(new LoginRequest(ci))
.when().post("/auth/login")
.then().log().all()
.extract().detailedCookies();
}
}

This file was deleted.