问题
I defined the CSP within meta tags in my Angulars project index.html
file
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
connect-src 'self' https://baseurl1/ https://baseurl2/ https://baseurl3/;
img-src 'self' data: http://baseurl/;
frame-src 'self' blob:;
media-src 'self' https://baseurl/;
script-src 'self' 'unsafe-inline' 'unsafe-eval' http://baseurl/;
style-src 'self' 'unsafe-inline';">
My issue is, that I want to whitelist exactly one more connect-src
dynamically based on a users choice within the application. How to do that since index.html
is a static page?
The url is called from a http service, which reaches out to a standard server interface (different providers). The user can choose his provider, as a result the url changes. There is no known set of possible urls. It would be also fine if I can somehow CSP-ignore all requests which are sent by this service.
回答1:
you can try by making use of Meta component for updating CSP dynamically.
It will be like below which might help you.
import { Meta } from '@angular/platform-browser';
let i = 0;
let tim = setInterval(() => {
let tag = this.meta.getTag('http-equiv=Content-Security-Policy');
if (tag) {
this.meta.removeTag('http-equiv=Content-Security-Policy');
let content = tag.getAttribute('content');
let str = 'connect-src ';
let index = content.indexOf(str);
content = content.slice(0, index + str.length) + "https://baseurl22/ https://baseurl23/ https://baseurl34/ " + content.slice(index + str.length);
this.meta.updateTag({ 'http-equiv': 'Content-Security-Policy', content: content });
} else {
this.meta.addTag({ 'http-equiv': 'Content-Security-Policy', content: 'connect-src \'self\' https://baseurl1/ https://baseurl2/ https://baseurl3/;' });
}
if (i == 1) clearInterval(tim);
i++;
}, 1000);
Demo - https://stackblitz.com/edit/angular-teecck
回答2:
I wouldn't think of Content Security Policy this way, because assuming that browsers will honor CSP meta header this way (I doubt that), it is still better and more secure implantation of Content Security Policy is to use the HTTP response header instead. For a quick reference check content-security-policy.com.
来源:https://stackoverflow.com/questions/59353603/dynamic-csp-content-security-policy-connect-src-in-angular