java - 如何在 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 的辅助函数,并将该函数放在内容安全策略中?有人可以举个例子吗?
解决方案
推荐阅读
- html - X轴上的重复标签-charts js
- java - 如果数组的索引等于某个数字或超过该数字,我将如何保存它?
- c - 我怎么知道要为数组分配多少空间?
- wordpress - 使用主题/wordpress 将邮政编码添加到搜索选项
- c++ - c++11 atomic 是否自动解决变量读写的多核竞争?
- d3.js - D3 的 if 语句
- python - 根据字典值和列表创建新矩阵
- lme4 - 随机结构如何影响固定效应的结果?
- php - php命令指向Ubuntu中不同版本的php
- node.js - 当对 localhost 节点应用程序的多个请求时,Google Chrome 将请求一一排队