首页 > 解决方案 > 如何在 Spring Security 中使用哈希指定内容安全策略

问题描述

我正在使用带有 thymeleaf 的 java springboot 应用程序,我想通过 spring security 中的内容安全策略保护我的应用程序免受非持久性 xss 的影响。现在,在我的前端,所有按钮都不起作用,因为我已经放置了 javascript 来对它们进行休息调用。以下是我的安全配置:

    @Override
protected void configure(HttpSecurity http) throws Exception {

    http.requiresChannel().anyRequest().requiresSecure().and().authorizeRequests().antMatchers("/login","/css_general/**","/css_page_specific/**","/**/*.js","/**/*.css")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and().formLogin(form -> form
            .loginPage("/login")
            .defaultSuccessUrl("/index.html")
            .failureUrl("/login?error=true")
        )
        .sessionManagement().invalidSessionUrl("/login")
        .and()
        .httpBasic()
       .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("JSESSIONID")
            .permitAll()
            .and()
            .cors().disable()
            .headers()
            .xssProtection()
            .and()
            .contentSecurityPolicy("default-src 'self'");

我得到以下信息:

Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-bzTE78wYOlzPtHKiZ2sKJr4A09DavGERaFsjDU2pdq8='), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

如果我使用 script-src 则看不到上述错误,但我仍然无法登录。如何添加加密/sha-256 以便 thymeleaf 和我页面上的后续内联脚本工作,但我仍然受到 XSS 的保护?我想两全其美:受到 XSS 的保护以及不必对 thymeleaf/我的 javascript 进行更改。我是否需要创建一个执行 sha-256 的辅助函数,并将该函数放在内容安全策略中?有人可以举个例子吗?

标签: javaspringspring-securitythymeleafxss

解决方案


推荐阅读