Using just Spring Security CSRF feature

雨燕双飞 提交于 2019-12-11 03:04:29

问题


I'd like to use just the Spring Security's CSRF feature without any of the other authentication/authorization features since those features are provided by a third party provider for me. If this can be done, how do I tell Spring not to look out for any authentication manager with its dependent beans and just intercept all URLs, and add the csrf token.


回答1:


I got the CSRF feature working by making the following changes/additions. Also, I used the <form:form> tag in my jsp to leverage the automatic insertion of the token by Spring.

jars added:

spring-security-acl-4.0.0.RC1.jar
spring-security-config-4.0.0.RC1.jar
spring-security-core-4.0.0.RC1.jar
spring-security-taglibs-4.0.0.RC1.jar
spring-security-web-4.0.0.RC1.jar

web.xml additions:

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

New java file added:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class TgtWebSecurityConfigureAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().permitAll();
    }
}

Marco - With just the CSRF filter, it does not work.




回答2:


You could try this:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().permitAll();
    }

CSRF is enabled per default. You can than make use of (for example in thymeleaf):

<meta name="_csrf" value="dummy" th:value="${_csrf.token}" />



回答3:


I'd personally avoid to include the Spring Security Filter chain if you intend to use only its CSRF protection. Without proper configuration, you will end up burdening your application with unnecessary logic.

The CSRF protection in Spring Security is offered by the org.springframework.security.web.csrf.CsrfFilter servlet Filter.

By default the filter stores the expected CSRF token on the HttpSession.

You can easily implement something similar or attempt at declaring this filter only in your servlet filter chain / web.xml.



来源:https://stackoverflow.com/questions/28209344/using-just-spring-security-csrf-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!