Search code examples
c#asp.net-mvcasp.net-mvc-5http-headersx-frame-options

Allow frame from different domain with MVC5


I am trying to load google maps into an iframe using MVC5 but I am getting blocked with the error

Refused to display 'https://www.google.com/maps?cid=XXXXX' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

So after much searching, I have tried the following:

  • Adding AntiForgeryConfig.SuppressXFrameOptionsHeader = true; to the Application_Start in global.ascx

  • Creating an attribute (have tried this with and without the setting in global.ascx):

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext != null)
        {
            filterContext.HttpContext.Response.Headers["X-Frame-Options"] = "ALLOW-FROM https://www.google.com";
            base.OnActionExecuted(filterContext);
        }
    }
    
  • trying the attribute OnResultExecuted(ResultExecutedContext filterContext) instead of OnActionExecuted

  • remove it in the web.config:

    <httpProtocol>
        <customHeaders>
            <remove name="X-Frame-Options" />
        </customHeaders>
    </httpProtocol>
    

Is there something I'm missing? how do I get rid of this http header (or at least change it to allow maps)?

Update

I have just checked the headers being sent and they are correct in that they either say

X-Frame-Options: ALLOW-FROM https://www.google.com

Or aren't there at all if I remove the attribute but keep the global.ascx update

Yet when I run the page and see these headers, it is still giving me the SAMEORIGIN error.


Solution

  • As it turns out I have been completely stupid and misunderstood how x-frame-options work. It is to stop your site page being shown on another site through an iframe.

    So the x-frame-options http header that I was getting for SAMEORIGIN was actually coming from google. I thought that as the url was returned from their places api I could just use it, but apparently you can only link to it.

    Creating a new map api key and enabling the maps embed api, I was able to use the place_id instead and call the following url into the iframe:

    https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=place_id:PLACE_ID
    

    And this would show without me getting the header (or doing anything extra to my headers).

    I'll leave this here just in case anyone is as daft as I am