rest - 如何避免自定义过滤器在 spring-security 中运行不安全的 url

标签 rest spring-security spring-boot

我正在构建一个基于 REST 的 Web 应用程序,我已经成功地对其应用了 Spring Security,但我担心的是我已经添加了一个自定义过滤器

http
        .authorizeRequests()
        .antMatchers("/mypro/userCont/signup").permitAll()
        .and()
        .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
        .httpBasic();

我希望这个过滤器应该只针对安全的 url 而不是不安全的 url 如果它针对非安全的 url 运行那么它不应该打断我在非安全的 url 上获取资源。 我的场景是,如果用户未登录,则应运行安全 url 自定义过滤器,使用以下代码检查 Principal:

Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication();

如果 authnull 用户应该看到默认的 spring security 登录弹出窗口 如果我点击不安全的 url,我应该访问该资源。 谁能帮帮我。

最佳答案

您可以通过配置 WebSecurity 完全跳过特定资源的安全性。在这种情况下,Spring 安全将完全忽略该 URL 模式:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

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

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .addFilter(mycustomFilter)
            .authorizeRequests().anyRequest()
        .and()
            .httpBasic();
    }
}

或者,您可以简单地使用 permitAll() 方法来排除您需要允许匿名访问的那些。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .addFilter(mycustomFilter)
            .authorizeRequests()
                .antMatchers("/not-secured/**").permitAll()
        .and()
            .httpBasic();
    }
}

关于rest - 如何避免自定义过滤器在 spring-security 中运行不安全的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287845/

相关文章:

Spring 循环依赖

java - 通过注释而不是 XML 配置 Spring LdapTemplate 的最佳实践?

.net - 让 WCF 输出 XHTML 的最佳/最灵活的方式是什么?

java - 使用 Spring Security 使 JSF 资源可公开访问

spring-security - Spring安全记住我覆盖perherent_logins表的默认SQL

java - 如何通过 Spring Rest 模板使用原始数据进行发布请求

java - 无法推断基本网址。这在使用动态 servlet 注册或 API 位于 API 网关 swagger 2.10.5 之后时很常见

rest - Feign REST 客户端 : How to get the HTTP status?

java - 自定义响应头 Jersey/Java

json - 使用 VSTS Rest API,如何更新 Markdown 小部件?