我的WebSecurityConfiguration
扩展了WebSecurityConfigurerAdapter
。在其中,我为CSP现时生成随机哈希。
private static final String CSP = "script-src 'self'{nonce}; style-src 'self' https://fonts.googleapis.com/; img-src 'self'; font-src https://fonts.gstatic.com/; object-src 'none'; connect-src 'self'; report-uri http://127.0.0.1:8080/report";
public String CSP_NONCE;
@Override
protected void configure(HttpSecurity http) throws Exception
{
CSP_NONCE = Util.byteArrayToHex(Util.RandomHash()); // Generate a random hash.
http.headers()
.contentTypeOptions().and()
.xssProtection().and()
.cacheControl().and()
.httpStrictTransportSecurity().and()
.frameOptions().and()
.contentSecurityPolicy(CSP.replace("{nonce}", " 'nonce-" + CSP_NONCE + "'"));
}
我想从其中一个控制器类访问这个哈希值,但由于WebSecurityConfiguration
没有被即时化,我只能对它进行静态引用,这不起作用。
如何直接访问此类或在WebSecurityConfiguration
和其中一个控制器之间传输信息?
答案 0 :(得分:1)
我能够使用此代码运行。
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter implements Filter {
@Override public void destroy() { }
@Override public void init (final FilterConfig fc) { }
@Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final String nonce = UUID.randomUUID().toString();
request.setAttribute("nonce", nonce);
((HttpServletResponse)response).setHeader("Content-Security-Policy", "frame-ancestors 'self'; default-src 'self'; script-src 'nonce-"+nonce+"'; object-src 'self'; style-src 'nonce-"+nonce+"'");
if(chain!= null) chain.doFilter(request, response);
}
@Override protected void configure(final HttpSecurity http) throws Exception { http.addFilterAfter(this, CsrfFilter.class).headers().frameOptions().deny(); }
}
在控制器类中,我通过以下方式访问它:
@RequestMapping(value="/", consumes=ALL) public String index(@RequestAttribute("nonce") final String nonce) throws Exception;