我有一個用于IFTTT平臺的簡單 Spring Boot REST 服務。每個授權請求都將包含一個IFTTT-Service-Key帶有我帳戶服務密鑰的標頭,我將使用它來處理請求或回傳 401(未授權)。但是,我只想對選定的端點執行此操作——尤其不是針對任何 Spring 執行器端點。
我已經研究過 Spring Security,使用過濾器,使用HandlerInterceptors,但似乎沒有一個完全適合我想要做的事情。Spring security 似乎附帶了很多額外的東西(尤其是默認用戶登錄),過濾器似乎并不真正匹配用例,并且處理程式攔截器作業正常,但我必須撰寫邏輯代碼來觀察特定的 URL 和忽略別人。
實作我想要做的事情的最佳方法是什么?
作為參考,這是我現在的代碼:
public class ServiceKeyValidator implements HandlerInterceptor {
private final String myIftttServiceKey;
public ServiceKeyValidator(@Value("${ifttt.service-key}") String myIftttServiceKey) {
this.myIftttServiceKey = myIftttServiceKey;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO will have to put logic in to skip this when actuator endpoints are added
String serviceKeyHeader = request.getHeader("IFTTT-Service-Key");
if (!myIftttServiceKey.equals(serviceKeyHeader)) {
var error = new Error("Incorrect value for IFTTT-Service-Key");
var errorResponse = new ErrorResponse(Collections.singletonList(error));
throw new UnauthorizedException(errorResponse);
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
uj5u.com熱心網友回復:
您需要在注冊HandlerInterceptor.
例如:
@EnableWebMvc
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(
new ServiceKeyValidator())
.addPathPatterns("/ifttt/**")
.excludePathPatterns("/actuator/**");
}
}
您可以使用不同的 URL 路徑匹配器來過濾哪些 URL 端點必須由攔截器處理,哪些不是。由于方法addPathPatterns回傳配置它的InterceptorRegistration物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360869.html
