我有一个扩展 WebSecurityConfigurerAdapter
的 WebSecurityConfiguration
。在其中,我生成 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 + "'"));
}
我想从 Controller 类之一访问此哈希值,但由于 WebSecurityConfiguration
未实例化,我只能对它进行静态引用,这是行不通的。
如何直接访问此类或在 WebSecurityConfiguration
和 Controller 之一之间传输信息?
最佳答案
我能够使用此代码运行它。
@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(); }
}
在 Controller 类中,我通过以下方式访问它:
@RequestMapping(value="/", consumes=ALL) public String index(@RequestAttribute("nonce") final String nonce) throws Exception;
关于java - 静态引用 WebSecurityConfigurerAdapter 来获取随机 CSP 随机数哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450917/