1 package cn.home1.oss.lib.security.starter;
2
3 import cn.home1.oss.lib.security.CsrfHeaderFilter;
4
5 import lombok.SneakyThrows;
6
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.boot.autoconfigure.security.SecurityProperties;
9 import org.springframework.context.annotation.Configuration;
10 import org.springframework.core.annotation.Order;
11 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12 import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
13 import org.springframework.security.web.csrf.CsrfFilter;
14 import org.springframework.security.web.csrf.CsrfTokenRepository;
15
16
17
18
19 @Order(CsrfConfiguration.ORDER_CSRF)
20 @Configuration
21 public class CsrfConfiguration extends SecurityConfigurerAdapter<CsrfConfiguration> {
22
23 public static final int ORDER_CSRF = VerifyCodeConfiguration.ORDER_VERIFY_CODE + 1;
24
25 @Autowired(required = false)
26 private SecurityProperties securityProperties;
27
28 @SneakyThrows
29 @Override
30 public void configure(final HttpSecurity http) {
31
32
33 if (this.securityProperties != null && this.securityProperties.isEnableCsrf()) {
34 http.csrf()
35 .csrfTokenRepository(this.csrfTokenRepository())
36 .and()
37 .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
38 } else {
39 http.csrf()
40 .disable();
41 }
42
43 if (this.securityProperties != null && this.securityProperties.getHeaders().isXss()) {
44 http.headers().xssProtection().xssProtectionEnabled(true);
45 } else {
46 http.headers().xssProtection().disable();
47 }
48 }
49
50 private CsrfTokenRepository csrfTokenRepository() {
51
52
53
54
55 final CookieCsrfTokenRepository repository = new CookieCsrfTokenRepository();
56 repository.setCookieHttpOnly(true);
57 repository.setHeaderName("X-XSRF-TOKEN");
58 repository.setParameterName("_csrf");
59 return repository;
60 }
61 }