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: accessToken 재발급 #155

Merged
merged 6 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import in.koreatech.koin.domain.auth.UserAuth;
import in.koreatech.koin.domain.user.dto.UserLoginRequest;
import in.koreatech.koin.domain.user.dto.UserLoginResponse;
import in.koreatech.koin.domain.user.dto.UserTokenRefreshRequest;
import in.koreatech.koin.domain.user.dto.UserTokenRefreshResponse;
import in.koreatech.koin.domain.user.model.User;
import in.koreatech.koin.domain.user.service.UserService;
import jakarta.validation.Valid;
Expand Down Expand Up @@ -31,4 +33,13 @@ public ResponseEntity<Void> logout(@UserAuth User user) {
userService.logout(user);
return ResponseEntity.ok().build();
}

@PostMapping("/user/refresh")
public ResponseEntity<UserTokenRefreshResponse> refresh(
@UserAuth User user,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R

PR Comment에 해당하는 부분입니다.

인증 헤더 필요 유무에 대한 의견 부탁드립니다~!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

현재 상황에 대해 저는 2번 방법이 좋을 것 같습니다!

  1. /user/refresh 요청 시에는 인증 헤더가 필요하지 않도록 설계 (만료 토큰 관리 안함)
    1. request로 넘어오는 refresh_token에 대한 검증만 수행하면 된다.
    2. refreshToken만 탈취되었을 때의 시나리오가 우려된다. 하지만 로그아웃이 존재하기에 탈취 적발 시 만료시킬 수 있으므로 대응책은 있는 상황임

refresh token만 검증하면 관리나 검증 로직이 간편하기 때문입니다.
탈취의 경우는 액세스 토큰의 만료 시간을 줄이거나 로그아웃하는 방법이 있기 때문에 괜찮을 것 같다고 생각합니다..!

@RequestBody @Valid UserTokenRefreshRequest request
) {
UserTokenRefreshResponse tokenGroupResponse = userService.refresh(user, request);
return ResponseEntity.ok().body(tokenGroupResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package in.koreatech.koin.domain.user.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import jakarta.validation.constraints.NotNull;

@JsonNaming(value = SnakeCaseStrategy.class)
public record UserTokenRefreshRequest(
@JsonProperty("refresh_token") @NotNull(message = "refresh_token을 입력해주세요.") String refreshToken
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package in.koreatech.koin.domain.user.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

public record UserTokenRefreshResponse(
@JsonProperty("token") String accessToken,
@JsonProperty("refresh_token") String refreshToken
) {

public static UserTokenRefreshResponse of(String accessToken, String refreshToken) {
return new UserTokenRefreshResponse(accessToken, refreshToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
import in.koreatech.koin.domain.auth.JwtProvider;
import in.koreatech.koin.domain.user.dto.UserLoginRequest;
import in.koreatech.koin.domain.user.dto.UserLoginResponse;
import in.koreatech.koin.domain.user.dto.UserTokenRefreshRequest;
import in.koreatech.koin.domain.user.dto.UserTokenRefreshResponse;
import in.koreatech.koin.domain.user.exception.UserNotFoundException;
import in.koreatech.koin.domain.user.model.User;
import in.koreatech.koin.domain.user.model.UserToken;
import in.koreatech.koin.domain.user.repository.UserRepository;
import in.koreatech.koin.domain.user.repository.UserTokenRepository;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -45,4 +48,14 @@ public UserLoginResponse login(UserLoginRequest request) {
public void logout(User user) {
userTokenRepository.deleteById(user.getId());
}

public UserTokenRefreshResponse refresh(User user, UserTokenRefreshRequest request) {
UserToken userToken = userTokenRepository.findById(user.getId())
.orElseThrow(() -> new IllegalArgumentException("refresh token이 존재하지 않습니다. request: " + request));
if (!Objects.equals(userToken.getRefreshToken(), request.refreshToken())) {
throw new IllegalArgumentException("refresh token이 일치하지 않습니다. request: " + request);
}
String accessToken = jwtProvider.createToken(user);
return UserTokenRefreshResponse.of(accessToken, userToken.getRefreshToken());
}
}
63 changes: 63 additions & 0 deletions src/test/java/in/koreatech/koin/acceptance/AuthApiTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import io.restassured.http.ContentType;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import java.util.Map;
import java.util.Optional;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
Expand Down Expand Up @@ -126,4 +127,66 @@ void userLogoutSuccess() {

Assertions.assertThat(token).isEmpty();
}

@Test
@DisplayName("사용자가 로그인 이후 refreshToken을 재발급한다")
void userRefreshToken() {
User user = User.builder()
.password("1234")
.nickname("주노")
.name("최준호")
.phoneNumber("010-1234-5678")
.userType(UserType.USER)
.email("[email protected]")
.isAuthed(true)
.isDeleted(false)
.build();

userRepository.save(user);

ExtractableResponse<Response> response = RestAssured
.given()
.log().all()
.body("""
{
"email": "[email protected]",
"password": "1234"
}
""")
.contentType(ContentType.JSON)
.when()
.log().all()
.post("/user/login")
.then()
.log().all()
.statusCode(HttpStatus.CREATED.value())
.extract();

RestAssured
.given()
.log().all()
.header("Authorization", "BEARER " + response.jsonPath().getString("token"))
.body(
Map.of("refresh_token", response.jsonPath().getString("refresh_token"))
)
.contentType(ContentType.JSON)
.when()
.log().all()
.post("/user/refresh")
.then()
.log().all()
.statusCode(HttpStatus.OK.value())
.extract();

UserToken token = tokenRepository.findById(user.getId()).get();

assertSoftly(
softly -> {
softly.assertThat(response.jsonPath().getString("token")).isNotNull();
softly.assertThat(response.jsonPath().getString("refresh_token")).isNotNull();
softly.assertThat(response.jsonPath().getString("refresh_token"))
.isEqualTo(token.getRefreshToken());
}
);
}
}
Loading