Spring Security 3.2 CSRF禁用特定URL

ylamdve6  于 11个月前  发布在  Spring
关注(0)|答案(7)|浏览(147)

在我的Spring MVC应用程序中使用Spring security 3.2启用了CSRF。
我的spring-security.xml

<http>
 <intercept-url pattern="/**/verify"  requires-channel="https"/>
 <intercept-url pattern="/**/login*"  requires-channel="http"/>
 ...
 ...
 <csrf />
</http>

字符串
正在尝试为请求URL中包含“verify”的请求禁用CSRF。
MySecurityConfig.java

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

private CsrfMatcher csrfRequestMatcher = new CsrfMatcher();

@Override
public void configure(HttpSecurity http) throws Exception {

    http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);

}

class CsrfMatcher implements RequestMatcher {
    @Override
    public boolean matches(HttpServletRequest request) {

        if (request.getRequestURL().indexOf("verify") != -1)
            return false;
        else if (request.getRequestURL().indexOf("homePage") != -1)         
            return false;

        return true;
    }
}

}


CSRF过滤器验证从“verify”提交的CSRF令牌,当我从http向https提交请求时,抛出无效令牌异常(403)。在这种情况下,我如何禁用CSRF令牌身份验证?

ttp71kqs

ttp71kqs1#

我知道这不是一个直接的答案,但人们(像我一样)在搜索这类问题时通常不会指定spring的版本。所以,由于spring security存在一个方法,让我们忽略一些路由:
以下内容将确保CSRF保护忽略:
1.任何GET、HEAD、TRACE、OPTIONS(这是默认值)
1.我们还显式声明忽略任何以“/sockjs/”开头的请求

http
         .csrf()
             .ignoringAntMatchers("/sockjs/**")
             .and()
         ...

字符串

nnsrf1az

nnsrf1az2#

我希望我的回答可以帮助别人。我发现这个问题搜索 * 如何禁用CSFR的具体网址在Spring Boot *。
我使用了这里描述的解决方案:http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/
这是Spring Security配置,允许我在某些URL上禁用CSFR控件:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    // Build the request matcher for CSFR protection
    RequestMatcher csrfRequestMatcher = new RequestMatcher() {

      // Disable CSFR protection on the following urls:
      private AntPathRequestMatcher[] requestMatchers = {
          new AntPathRequestMatcher("/login"),
          new AntPathRequestMatcher("/logout"),
          new AntPathRequestMatcher("/verify/**")
      };

      @Override
      public boolean matches(HttpServletRequest request) {
        // If the request match one url the CSFR protection will be disabled
        for (AntPathRequestMatcher rm : requestMatchers) {
          if (rm.matches(request)) { return false; }
        }
        return true;
      } // method matches

    }; // new RequestMatcher

    // Set security configurations
    http
      // Disable the csrf protection on some request matches
      .csrf()
        .requireCsrfProtectionMatcher(csrfRequestMatcher)
        .and()
      // Other configurations for the http object
      // ...

    return;
  } // method configure

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {

    // Authentication manager configuration  
    // ...

  }

}

字符串
它与Sping Boot 1.2.2(和Spring Security 3.2.6)一起工作。

bq8i3lrv

bq8i3lrv3#

我使用的是Spring Security v4.1。经过大量的阅读和测试,我使用XML配置禁用了特定URL的CSRF安全功能。

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:util="http://www.springframework.org/schema/util"
             xsi:schemaLocation="
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <http pattern="/files/**" security="none" create-session="stateless"/>

    <http>
        <intercept-url pattern="/admin/**" access="hasAuthority('GenericUser')" />
        <intercept-url pattern="/**" access="permitAll" />
        <form-login 
            login-page="/login" 
            login-processing-url="/login"
            authentication-failure-url="/login"
            default-target-url="/admin/"
            password-parameter="password"
            username-parameter="username"
        />
        <logout delete-cookies="JSESSIONID" logout-success-url="/login" logout-url="/admin/logout" />
        <http-basic />
        <csrf request-matcher-ref="csrfMatcher"/>
    </http>

    <beans:bean id="csrfMatcher" class="org.springframework.security.web.util.matcher.OrRequestMatcher">
        <beans:constructor-arg>
            <util:list value-type="org.springframework.security.web.util.matcher.RequestMatcher">
                <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
                    <beans:constructor-arg name="pattern" value="/rest/**"/>
                    <beans:constructor-arg name="httpMethod" value="POST"/>
                </beans:bean>
                <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
                    <beans:constructor-arg name="pattern" value="/rest/**"/>
                    <beans:constructor-arg name="httpMethod" value="PUT"/>
                </beans:bean>
                <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
                    <beans:constructor-arg name="pattern" value="/rest/**"/>
                    <beans:constructor-arg name="httpMethod" value="DELETE"/>
                </beans:bean>
            </util:list>
        </beans:constructor-arg>
    </beans:bean>

    //...

</beans:bean>

字符串
通过上述配置,我为POST启用了CSRF安全性only| 放|拒绝所有以/rest/开头的URL的请求。

ctrmrzij

ctrmrzij4#

explanate对特定的url模式禁用,对某些url模式启用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;

@EnableWebSecurity
public class SecurityConfig {

    @Configuration
    @Order
    public static class GeneralWebSecurityConfig extends WebSecurityConfigurerAdapter {
        
        
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().ignoringAntMatchers("/rest/**").and()
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/home/**","/search/**","/geo/**").authenticated().and().csrf()
            .and().formLogin().loginPage("/login")
            .usernameParameter("username").passwordParameter("password")
            .and().exceptionHandling().accessDeniedPage("/error")
            .and().sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
        }
    }
}

字符串

qni6mghb

qni6mghb5#

<http ...>
    <csrf request-matcher-ref="csrfMatcher"/>

    <headers>
        <frame-options policy="SAMEORIGIN"/>
    </headers>

    ...
</http>

<b:bean id="csrfMatcher"
    class="AndRequestMatcher">
    <b:constructor-arg value="#{T(org.springframework.security.web.csrf.CsrfFilter).DEFAULT_CSRF_MATCHER}"/>
    <b:constructor-arg>
        <b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
          <b:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
            <b:constructor-arg value="/chat/**"/>
          </b:bean>
        </b:bean>
    </b:constructor-arg>
</b:bean>

字符串
平均值

http
        .csrf()
            // ignore our stomp endpoints since they are protected using Stomp headers
            .ignoringAntMatchers("/chat/**")


标签:https://docs.spring.io/spring-security/site/docs/4.1.x/reference/htmlsingle/

polkgigr

polkgigr6#

对于Spring Security 6,应该使用接受Customizer参数的csrf方法。
示例配置:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf(csrf -> csrf.ignoringRequestMatchers("/somepath", "/other/**"));
    return http.build();
}

字符串

xsuvu9jc

xsuvu9jc7#

Use security=“none”. for e.g. in spring-security-soft.xml

<security:intercept-url pattern="/*/verify" security="none" />

字符串

相关问题