spring-security防禦csrf攻擊
阿新 • • 發佈:2021-01-20
技術標籤:javawebspring boot
@Configuration @EnableWebSecurity //啟用web許可權 @EnableGlobalMethodSecurity(prePostEnabled = true) //啟用方法驗證 public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 定義安全策略 */ @Override protected void configure(HttpSecurity http) throws Exception { String casIsEnable = env.getProperty("cas.server.enable"); final MyCallbackFilter callbackFilter = new MyCallbackFilter(config); callbackFilter.setMultiProfile(true); callbackFilter.setSaveInSession(true); if (env.getProperty("app.login.type") != null && env.getProperty("app.login.type").toLowerCase().equals("oauth")) { http.authorizeRequests() .anyRequest().authenticated() .and().exceptionHandling().authenticationEntryPoint(new Pac4jEntryPoint(config, "MyOauthClient")) .and().addFilterBefore(callbackFilter, BasicAuthenticationFilter.class) .addFilterAfter(new CoreFilter(), BasicAuthenticationFilter.class).cors()// 跨域設定 .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } else { http.authorizeRequests() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(new Pac4jEntryPoint(config, "CasClient")) .and() .addFilterBefore(callbackFilter, BasicAuthenticationFilter.class) .addFilterAfter(new CoreFilter(), BasicAuthenticationFilter.class) .formLogin()// 使用form表單登入 .and() .logout().permitAll() .logoutSuccessUrl(casProperties.getCasServerLogoutUrl()) .and() .cors()// 跨域設定 .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringAntMatchers("/user/getUserInfo"); } }
// @Bean // public FilterRegistrationBean csrfFilter() { // FilterRegistrationBean registration = new FilterRegistrationBean(); // //registration.setFilter(new CsrfFilter(new CookieCsrfTokenRepository())); // registration.setFilter(new CsrfFilter(new HttpSessionCsrfTokenRepository())); // registration.addUrlPatterns("/user/save"); // return registration; // } }
下面注如FilterRegistrationBean不需要了,因為前面csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())。其實內部也是走了csrfFilter過濾器的。
而且一般repository有3種,這裡只介紹2種CookieCsrfTokenRepository和HttpSessionCsrfTokenRepository,CookieCsrfTokenRepository就是把token放在cookie種,然後前端直接從
cookie上取,HttpSessionCsrfTokenRepository就是把token放到session裡,但是因為前端是不能從session取數的,所以這種方式適用於前後端不分離的專案,如果是前後端分離的專案,則需單獨再出getToken的介面。