首页 > 解决方案 > 如何仅通过配置禁用特定 url 的 spring 安全性?

问题描述

我有一个特定的应用程序 URL - https://baseurl/contextroot。它是一个打包在 Spring Boot 应用程序中的 Angular5 应用程序。我想为除https://baseurl/contextroot/path1之外的所有 url 启用 spring 安全性。

我的应用程序没有用户登录。

根据搜索论坛的结果,我尝试了以下类似的方法。下面的代码甚至没有加载我的应用程序https://baseurl/contextroot并且它返回 403。

错误:(类型=禁止,状态=403)。在请求参数“_csrf”或标头“X-XSRF-TOKEN”上发现无效的 CSRF 令牌“null”。

@Configuration
@EnableWebSecurity
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("/**/path1")
            };

            @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

        http.headers().frameOptions().disable();
        http.csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
         // Disable the csrf protection on some request matches
         .csrf()
         .requireCsrfProtectionMatcher(csrfRequestMatcher);

        return;
    } // method configure
}

此外,我的应用程序将是一个子应用程序,加载在 iframe 中,我想只允许某些 url 加载我的应用程序,我找到了添加标头编写器的选项,但我无法像下面这样工作。

http.headers().frameOptions().disable();
http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(
        new WhiteListedAllowFromStrategy(Arrays.asList("allowed-website-1","allowed-website-2"))));

标签: springspring-securitycsrf

解决方案


你可以尝试这样做。

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
           .antMatchers("/contextroot/path1").permitAll();

    }

推荐阅读