【问题标题】:How to disable spring security for specific url only via config?如何仅通过配置禁用特定 url 的 spring 安全性?
【发布时间】:2020-09-05 21:04:02
【问题描述】:

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

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

根据搜索论坛的结果,我尝试了以下类似方法。下面的代码甚至没有加载我的应用程序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"))));

【问题讨论】:

    标签: spring spring-security csrf


    【解决方案1】:

    您可以尝试这样做。

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

    【讨论】:

    • 只是为了确认,我不需要对“/contextroot/path1”进行任何 csrf 检查。这也能达到同样的效果?
    • 你不需要任何 csrf。它应该工作。您可以添加此行,以防出现任何错误 http.csrf().disable();
    • 我相信这会禁用 crsf 检查。但我需要启用 CSRF 作为我们安全要求的一部分。我试过这个,它也验证了“/contextroot/path1”的csrf并给出了403错误。 “无法验证提供的 CSRF 令牌,因为找不到您的会话。”
    猜你喜欢
    • 2018-11-22
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2018-08-15
    • 2018-08-02
    • 1970-01-01
    • 2019-11-04
    相关资源
    最近更新 更多