Spring Boot Token Filter

add filter

1
2
3
4
5
6
7
8
@Bean
fun getJwtFilter(): FilterRegistrationBean {
val filterBean = FilterRegistrationBean()
filterBean.filter = JwtFilter()
val including = appProperties.filter?.jwt?.include?.split(",")
including?.forEach { it -> filterBean.addUrlPatterns(it) }
return filterBean
}

filter config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component
class JwtFilter : GenericFilterBean() {
private val log: Logger = LoggerFactory.getLogger(JwtFilter::class.java.simpleName)
private val methods = arrayListOf(RequestMethod.GET.name, RequestMethod.POST.name, RequestMethod.PUT.name, RequestMethod.DELETE.name)

override fun doFilter(servletRequest: ServletRequest?, servletResponse: ServletResponse?,
filterChain: FilterChain?) {
val request = servletRequest as HttpServletRequest
val response = servletResponse as HttpServletResponse
val path = request.requestURI.substring(request.contextPath.length).replace("[/]+$", "")
log.debug("doFilter(): path:$path")
if (methods.contains(request.method)) {
if (!FilterConfig.JwtExcludePath.containsKey(path)) {
val token = request.getHeader(AuthConfig.TokenHeader)
if (!JwtUtil.isValid(token, KeyConfig.publicKey)) {
response.sendError(401)
return
}
}
}
filterChain?.doFilter(request, response)
}
}