Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
MoxxiManagarm Avatar asked Feb 14 '26 16:02

MoxxiManagarm


1 Answers

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

like image 80
Allabakash Avatar answered Feb 16 '26 06:02

Allabakash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!