解決方式之一:(在過濾器中增加 OPTIONS 請求過濾)
@Configuration
class AuthFilter : Filter {
private val logger: Logger = LoggerFactory.getLogger(AuthFilter::class.java)
override fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) {
val httpRequest = RequestWrapper(request = request as HttpServletRequest)
val httpResponse = response as HttpServletResponse
val url = httpRequest.requestURL
val path = httpRequest.requestURI
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
if ("OPTIONS" == (request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return chain.doFilter(request, httpResponse)
}
// public api do not check authorization
if (RestfulPath.isPublic(path)) {
//can not replace request by httpRequest
return chain.doFilter(request, httpResponse)
}
try {
val token = httpRequest.getHeader(Constant.AUTHORIZATION)
if (token != null && authToken(token, httpResponse, httpRequest)) {
return chain.doFilter(httpRequest, response)
}
response(httpCode = HttpStatus.UNAUTHORIZED.value(), errorInfo = BusinessCode.NO_PERMISSION, httpResponse = httpResponse)
return
} catch (e: Exception) {
e.printStackTrace()
response(httpCode = HttpStatus.UNAUTHORIZED.value(), errorInfo = BusinessCode.SYSTEM_ERROR, httpResponse = httpResponse)
return
}
}
}
關(guān)鍵代碼:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
if ("OPTIONS" == (request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return chain.doFilter(request, httpResponse)
}