Spring Security多个url规则集不能一起工作 [英] Spring Security multiple url ruleset not working together

查看:82
本文介绍了Spring Security多个url规则集不能一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTTP Spring安全配置,当我注释掉每个方面时它似乎有用,但是当我将Spring Security规则组合在一起时它不起作用,所以我知道问题不在于 regexMatcher antMatcher 但组合应用规则。

I have an HTTP Spring Security configuration that appears to work when I comment out each individual aspect but it doesn't work when I combine the Spring Security rules together, so I know the problem is not with the regexMatcher or the antMatcher but with the rules applied in combination.

这是我的Spring Security类:

Here is my Spring Security class:

package com.driver.website.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.security.AccessControlContext;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${widget.headers.xframeoptions.domains.allowed}")
    private String allowedXFrameOptions;

    @Value("${widget.headers.origins.allowed}")
    private String allowedOrigins;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off

        http.exceptionHandling().accessDeniedPage("/login")
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/myaccount", true).permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/**").permitAll();

        http.regexMatcher("^((?!(/widget|/assistedSearch)).)*$")
                .headers().frameOptions().disable()
                .regexMatcher("^((?!(/widget|/assistedSearch)).)*$")
                .headers()
                .xssProtection()
                .contentTypeOptions()
                .addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "SAMEORIGIN"));

        http.antMatcher("/widget")
            .headers()
            .frameOptions()
            .disable()
            .antMatcher("/widget")
            .headers()
            .addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "ALLOW-FROM " + allowedXFrameOptions));

        http.requestMatchers().antMatchers("/assistedSearch", "/widget")
            .and()
            .headers()
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", allowedOrigins))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "GET, POST"))
            .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "Content-Type"));

        // @formatter:on
    }
}

规则应该是......

The rules should be...


  • 对于所有网址而不是/ widget和/ assistedSearch我们应该添加SAMEORIGIN X-Frame -Options header

  • 对于 / widget 端点,我们应该添加X-Frame-Options:ALLOW-FROM header

  • 对于 / widget / assistedSearch 端点,我们应该添加 Access-Control-Allow-Origin Access-Control-Allow-Methods Access-Control-Allow-Headers 标题

  • For all urls but not /widget and /assistedSearch we should add the SAMEORIGIN X-Frame-Options header
  • For the /widget endpoint we should add the X-Frame-Options: ALLOW-FROM header
  • For the /widget and /assistedSearch endpoints we should add the Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers headers

正如我上面提到的,如果我注释掉对于所有网址规则集然后其他两个协同工作,但使用对于所有网址规则取消注释没有标题出现。

As I mentioned above if I comment out the For all urls ruleset then the other two work in unison, but with the For all urls rule uncommented none of the headers appear.

有没有人知道为什么会这样?如何在Spring Security中添加多个规则集并使用新规则覆盖现有规则集?​​

Does anyone have any ideas why this might be? How do you add multiple rulesets in Spring Security and override existing rulesets with new ones?

我试过

http.antMatcher("/widget")
    .headers()
    .frameOptions()
    .disable()

这似乎再次对它有效但不能合并。

Which again appears to work on it's own but not in combination.

谢谢提前!

推荐答案

您覆盖以前的匹配器,请参阅 HttpSecurity.html #antMatcher

You override your previous matchers, see HttpSecurity.html#antMatcher:


调用 antMatcher(String)将覆盖之前的调用 mvcMatcher(String)} requestMatchers() antMatcher(String) regexMatcher(String) requestMatcher(RequestMatc)她)

Invoking antMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).

HttpSecurity.html #regexMatcher


调用 regexMatcher(String)将覆盖之前的调用 mvcMatcher(String)} requestMatchers() antMatcher(String) regexMatcher(String) requestMatcher(RequestMatcher)

Invoking regexMatcher(String) will override previous invocations of mvcMatcher(String)}, requestMatchers(), antMatcher(String), regexMatcher(String), and requestMatcher(RequestMatcher).

如果您需要多个 HttpSecurity ,见 Spring Security Reference


我们可以配置多个HttpSecurity实例,就像我们可以有多个一样< http> 块。关键是多次扩展 WebSecurityConfigurationAdapter 。例如,以下是具有以 / api / 开头的URL的不同配置的示例。

We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.

@EnableWebSecurity
public class MultiHttpSecurityConfig {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) { 1
      auth
          .inMemoryAuthentication()
              .withUser("user").password("password").roles("USER").and()
              .withUser("admin").password("password").roles("USER", "ADMIN");
  }

  @Configuration
  @Order(1)                                                        2
  public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
      protected void configure(HttpSecurity http) throws Exception {
          http
              .antMatcher("/api/**")                               3
              .authorizeRequests()
                  .anyRequest().hasRole("ADMIN")
                  .and()
              .httpBasic();
      }
  }

  @Configuration                                                   4
  public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

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


这篇关于Spring Security多个url规则集不能一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆