我有一個簡單的過濾器來檢查請求是否包含帶有靜態鍵的特殊標頭 - 沒有用戶身份驗證 - 僅用於保護端點。這個想法是如果密鑰不匹配,則會拋出AccessForbiddenException
,然後將映射到帶有註解爲@ControllerAdvice
的類的響應。然而,我無法讓它工作。我的@ExceptionHandler
未被調用。使用@ControllerAdvice創建簡單的servlet過濾器
ClientKeyFilter
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Controller
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
@Controller //I know that @Component might be here
public class ClientKeyFilter implements Filter {
@Value('${CLIENT_KEY}')
String clientKey
public void init(FilterConfig filterConfig) {}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
req = (HttpServletRequest) req
def reqClientKey = req.getHeader('Client-Key')
if (!clientKey.equals(reqClientKey)) {
throw new AccessForbiddenException('Invalid API key')
}
chain.doFilter(req, res)
}
public void destroy() {}
}
AccessForbiddenException
public class AccessForbiddenException extends RuntimeException {
AccessForbiddenException(String message) {
super(message)
}
}
ExceptionController
@ControllerAdvice
class ExceptionController {
static final Logger logger = LoggerFactory.getLogger(ExceptionController)
@ExceptionHandler(AccessForbiddenException)
public ResponseEntity handleException(HttpServletRequest request, AccessForbiddenException e) {
logger.error('Caught exception.', e)
return new ResponseEntity<>(e.getMessage(), I_AM_A_TEAPOT)
}
}
我錯在哪裏?簡單的servlet過濾器可以使用spring-boot的異常映射嗎?
這絕不會發生過濾器。 '@ ControllerAdvice'只對請求到達'DispatcherServlet'有用,'Filter's總是在那之前執行。要麼把這個邏輯放在過濾器中,要麼代替過濾器使用'HandlerInterceptor'。 –
@ M.Deinum,我終於使用了'HandlerInterceptor'。如果您想將其添加爲答案,我會很樂意接受它。 – Opal