Allowing localhost api request without Removing Content-Security-Policy

Issue

I recently discovered electron and used it to create a windows app for my ionic-angular webapp.
I want to make API calls to a localhost API.
Until now I have been just deleting the Content Security Policy like this:

//before
export function setupContentSecurityPolicy(customScheme: string): void {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          electronIsDev
            ? `default-src ${customScheme}://* 'unsafe-inline' devtools://* 'unsafe-eval' data:`
            : `default-src ${customScheme}://* 'unsafe-inline' data:`,
        ],
      },
    });
  });
}


//after
// Set a CSP up for our application based on the custom scheme
export function setupContentSecurityPolicy(customScheme: string): void {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
      },
    });
  });
}

which works just fine for testing but it obviously is only a temporary solution.

The only thing I achieved by editing the Content Policy is stopping my app from getting the Ionic CSS stylesheets.

How would I go about implementing save/accepted sources in the Policy?
Also do I have to edit the Policy in electron or is there a way to do that in my Ionic-Angular app before compiling?

Solution

I think this should work for you:

export function setupContentSecurityPolicy(customScheme: string): void {
  const domainsWhiteList:string[] = [
    "http://localhost"
    , "https://www.gstatic.com"
    , "https://www.googletagmanager.com"
    , "https://firebase.googleapis.com" //firebase
    , "https://firebaseinstallations.googleapis.com" //firebase
  ];

  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          electronIsDev
          ? `default-src ${customScheme}://* 'unsafe-inline' file://* devtools://* 'unsafe-eval' data: ${domainsWhiteList.join(' ')}`
          : `default-src ${customScheme}://* 'unsafe-inline' file://*                            data: ${domainsWhiteList.join(' ')}`,
        ],
      },
    });
  });
}

Answered By – Miguel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published