web-dev-qa-db-fra.com

Spring Security 3.2 CSRF désactivé pour des URL spécifiques

Activation de CSRF dans mon application Spring MVC avec Spring Security 3.2.

Mon printemps-security.xml

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

Essayer de désactiver CSRF pour les demandes contenant l'URL de demande 'vérifier'.

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;
    }
}

}

Le filtre Csrf valide le jeton CSRF soumis à partir de 'verify' et une exception de jeton non valide (403) est émise lorsque je soumets une demande à https depuis http. Comment puis-je désactiver l'authentification par jeton csrf dans un tel scénario?

18
Mahesh

Je sais que ce n'est pas une réponse directe, mais les gens (comme moi) ne spécifient généralement pas la version du printemps lorsqu'ils cherchent ce genre de questions. Donc, depuis spring security une méthode existe qui permet d'ignorer certaines routes:

Les éléments suivants garantissent que la protection CSRF est ignorée:

  1. Tout GET, HEAD, TRACE, OPTIONS (par défaut)
  2. Nous indiquons aussi explicitement d'ignorer toute requête commençant par "/ sockjs /"
 http 
 .csrf () 
 .ignoringAntMatchers ("/ sockjs /**")
 .et()
 ...
26
le0diaz

J'espère que ma réponse pourra aider quelqu'un d'autre. J'ai trouvé cette question en cherchant Comment désactiver CSFR pour des URL spécifiques dans Spring Boot

J'ai utilisé la solution décrite ici: http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/

Il s'agit de la configuration de Spring Security qui me permet de désactiver le contrôle du fichier CSFR sur certaines URL:

@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  
    // ...

  }

}

Cela fonctionne avec Spring Boot 1.2.2 (et Spring Security 3.2.6).

5
Andrea

J'utilise Spring Security v4.1. Après beaucoup de lectures et de tests, je désactive la fonctionnalité de sécurité crcf pour des URL spécifiques à l’aide de la configuration xml.

<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>

Avec la configuration ci-dessus, j'active les requêtes crcf security only pour les requêtes POST | PUT | DELETE de toutes les URL commençant par /rest/.

4

Temporairement, cette simple ligne pourrait être utile:

<http pattern="/home/test**" security="none" />
1
zygimantus

Utilisez security = "none" ., Par exemple, dans spring-security-config.xml

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