Spring Security配置CSP Header资源被拦截问题求助
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: Addshttps://fonts.gstatic.com—this is where Google Fonts actually serves font files, not just the CSS fromfonts.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-srcorstyle-srcin isolation, leaving other resource types (fonts, images) blocked by the defaultdefault-src 'self'rule. - Missing Font Domain: Google Fonts loads font files from
https://fonts.gstatic.com, not just CSS fromfonts.googleapis.com—your earlier configs missed this. - Unaccounted Inline Content: Even when you added
'unsafe-inline', if you didn’t include it in bothscript-srcandstyle-src, one or the other would still block inline content.
内容的提问来源于stack exchange,提问作者UsamaAmjad

