Spring Cloud Request Filter

OncePerRequestFilter

For our one request, this filter will execute exactly one time (no more no less). This behavior is very useful while working with security authentication.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class AuthorizationFilter : OncePerRequestFilter() {
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filter: FilterChain) {
val token = request.getHeader(HttpHeaders.AUTHORIZATION)
if (token == null) {
val error = ErrorInfo(ErrorCode.ILLEGAL_TOKEN)
writeError(response, error, HttpStatus.UNAUTHORIZED.value())
return
}

val claims = JwtUtil.parseAuthToken(token)
if (claims == null) {
val error = ErrorInfo(ErrorCode.ILLEGAL_TOKEN)
writeError(response, error, HttpStatus.UNAUTHORIZED.value())
return
}

filter.doFilter(request, response)
}

private fun writeError(response: HttpServletResponse, error: ErrorInfo, code: Int) {
response.writer.write(JsonUtil.objToJson(error))
response.status = code
response.writer.flush()
}
}

@SpringBootApplication
class GatewayApplication {
@Bean
fun configFilter(): FilterRegistrationBean<AuthorizationFilter> {
val registration = FilterRegistrationBean<AuthorizationFilter>()
registration.filter = AuthorizationFilter()
registration.addUrlPatterns("/*")
registration.setName("AuthorizationFilter")
registration.order = Ordered.HIGHEST_PRECEDENCE
return registration
}
}

// contracts
StandaloneMockMvcBuilder mockMvc = MockMvcBuilders.standaloneSetup(
new OrderController(),
new PositionController()
).addFilters(new AuthorizationFilter());
RestAssuredMockMvc.standaloneSetup(mockMvc);