java - 静态引用 WebSecurityConfigurerAdapter 来获取随机 CSP 随机数哈希?

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

我有一个扩展 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 + "'"));
    }

我想从 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/

相关文章:

java - Spring Data Mongo - 如何通过@DBRef 字段的 id 进行查询

java - Spring 或 App-Server escape html 无法正常工作 JAVA MVC

java - 我应该如何格式化 3D 引擎的几何实例化过程?

java - 表示 NxN 板的最有效数据结构

java - 我必须在 Spring boot 中使用 POST 方法(Restfull)从 MySQL Db 表中搜索 where 子句中的多个参数?

model-view-controller - 现有的营养成分数据库?

java - 模型 View 同步(或避免同步)

java - 删除以前的字符串条目

java - Hadoop:mapred.LocalJobRunner:MissingResourceException

java - 从两个数据库同步获取结果