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: renew authentication token #43

Merged
merged 8 commits into from
Feb 4, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private void saveRefreshToken(Authentication authentication, String refreshToken
CustomUserDetails user = (CustomUserDetails) authentication.getPrincipal();

refreshTokenRedisRepository.save(RefreshToken.builder()
.email(user.getEmail())
.id(user.getId())
.token(refreshToken)
.expiredTime(REFRESH_TOKEN_EXPIRE_LENGTH)
.build());
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/dnd/wedding/domain/jwt/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
@AllArgsConstructor
@NoArgsConstructor
@Builder
@RedisHash(value = "email")
@RedisHash(value = "id")
public class RefreshToken {

@Id
private String email;
private Long id;
private String token;

@TimeToLive
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.dnd.wedding.domain.jwt.controller;

import com.dnd.wedding.domain.jwt.service.JwtService;
import io.lettuce.core.dynamic.annotation.Param;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("api/v1/jwt")
public class JwtController {

private final JwtService jwtService;

@GetMapping("/refresh")
public ResponseEntity refreshToken(HttpServletRequest request, HttpServletResponse response,
@Param("accessToken") String accessToken) {
String newToken = jwtService.refreshToken(request, response, accessToken);

if (newToken != null) {
return ResponseEntity.ok().body(newToken);
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Failed renew access token");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
import org.springframework.stereotype.Repository;

@Repository
public interface RefreshTokenRedisRepository extends CrudRepository<RefreshToken, String> {
public interface RefreshTokenRedisRepository extends CrudRepository<RefreshToken, Long> {

}
65 changes: 65 additions & 0 deletions src/main/java/com/dnd/wedding/domain/jwt/service/JwtService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.dnd.wedding.domain.jwt.service;

import com.dnd.wedding.domain.jwt.JwtTokenProvider;
import com.dnd.wedding.domain.jwt.RefreshToken;
import com.dnd.wedding.domain.jwt.repository.RefreshTokenRedisRepository;
import com.dnd.wedding.domain.oauth.CustomUserDetails;
import com.dnd.wedding.global.config.util.CookieUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Optional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Log4j2
@Service
public class JwtService {

@Value("${app.auth.token.refresh-cookie-key}")
private final String cookieKey;

private final RefreshTokenRedisRepository refreshTokenRedisRepository;
private final JwtTokenProvider tokenProvider;

public JwtService(@Value("${app.auth.token.refresh-cookie-key}") String cookieKey,
RefreshTokenRedisRepository refreshTokenRedisRepository, JwtTokenProvider tokenProvider) {
this.cookieKey = cookieKey;
this.refreshTokenRedisRepository = refreshTokenRedisRepository;
this.tokenProvider = tokenProvider;
}

public String refreshToken(HttpServletRequest request, HttpServletResponse response,
String oldAccessToken) {
String oldRefreshToken = CookieUtil.getCookie(request, cookieKey)
.map(Cookie::getValue).orElseThrow(() -> new RuntimeException("No Refresh Token Cookie"));

if (Boolean.FALSE.equals(tokenProvider.validateToken(oldRefreshToken))) {
log.info("Not Validated Refresh Token.");
return null;
}

Authentication authentication = tokenProvider.getAuthentication(oldAccessToken);
CustomUserDetails user = (CustomUserDetails) authentication.getPrincipal();

Long id = user.getId();
Optional<RefreshToken> savedToken = refreshTokenRedisRepository.findById(id);

if (savedToken.isEmpty()) {
log.info("Not Existed Refresh Token.");
return null;
} else {
if (!(savedToken.get().getToken().equals(oldRefreshToken))) {
log.info("Not Validated Refresh Token.");
return null;
}
}

String accessToken = tokenProvider.createAccessToken(authentication);
tokenProvider.addRefreshToken(authentication, response);

return accessToken;
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/dnd/wedding/global/config/RedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public RedisConnectionFactory redisConnectionFactory() {
}

@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
public RedisTemplate<Long, String> redisTemplate() {
RedisTemplate<Long, String> redisTemplate = new RedisTemplate<>();

redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.authorizeHttpRequests()
.requestMatchers(HttpMethod.GET, "/oauth2/**").permitAll()
.requestMatchers("/api/v1/jwt/**").permitAll()
.anyRequest().authenticated();

http
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.dnd.wedding.domain.jwt.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

import com.dnd.wedding.domain.jwt.service.JwtService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

class JwtControllerTest {

JwtController jwtController;
JwtService jwtService;
MockHttpServletRequest request;
MockHttpServletResponse response;

@BeforeEach
void init() {
jwtService = mock(JwtService.class);
jwtController = new JwtController(jwtService);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}

@Test
@DisplayName("access token 갱신 성공 시 새로 발급한 token을 전달한다.")
void successRenewAccessToken() {
// given
given(jwtService.refreshToken(request, response, "accessToken")).willReturn("token");

// when
ResponseEntity responseEntity = jwtController.refreshToken(request, response, "accessToken");

// then
assertEquals("token", responseEntity.getBody());
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}

@Test
@DisplayName("access token 갱신 실패 시 401 코드가 전달된다.")
void failRenewAccessToken() {
// given
given(jwtService.refreshToken(request, response, "accessToken")).willReturn(null);

// when
ResponseEntity responseEntity = jwtController.refreshToken(request, response, "accessToken");

// then
assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode());
}
}
128 changes: 128 additions & 0 deletions src/test/java/com/dnd/wedding/domain/jwt/service/JwtServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.dnd.wedding.domain.jwt.service;

import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.dnd.wedding.domain.jwt.JwtTokenProvider;
import com.dnd.wedding.domain.jwt.RefreshToken;
import com.dnd.wedding.domain.jwt.repository.RefreshTokenRedisRepository;
import com.dnd.wedding.domain.member.Role;
import com.dnd.wedding.domain.oauth.CustomUserDetails;
import com.dnd.wedding.domain.oauth.OAuth2Provider;
import jakarta.servlet.http.Cookie;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

class JwtServiceTest {

private static final Collection<? extends GrantedAuthority> authority = Collections.singletonList(
new SimpleGrantedAuthority("ROLE_USER"));

private final String cookieKey = "testCookieKey";
private final String oldRefreshToken = "testRefreshToken";
private final String oldAccessToken = "testAccessToken";
private CustomUserDetails customUserDetails = new CustomUserDetails(1L, "[email protected]",
OAuth2Provider.GOOGLE, Role.USER, authority);
private RefreshTokenRedisRepository refreshTokenRedisRepository;
private JwtTokenProvider tokenProvider;
private JwtService jwtService;
MockHttpServletResponse response;
MockHttpServletRequest request;
Authentication authentication;

@BeforeEach
void init() {
this.refreshTokenRedisRepository = mock(RefreshTokenRedisRepository.class);
this.tokenProvider = mock(JwtTokenProvider.class);
this.authentication = mock(Authentication.class);
this.jwtService = new JwtService(cookieKey, refreshTokenRedisRepository, tokenProvider);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}

@Test
@DisplayName("쿠키에 refresh token이 없는 경우 에러가 발생한다.")
void throwException() {
assertThrows(RuntimeException.class, () -> jwtService.refreshToken(request, response, "token"));
}

@Test
@DisplayName("accessToken 재발급 성공")
void suceessRenewToken() {
Cookie cookie = new Cookie(cookieKey, oldRefreshToken);
request.setCookies(cookie);

RefreshToken refreshToken = RefreshToken.builder()
.id(1L)
.token(oldRefreshToken)
.build();
when(tokenProvider.validateToken(oldRefreshToken)).thenReturn(true);
when(tokenProvider.getAuthentication(oldAccessToken)).thenReturn(authentication);
when(authentication.getPrincipal()).thenReturn(customUserDetails);
when(refreshTokenRedisRepository.findById(1L)).thenReturn(Optional.of(refreshToken));

jwtService.refreshToken(request, response, oldAccessToken);
verify(tokenProvider).createAccessToken(authentication);
verify(tokenProvider).addRefreshToken(authentication, response);
}

@Test
@DisplayName("refresh token이 유효하지 않은 경우 null을 반환한다.")
void failRenewTokenByInvalidRefreshToken() {
Cookie cookie = new Cookie(cookieKey, oldRefreshToken);
request.setCookies(cookie);

String token = jwtService.refreshToken(request, response, oldAccessToken);

assertNull(token);
}

@Test
@DisplayName("저장된 refresh token이 없는 경우 null을 반환한다.")
void failRenewTokenByNotSavedRefreshToken() {
Cookie cookie = new Cookie(cookieKey, oldRefreshToken);
request.setCookies(cookie);

when(tokenProvider.validateToken(oldRefreshToken)).thenReturn(true);
when(tokenProvider.getAuthentication(oldAccessToken)).thenReturn(authentication);
when(authentication.getPrincipal()).thenReturn(customUserDetails);

String token = jwtService.refreshToken(request, response, oldAccessToken);

assertNull(token);
}

@Test
@DisplayName("쿠키의 refresh token이 저장된 refresh token과 일치하지 않는 경우 null을 반환한다.")
void failRenewTokenByDifferentRefreshToken() {
Cookie cookie = new Cookie(cookieKey, oldRefreshToken);
request.setCookies(cookie);

RefreshToken refreshToken = RefreshToken.builder()
.id(1L)
.token("test")
.build();

when(tokenProvider.validateToken(oldRefreshToken)).thenReturn(true);
when(tokenProvider.getAuthentication(oldAccessToken)).thenReturn(authentication);
when(authentication.getPrincipal()).thenReturn(customUserDetails);
when(refreshTokenRedisRepository.findById(1L)).thenReturn(Optional.of(refreshToken));

String token = jwtService.refreshToken(request, response, oldAccessToken);

assertNull(token);
}
}