How to restrict angular app from being loaded in iframe

3.3k views Asked by At

I am trying to restrict angular app from being loaded in iframe but not able to do that.

I have angular app running independently from API. API is implemented using .net core 2.1 and UI client using angular 7.

I tried below different options in api middleware but none is working in my case:

#1

    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("Content-Security-Policy", "frame-ancestors 'none'; " +
            "script-src 'self'; " +
            "style-src 'self'; " +
            "img-src 'self'");
        await next();
    });

#2

    app.Use(async (context, next) =>
    {
        context.Response.Headers.Add("X-Frame-Options", "DENY");
        await next();
    });

I am getting above added values in response header but still able to load application in iframe in other application.

Is there anything I am missing here at angular/API side?

Added more information

We used IIS to host angular app. Also tried below setting in web.config in angular app:

<httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="DENY" />
    </customHeaders>
</httpProtocol>
2

There are 2 answers

1
Célian Garcia On

Why not serving the headers in the server side of your UI ? What are you using to serve your angular app ? is it nginx ? apache httpd ? Both of them provide the ability to return headers on every requests

Edit : As you are using IIS indeed it seems to be

<system.webServer>
  ...

  <httpProtocol>
    <customHeaders>
        <add name="X-Frame-Options" value="sameorigin" />
    </customHeaders>
  </httpProtocol>

  ...
</system.webServer>

But I don't know more about it

Sources: https://www.keycdn.com/blog/x-frame-options

0
Tim On

Generally, when you have a separated Front end technology than the one used in the back end, you will use a dedicated server for the front end, and another for the backend.

You could use NGINX or NODEJS to serve your Angular application and use their proxy features to route the frontend call to you API.

And launch your ASP.NET Core application via the executable/visual studio.

By the way, Angular natively provides a seed configured with Webpack to server your application with reverse proxy support.

Example with ANGULAR https://medium.com/better-programming/setup-a-proxy-for-api-calls-for-your-angular-cli-app-6566c02a8c4d

Example with NGINX : https://spencerfeng.medium.com/setup-reverse-proxy-for-api-calls-for-your-angular-application-with-node-js-62321f0defb5

Summary

DEV:

  • Configure Angular proxy feature.
  • Start your angular app with ng serve
  • Start your API with Visual Studio

PROD:

Configure your webserver to act a reverse proxy and serving the angular app.

Host your ASP.NET Core API in IIS or inside a docker container.