【问题标题】:Static reference to WebSecurityConfigurerAdapter to get random CSP nonce hash?静态引用 WebSecurityConfigurerAdapter 以获取随机 CSP 随机数哈希?
【发布时间】:2018-07-05 04:14:45
【问题描述】:

我有一个扩展WebSecurityConfigurerAdapterWebSecurityConfiguration。在其中,我为 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 和其中一个控制器之间传输信息?

【问题讨论】:

    标签: java spring model-view-controller content-security-policy nonce


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2020-07-19
      • 1970-01-01
      • 2016-09-07
      • 2013-06-17
      • 2018-12-14
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多