[英]How to enable/disable CSRF in Spring at runtime?
我關注了具有 CSRF if/else 條件的 class。 我從屬性文件中讀取了這個標志,我可以使用 /refresh 端點更改標志值。 :
@Order(-1)
@EnableWebSecurity
public class SomeConfigClass extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
String csrfFlag = somePropertyFile.getCsrfFlag();
if(isCsrfEnable){
http.csrf()....some other code
}else {
http.csrf().disable();
}
}
}
問題:所以當我調試代碼時,我知道這個 class 只在 Spring 容器啟動時調用一次。 之后 if 將不會被調用。 因此,即使在將 CSRF 標志更改為 false 之后,打算關閉 CSRF 標志,也不會工作,並且 CSRF 檢查將在那里。
為避免這種情況,我需要重新啟動/重新暫存應用程序,以便容器從屬性文件中獲取新配置,這可能會導致應用程序停機。 任何人都可以更好地解決這個問題嗎?
目標:CSRF 禁用/啟用標志應該被外部化。 可以切換標志並啟用/禁用 CSRF,而無需重新啟動/重新暫存應用程序。
您需要使用 csrf 保護匹配器來實現相同的功能。
您需要編寫 CSRFProtectionMatcher。
http.csrf().requireCsrfProtectionMatcher(new CustomCsrfProtectionMatcher())
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
自定義CsrfProtectionMatcher.java
public class CustomCsrfProtectionMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
//based on the logic..
//You can store flag in DB or properties or XML File
//Please note that for every request this flag will be checked.You can choose a
//better way to implement this
return true/false;
}
}
我個人建議保留 app.properties,而不是按請求檢查它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.