Spring Boot 프로젝트를 진행하며 JWT토큰으로 로그인 기능을 구현했다.
내 프로젝트 기준으로 액세스토큰의 만료시간은 1시간, 리프레시 토큰의 만료시간은 3시간으로 설정했는데, API를 개발하고 테스트할 때마다 헤더에 토큰을 넣어주고, 만료되었을 경우 갱신해줘야 한다.
이 과정을 쿠키 관련 유틸 클래스를 만들어 자동으로 설정해 보도록 하자.
CookieUtil 구현
public class CookieUtil {
private static final int COOKIE_EXPIRATION_TIME = 3 * 60 * 60;
// JWT 필터에서 쿠키에 저장된 액세스토큰을 조회하는 메소드
public static String getAccessToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (!ObjectUtils.isEmpty(cookies)) {
for (Cookie cookie : cookies) {
if ("accessToken".equals(cookie.getName())) {
return cookie.getValue();
}
}
}
return null;
}
// 로그인 성공 시 HttpServletResponse에 액세스토큰 저장하는 메소드
public static void generateCookie(HttpServletResponse response, String key, String value) {
Cookie cookie = new Cookie(key, value);
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setMaxAge(COOKIE_EXPIRATION_TIME);
response.addCookie(cookie);
}
}
CookieUtil 클래스를 만들어 요청에서 쿠키를 꺼내오는 메소드와 응답에 쿠키를 저장해 주는 메소드를 구현한다.
로그인 성공 시 쿠키 저장
public TokenDto login(LoginDto loginDto, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUserId(), loginDto.getPassword());
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
TokenDto tokenDto = tokenProvider.generateToken(authentication);
CookieUtil.generateCookie(response, "accessToken", tokenDto.getAccessToken());
return tokenDto;
}
로그인 메소드에서 인증을 마친 후 토큰을 생성한 다음 CookieUtil의 generateCookie() 메소드를 사용해 'accessToken'이라는 key에 액세스 토큰을 저장한다.
로그인 API 호출 후 'accessToken'이라는 쿠키가 생겨있는 것을 확인할 수 있다.
쿠키에서 토큰 조회
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// 쿠키에서 토큰 추출
String accessToken = CookieUtil.getAccessToken(request);
if (StringUtils.hasText(accessToken)) {
try {
if (tokenProvider.validateToken(accessToken)) {
Authentication authentication = tokenProvider.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (ExpiredJwtException accessTokenEx) {
log.info("Expired accessToken");
...
}
}
filterChain.doFilter(request, response);
}
Jwt 필터의 일부이다. CookieUtil의 getAccessToken() 메소드를 호출해서 accessToken을 가져와 인증 과정을 수행한다.
Spring Boot 프로젝트를 진행하며 간단하게 로그인 후 토큰을 설정해주는 과정을 알아보았다.
끝.
'Spring Boot' 카테고리의 다른 글
[Spring Boot] Redis 적용해서 토큰 정보 저장 후 자동 갱신하기 (0) | 2023.12.25 |
---|---|
[Spring Boot] @Valid 어노테이션 사용하기 (0) | 2023.12.24 |
[SpringBoot] @Secured, @PreAuthorize, @PostAuthorize (0) | 2023.12.24 |