首页 > 解决方案 > 如何巧妙地配置 Spring WebSecurity

问题描述

我目前正在使用 Spring Security 设置反向代理安全域,其想法是默认情况下在所有请求上都需要不记名令牌,除了一些例外,例如注册等。目前我的配置功能看起来像如下:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Ant 匹配器非常有用,但您必须单独传递所有 URL。有没有办法让我传入一个字符串数组,以便我可以将配置分开?

标签: springspring-bootspring-security

解决方案


http.cors().and().csrf().disable().authorizeRequests()
        .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()

在上面的代码antMatchers中也将接受字符串数组。下面是 spring security 中 anyMatcher 方法的实现4.2.3.RELEASE。根据方法签名,您应该能够传递包含所需路径的字符串数组。

    /**
 * Maps a {@link List} of
 * {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher}
 * instances that do not care which {@link HttpMethod} is used.
 *
 * @param antPatterns the ant patterns to create
 * {@link org.springframework.security.web.util.matcher.AntPathRequestMatcher} from
 *
 * @return the object that is chained after creating the {@link RequestMatcher}
 */
public C antMatchers(String... antPatterns) {
    return chainRequestMatchers(RequestMatchers.antMatchers(antPatterns));
}

如果您深入研究实现,spring 正在将此 args 转换为所有路径的 ArrayList。

此外,还有另一种方法。WebSecurityConfigurerAdapter如果要扩展 spring 的类,要忽略不应由 spring security 保护的路径,请再次覆盖相同的方法。

@Override
public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("path":);
}

我想这种方式很整洁。


推荐阅读