You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security配置CSP Header资源被拦截问题求助

Fixing Content Security Policy (CSP) Issues in Spring Security XML Configuration

Let’s tackle your CSP problem head-on—your console error is giving you the key clue: inline scripts are being blocked, and your previous configurations either didn’t account for inline content properly or missed critical resource directives. Here’s how to resolve this:

1. Understand the Root Cause

The error explicitly states that inline scripts violate your script-src directive. By default, CSP blocks all inline scripts/styles unless you explicitly allow them via:

  • 'unsafe-inline' (quick fix for development, not recommended for production)
  • A nonce (cryptographically random value tied to each request)
  • A hash of the inline script/style content

Additionally, your earlier configurations only targeted single directives (e.g., only script-src or style-src), leaving other resource types (like fonts, images) under the restrictive default default-src 'self' rule—this is why other resources were getting blocked too.

2. Working XML Configuration (Development)

For development, you can use 'unsafe-inline' to quickly unblock inline content while allowing all your required external resources. Here’s a complete, multi-directive configuration that covers all your needs:

<content-security-policy policy-directives="
    default-src 'self';
    script-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://code.jquery.com https://maxcdn.bootstrapcdn.com https://cdn.datatables.net https://cdnjs.cloudflare.com https://maps.googleapis.com https://chart.apis.google.com https://gyrocode.github.io;
    style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com https://cdn.datatables.net https://cdnjs.cloudflare.com;
    font-src 'self' https://fonts.gstatic.com;
    img-src 'self' data: https://*.googleapis.com;
    connect-src 'self'
"/>

Key Notes on This Configuration:

  • default-src 'self': Acts as a fallback for any resource type you don’t explicitly define, allowing local resources by default.
  • script-src: Includes your trusted external script domains plus 'unsafe-inline' to unblock inline scripts.
  • style-src: Covers external style domains and inline styles (many CSS frameworks rely on inline styles).
  • font-src: Adds https://fonts.gstatic.com—this is where Google Fonts actually serves font files, not just the CSS from fonts.googleapis.com.
  • img-src: Allows local images, base64-encoded images (data:), and Google’s image resources (for maps/charts).
  • connect-src: Allows local AJAX requests; add external API domains here if your app makes cross-origin calls.

3. Production-Grade Fix (Avoid 'unsafe-inline')

For production, 'unsafe-inline' is a security risk. Instead, use a nonce to safely allow inline content:

Step 1: Generate a Nonce per Request

Create an interceptor to generate a random nonce for each request and attach it to the request context:

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CspNonceInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Generate a random UUID as the nonce
        String nonce = UUID.randomUUID().toString();
        request.setAttribute("cspNonce", nonce);
        return true;
    }
}

Step 2: Register the Interceptor in XML

Add the interceptor to your Spring MVC configuration:

<mvc:interceptors>
    <bean class="com.yourpackage.CspNonceInterceptor"/>
</mvc:interceptors>

Step 3: Update CSP Configuration to Use the Nonce

Modify your CSP directive to include the nonce instead of 'unsafe-inline':

<content-security-policy policy-directives="
    default-src 'self';
    script-src 'self' 'nonce-${cspNonce}' https://fonts.googleapis.com https://code.jquery.com https://maxcdn.bootstrapcdn.com https://cdn.datatables.net https://cdnjs.cloudflare.com https://maps.googleapis.com https://chart.apis.google.com https://gyrocode.github.io;
    style-src 'self' 'nonce-${cspNonce}' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com https://cdn.datatables.net https://cdnjs.cloudflare.com;
    font-src 'self' https://fonts.gstatic.com;
    img-src 'self' data: https://*.googleapis.com;
    connect-src 'self'
"/>

Step 4: Add the Nonce to Inline Scripts/Styles

In your JSP/Thymeleaf templates, add the nonce attribute to any inline script/style tags:

<script nonce="${cspNonce}">
    // Your inline script code here
</script>

<style nonce="${cspNonce}">
    /* Your inline style code here */
</style>

4. Why Your Previous Configurations Failed

  • Incomplete Directives: You only set script-src or style-src in isolation, leaving other resource types (fonts, images) blocked by the default default-src 'self' rule.
  • Missing Font Domain: Google Fonts loads font files from https://fonts.gstatic.com, not just CSS from fonts.googleapis.com—your earlier configs missed this.
  • Unaccounted Inline Content: Even when you added 'unsafe-inline', if you didn’t include it in both script-src and style-src, one or the other would still block inline content.

内容的提问来源于stack exchange,提问作者UsamaAmjad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:23