简体   繁体   中英

Dynamic CSP (Content Security Policy) connect-src in Angular

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM