Skip to content

Commit

Permalink
feat: 액세스 토큰 전송시 perfix Bearer를 추가한다. (#160)
Browse files Browse the repository at this point in the history
* refactor: 인증 패키지 구조를 개선한다.

* feat: JWT 인증 필터에서 Bearer 를 명시한 토큰만을 받도록 변경한다.

* docs: 인증 도메인 api 문서화를 추가한다.
  • Loading branch information
hseong3243 authored Nov 8, 2023
1 parent 941d999 commit e89039c
Show file tree
Hide file tree
Showing 29 changed files with 109 additions and 47 deletions.
24 changes: 24 additions & 0 deletions src/docs/asciidoc/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,30 @@

== 0. 인증

=== 보호소 로그인

==== Request
operation::auth-controller-test/shelter-login[snippets='http-request,request-fields']

==== Response
operation::auth-controller-test/shelter-login[snippets='http-response,response-fields,response-cookies']

=== 봉사자 로그인

==== Request
operation::auth-controller-test/volunteer-login[snippets='http-request,request-fields']

==== Response
operation::auth-controller-test/volunteer-login[snippets='http-response,response-fields,response-cookies']

=== 액세스 토큰 갱신

==== Request
operation::auth-controller-test/refresh-access-token[snippets='http-request,request-cookies']

==== Response
operation::auth-controller-test/refresh-access-token[snippets='http-response,response-fields,response-cookies']

== 1. 봉사자

=== 봉사자가 완료한 봉사 모집글 리스트 조회
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import com.clova.anifriends.domain.animal.dto.response.FindAnimalsByVolunteerResponse;
import com.clova.anifriends.domain.animal.dto.response.RegisterAnimalResponse;
import com.clova.anifriends.domain.animal.service.AnimalService;
import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import jakarta.validation.Valid;
import java.net.URI;
import lombok.RequiredArgsConstructor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import com.clova.anifriends.domain.applicant.dto.FindApplicantsApprovedResponse;
import com.clova.anifriends.domain.applicant.dto.FindApplyingVolunteersResponse;
import com.clova.anifriends.domain.applicant.service.ApplicantService;
import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.clova.anifriends.domain.auth.resolver;
package com.clova.anifriends.domain.auth;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.clova.anifriends.domain.auth.authentication;

import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.response.CustomClaims;
import com.clova.anifriends.domain.auth.dto.response.CustomClaims;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.clova.anifriends.domain.auth.controller;

import com.clova.anifriends.domain.auth.controller.request.LoginRequest;
import com.clova.anifriends.domain.auth.controller.response.LoginResponse;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.request.LoginRequest;
import com.clova.anifriends.domain.auth.dto.response.LoginResponse;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.service.AuthService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.clova.anifriends.domain.auth.controller.request;
package com.clova.anifriends.domain.auth.dto.request;

import jakarta.validation.constraints.NotBlank;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.clova.anifriends.domain.auth.jwt.response;
package com.clova.anifriends.domain.auth.dto.response;

import java.util.List;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.clova.anifriends.domain.auth.controller.response;
package com.clova.anifriends.domain.auth.dto.response;

import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;

public record LoginResponse(Long userId, UserRole role, String accessToken) {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.clova.anifriends.domain.auth.jwt.response;
package com.clova.anifriends.domain.auth.dto.response;

import com.clova.anifriends.domain.auth.jwt.UserRole;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

public class InvalidJwtException extends AuthenticationException {

public InvalidJwtException(String message) {
super(ErrorCode.UN_AUTHENTICATION, message);
}

public InvalidJwtException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.clova.anifriends.domain.auth.jwt;


import com.clova.anifriends.domain.auth.jwt.response.CustomClaims;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.CustomClaims;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;

public interface JwtProvider {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import com.clova.anifriends.domain.auth.exception.AuthNotFoundException;
import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.repository.RefreshTokenRepository;
import com.clova.anifriends.domain.shelter.Shelter;
import com.clova.anifriends.domain.shelter.repository.ShelterRepository;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.clova.anifriends.domain.recruitment.controller;

import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import com.clova.anifriends.domain.recruitment.dto.request.FindRecruitmentsByShelterRequest;
import com.clova.anifriends.domain.recruitment.dto.request.FindRecruitmentsByVolunteerRequest;
import com.clova.anifriends.domain.recruitment.dto.request.RegisterRecruitmentRequest;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.clova.anifriends.domain.review.controller;

import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import com.clova.anifriends.domain.review.dto.request.RegisterReviewRequest;
import com.clova.anifriends.domain.review.dto.response.FindReviewResponse;
import com.clova.anifriends.domain.review.dto.response.FindShelterReviewsByVolunteerResponse;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.clova.anifriends.domain.shelter.controller;

import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import com.clova.anifriends.domain.shelter.dto.CheckDuplicateShelterEmailRequest;
import com.clova.anifriends.domain.shelter.dto.CheckDuplicateShelterResponse;
import com.clova.anifriends.domain.shelter.dto.FindShelterDetailResponse;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.clova.anifriends.domain.volunteer.controller;

import com.clova.anifriends.domain.auth.resolver.LoginUser;
import com.clova.anifriends.domain.auth.LoginUser;
import com.clova.anifriends.domain.volunteer.dto.request.CheckDuplicateVolunteerEmailRequest;
import com.clova.anifriends.domain.volunteer.dto.request.RegisterVolunteerRequest;
import com.clova.anifriends.domain.volunteer.dto.response.CheckDuplicateVolunteerEmailResponse;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.clova.anifriends.global.config;

import com.clova.anifriends.domain.auth.authentication.JwtAuthenticationProvider;
import com.clova.anifriends.domain.auth.filter.JwtAuthenticationFilter;
import com.clova.anifriends.global.web.filter.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.clova.anifriends.global.config;

import com.clova.anifriends.domain.auth.resolver.LoginUserArgumentResolver;
import com.clova.anifriends.global.web.argumentresolver.LoginUserArgumentResolver;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.clova.anifriends.domain.auth.jwt;
package com.clova.anifriends.global.jwt;

import com.clova.anifriends.domain.auth.dto.response.CustomClaims;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.exception.ExpiredAccessTokenException;
import com.clova.anifriends.domain.auth.exception.InvalidJwtException;
import com.clova.anifriends.domain.auth.exception.ExpiredRefreshTokenException;
import com.clova.anifriends.domain.auth.jwt.response.CustomClaims;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.global.exception.ErrorCode;
import com.clova.anifriends.domain.auth.exception.InvalidJwtException;
import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
Expand Down Expand Up @@ -101,7 +102,7 @@ public CustomClaims parseAccessToken(String token) {
} catch (JwtException ex) {
log.info("[EX] {}: 잘못된 JWT입니다.", ex.getClass().getSimpleName());
}
throw new InvalidJwtException(ErrorCode.UN_AUTHENTICATION, "유효하지 않은 JWT입니다.");
throw new InvalidJwtException("유효하지 않은 JWT입니다.");
}

@Override
Expand All @@ -117,6 +118,6 @@ public TokenResponse refreshAccessToken(String refreshToken) {
} catch (JwtException ex) {
log.info("[EX] {}: 잘못된 리프레시 토큰입니다.", ex.getClass().getSimpleName());
}
throw new InvalidJwtException(ErrorCode.UN_AUTHENTICATION, "유효하지 않은 리프레시 토큰입니다.");
throw new InvalidJwtException("유효하지 않은 리프레시 토큰입니다.");
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.clova.anifriends.domain.auth.resolver;
package com.clova.anifriends.global.web.argumentresolver;

import static com.clova.anifriends.global.exception.ErrorCode.UN_AUTHENTICATION;

import com.clova.anifriends.domain.auth.authentication.JwtAuthentication;
import com.clova.anifriends.domain.auth.exception.AuthAuthenticationException;
import com.clova.anifriends.domain.auth.LoginUser;
import java.util.Objects;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.clova.anifriends.domain.auth.filter;
package com.clova.anifriends.global.web.filter;

import com.clova.anifriends.domain.auth.authentication.JwtAuthenticationProvider;
import com.clova.anifriends.domain.auth.exception.InvalidJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.GenericFilter;
import jakarta.servlet.ServletException;
Expand All @@ -17,17 +18,30 @@
public class JwtAuthenticationFilter extends GenericFilter {

private static final String HEADER = "Authorization";
private static final String BEARER = "Bearer ";
private final JwtAuthenticationProvider authenticationProvider;

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String accessToken = request.getHeader(HEADER);
if (Objects.nonNull(accessToken)) {
String bearerAccessToken = request.getHeader(HEADER);
if (Objects.nonNull(bearerAccessToken)) {
String accessToken = removeBearer(bearerAccessToken);
Authentication authentication = authenticationProvider.authenticate(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(req, res);
}

private String removeBearer(String bearerAccessToken) {
checkTokenContainsBearer(bearerAccessToken);
return bearerAccessToken.replace(BEARER, "");
}

private static void checkTokenContainsBearer(String bearerAccessToken) {
if(!bearerAccessToken.contains(BEARER)) {
throw new InvalidJwtException("올바르지 않는 액세스 토큰 형식입니다.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.support.AuthFixture;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.clova.anifriends.base.BaseControllerTest;
import com.clova.anifriends.domain.auth.controller.request.LoginRequest;
import com.clova.anifriends.domain.auth.dto.request.LoginRequest;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.support.AuthFixture;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -65,7 +65,7 @@ void volunteerLogin() throws Exception {
void shelterLogin() throws Exception {
//given
LoginRequest request = new LoginRequest("[email protected]", "password123!");
TokenResponse response = new TokenResponse(1L, UserRole.ROLE_VOLUNTEER, "accessToken",
TokenResponse response = new TokenResponse(1L, UserRole.ROLE_SHELTER, "accessToken",
"refreshToken");

given(authService.shelterLogin(any(), any())).willReturn(response);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package com.clova.anifriends.domain.auth.filter;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;

import com.clova.anifriends.domain.auth.authentication.JwtAuthenticationProvider;
import com.clova.anifriends.domain.auth.exception.InvalidJwtException;
import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.support.AuthFixture;
import com.clova.anifriends.global.web.filter.JwtAuthenticationFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import java.io.IOException;
Expand Down Expand Up @@ -57,8 +58,7 @@ void doFilter() throws ServletException, IOException {
@DisplayName("성공: 액세스 토큰이 요청에 포함된 경우")
void doFilterWhenContainsToken() throws ServletException, IOException {
//given
TokenResponse tokenResponse = jwtProvider.createToken(1L, UserRole.ROLE_VOLUNTEER);
String accessToken = tokenResponse.accessToken();
String accessToken = AuthFixture.shelterAccessToken();
mockRequest.addHeader("Authorization", accessToken);

//when
Expand All @@ -80,5 +80,21 @@ void doFilterWhenNotContainsToken() throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(authentication).isNull();
}

@Test
@DisplayName("예외: 액세스 토큰이 Bearer 형식이 아닌 경우")
void exceptionWhenTokenIsNotBearer() {
//given
String bearerAccessToken = AuthFixture.volunteerAccessToken();
String accessToken = bearerAccessToken.replace("Bearer ", "");
mockRequest.addHeader("Authorization", accessToken);

//when
Exception exception = catchException(
() -> jwtAuthenticationFilter.doFilter(mockRequest, mockResponse, filterChain));

//then
assertThat(exception).isInstanceOf(InvalidJwtException.class);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
import com.clova.anifriends.domain.auth.exception.ExpiredAccessTokenException;
import com.clova.anifriends.domain.auth.exception.ExpiredRefreshTokenException;
import com.clova.anifriends.domain.auth.exception.InvalidJwtException;
import com.clova.anifriends.domain.auth.jwt.response.CustomClaims;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.CustomClaims;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.support.AuthFixture;
import com.clova.anifriends.global.jwt.JJwtProvider;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.awaitility.core.ThrowingRunnable;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.clova.anifriends.domain.auth.resolver;

import com.clova.anifriends.domain.auth.LoginUser;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import com.clova.anifriends.domain.auth.exception.AuthNotFoundException;
import com.clova.anifriends.domain.auth.jwt.JwtProvider;
import com.clova.anifriends.domain.auth.jwt.UserRole;
import com.clova.anifriends.domain.auth.jwt.response.TokenResponse;
import com.clova.anifriends.domain.auth.dto.response.TokenResponse;
import com.clova.anifriends.domain.auth.repository.RefreshTokenRepository;
import com.clova.anifriends.domain.auth.support.AuthFixture;
import com.clova.anifriends.domain.auth.support.MockPasswordEncode;
Expand Down
Loading

0 comments on commit e89039c

Please sign in to comment.