[JWT] Spring Interceptor 세팅 및 사용하기
안녕하세요! 프뚜입니다.
이전에 JWT 인증을 기준으로 Interceptor를 구현하려고 합니다. 이전 포스팅을 참조하시길 바랍니다.
[JAVA] SpringBoot에서 JWT 설정 및 사용하기 (JJWT)
[개발 환경]
- OS: Windows 10 64bit
- JAVA: 1.8
# Interceptor 설정하기
@RequiredArgsConstructor
@Component
public class JwtInterceptor implements HandlerInterceptor {
private final JwtService jwtService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token != null) {
jwtService.check(token);
return true;
} else {
throw new Exception("JWT 토큰이 없습니다.");
}
}
}
header에 Authorization Key로 token값을 찾습니다.
# WebConfig 설정하기
@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final JwtInterceptor jwtInterceptor;
private String[] excludePathPatterns = {
"/create"
};
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(excludePathPatterns);
}
}
위에 등록한 Interceptor를 등록합니다. /create URI는 토큰을 생성하기 때문에 토큰 여부에 제외됩니다.
# 작동 확인하기
PostMan을 통해서 /create URI에 요청을 보내면 Interceptor에 제외된 URI이기 때문에 정상 작동을 합니다.
/test URI는 Interceptor preHandler에 걸렸기 때문에 token 체크를 합니다. Header에 token이 없기 때문에 error가 발생합니다.
Header에 Authorization Key에 token값을 넣고 요청하면 정상적으로 요청을 받을 수 있습니다. (/test URI는 없기 때문에 404 error가 정상입니다.)
자세한 내용은 소스코드를 통해 확인해보실 수 있습니다. (제목과 Git Comment는 같습니다.)
https://github.com/JeongSeongSoo/spring-tistory
GitHub - JeongSeongSoo/spring-tistory
Contribute to JeongSeongSoo/spring-tistory development by creating an account on GitHub.
github.com