부족한 부분이 있다면 누가 내용 보충좀 해주세요 🤟
컨트롤러에서 Authentication 정보를 사용하는 경우!

조금 억지스러운 예제이긴 하지만… 😓
컨트롤러에서 위와 같이
@AuthenticationPrincipal
를 사용해서 토큰 정보를 사용한다고 가정해보겠습니다.이 경우에 테스트 코드에서 그냥 테스트를 하게 되면 아래와 같은 오류를 만나게 됩니다.
이유는 토큰 정보를 찾을 수가 없기 때문입니다. 😱

그래서 테스트 하기 위해서는 토큰 정보를 설정해줘야 합니다.
이전 인스타뀨램에서는 아래와 같이 테스트 클래스에서 별도의 메서드를 정의해줘야 했습니다. 🫠

✨✨ 이를 조금 더 손쉽게 사용할 수 있도록 어노테이션 클래스를 생성했습니다.

public class WithMockJwtAuthenticationSecurityContextFactory implements WithSecurityContextFactory<WithMockJwtAuthentication> { @Override public SecurityContext createSecurityContext(WithMockJwtAuthentication annotation) { SecurityContext context = SecurityContextHolder.createEmptyContext(); JwtAuthenticationToken authentication = new JwtAuthenticationToken( new JwtAuthentication(annotation.token(), annotation.id(), annotation.username()), null, createAuthorityList(annotation.role()) ); context.setAuthentication(authentication); return context; } }
@Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithMockJwtAuthenticationSecurityContextFactory.class) public @interface WithMockJwtAuthentication { String token() default "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwicm9sZXMiOlsiVVNFUiJdLCJpc3MiOiJzZmFtIiwiZXhwIjoxNjU4NTkyNTYyLCJpYXQiOjE2NTg1OTI1MzIsInVzZXJJZCI6MSwidXNlcm5hbWUiOiJ0ZXN0MDAifQ.FDkOUzhLvKOYFmjOxRtF-dRDSO2BkoplJTMIyhp0c0ajxOLeZbKuekSyySnCnjVvv_f0Qx8T7a3ZS2OlaSGiDQ"; long id() default 1L; String username() default "test00"; String role() default "USER"; }
토큰 설정에 필요한 필드들과 함께 Default 값들을 설정했습니다.
이를 사용하신다면 해당 값으로 토큰 정보가 설정되기 때문에 해당 필드의 값으로 테스트 해주시면 됩니다.
- 토큰은
application-mem.yml
의 테스트 키로 만든 값입니다. (배포 환경의 실제 키로 만든 토큰을 넣는건 위험할 수 있겠죠? 🫠 )

해당 클래스는 공통적으로 사용되는 값이기 때문에 Default값을 변경은 팀원들 검토 후에 해주세요.
✨ 설정은 이제 매우 간단해집니다.
어노테이션만 사용해주시면 이제 토큰 정보가 위의 클래스에서 설정된 정보로 사용됩니다.

- 이제 테스트를 다시 해보면 상큼하게 성공하게 됩니다.

끗…?
정보가 더 필요하다면 아래의 블로그가 참고가 될것 같습니다. 👍