【问题标题】:How to ignore Spring Security config for every thing except a pattern如何忽略除模式之外的所有内容的 Spring Security 配置
【发布时间】:2015-03-16 10:16:05
【问题描述】:

我有一个配置为 Spring Boot 应用程序的休息 Web 服务。 我所有的其余网址都有一个基本路径“/api/...”。 我还从我的应用程序中提供静态内容。 我只需要为 Web 服务配置安全性,即以“/api/...”开头但提供其他静态内容而不应用安全性的 URL。

我只见过我们通过以下方式过滤一些 url 模式的示例:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/*");
}

但并非如此......

【问题讨论】:

  • http .authorizeRequests() .antMatchers("/resources/**").permitAll(),这样的配置会绕过安全性,您需要将所有此类静态内容保留在配置为以上。
  • 是的,但我的事情是允许除 antMatchers("/api/**") 之外的所有内容 .. 怎么做?或者正如你所说,我将不得不将我的静态内容限制在一个基本路径中......这是一个约束 na ..
  • .ignoring() // 忽略所有以 /resources/ 或 /static/ 开头的 URL .antMatchers("/resources/**", "/static/**");您可以在逗号分隔列表中添加所有此类静态 url,标准实现中没有其他方法。如果你想要这样的东西,那么你可能需要覆盖 AntPathRequestMatcher 中实现的默认逻辑,它只检查匹配的 url。
  • 感谢用户先生的回复...有没有办法为我的 web 服务基本路径全局应用 Spring 安全性,例如“/api/**”...可能在 servlet 调度程序级别或者就像你提到的那样

标签: spring-security url-mapping


【解决方案1】:

使用HttpSecurity类的antMatcher方法:

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/**");
        // add security constraints for /api/... here
    }

    /* rest of config */
}

【讨论】:

  • 为什么是两个星号?一个还不够吗?
  • @user6708151 一个星号 = 目录中的所有文件/一个级别,两个星号 = 包括子目录/所有级别。
【解决方案2】:

你可以用 regexMatcher 代替 antMatcher,它可以是一个否定模式

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().regexMatchers(XXXXX);
}

回答您的最后一条评论,如果您使用的是最新的 spring 框架和 spring 安全性,请根据配置标准定义以下类和安全性配置。

package org.springframework.security.samples.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

另外,如果您仍然难以开始使用 Spring Security,请查看以下 URL。

http://docs.spring.io/spring-security/site/docs/3.2.6.RELEASE/reference/htmlsingle/#hello-web-security-java-configuration

【讨论】:

  • 我们如何使用 XML 配置来做到这一点?
猜你喜欢
  • 2015-05-02
  • 2011-07-19
  • 2021-01-15
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2016-02-05
相关资源
最近更新 更多