Solved! Go to Solution.
Views
Replies
Total Likes
Hi @ArunJh1 ,
Try below step's:
Step 1: Enable Dispatcher to Pass Dynamic CSP Header
In Dispatcher (Apache HTTPD):
/conf/dispatcher/filters/filters.any
# Allow the CSP header to be passed from AEM
/Header set Content-Security-Policy "script-src 'self' 'nonce-%{CSP_NONCE}e'"
Add to Apache virtual host:
SetEnvIf Request_URI ".*" CSP_NONCE=<%{CSP_NONCE}e>
However, you’ll need to set CSP_NONCE environment variable dynamically from AEM using Sling filters or Servlet Filters.
Step 2: Generate Nonce in AEM Using Servlet Filter
package com.example.core.filters;
import org.apache.commons.lang3.RandomStringUtils;
import org.osgi.service.component.annotations.Component;
import javax.servlet.*;
import java.io.IOException;
@Component(service = Filter.class,
property = {
"sling.filter.scope=request",
"service.ranking=1000"
})
public class CspNonceFilter implements Filter {
public static final String NONCE_ATTRIBUTE = "cspNonce";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String nonce = RandomStringUtils.randomAlphanumeric(16);
request.setAttribute(NONCE_ATTRIBUTE, nonce);
// Add CSP Header
if (response instanceof HttpServletResponse) {
((HttpServletResponse) response).setHeader("Content-Security-Policy",
"script-src 'self' 'nonce-" + nonce + "'");
}
chain.doFilter(request, response);
}
}
<script nonce="${request.getAttribute('cspNonce')}">
console.log('Inline script with CSP nonce');
</script>
Step 4: Make Dispatcher Cache Respect Dynamic Header (Cloud Service Note )
You must avoid full page caching if the CSP nonce is dynamic per request.
Options:
Use Edge-side include (ESI) (Akamai/Fastly/CDN level) for nonce placeholder.
Or: Disable caching for CSP dynamic pages.
Or: use a JS nonce injection solution post-cache (less secure but works if needed).
Step 5: AEM as a Cloud Service Notes
On AEMaaCS, for performance and CSP:
You can use a Page Model approach, or use Sling Dynamic Include (SDI) for injecting the nonce via non-cached include.
Or register a PageHeadFilter and add a nonce meta tag + CSP header centrally.
Sample Output
Header:
Content-Security-Policy: script-src 'self' 'nonce-xYzAbc123QWE78as'
HTML:
<script nonce="xYzAbc123QWE78as">
console.log('Secure script');
</script>
Regards,
Amit
Views
Replies
Total Likes
@ArunJh1 Did you find the suggestions helpful? If you need more information, please let us know. If a response resolved your issue, kindly mark it as correct to help others in the future. Alternatively, if you discovered a solution on your own, we'd appreciate it if you could share it with the community. Thank you.
Views
Replies
Total Likes
Views
Likes
Replies