Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
1.0 kB
2
Indexable
Never
@WebFilter(urlPatterns = ["/v1/sites/categories/*"])
class ApiKeyFilter(
    @Value("\${config.api.key}")
    private val configApiKey: String,
    private val X_API_KEY: String = "X-Api-Key"
) : Filter {
    override fun doFilter(
        request: ServletRequest,
        response: ServletResponse,
        chain: FilterChain
    ) {
        val key = (request as HttpServletRequest).getHeader(X_API_KEY)
        if (StringUtils.hasText(key) && configApiKey == key) {
            chain.doFilter(request, response)
            return
        } else {
            response.resetBuffer()
            response.contentType = MediaType.APPLICATION_JSON_VALUE
            response.outputStream.print(
                ObjectMapper().writeValueAsString(
                    ErrorResponse(
                        code = "401",
                        message = HttpStatus.UNAUTHORIZED.name,
                    )
                )
            )
            response.flushBuffer()
        }
    }
}
Leave a Comment