Asp razor page return 400 code when POST form from Iframe

Viewed 1611

I am trying to post a form from an Iframe. But I am getting 400 error and I don't know why. In the iframe it shows the GET requests and I also set "X-Frame-Options", "ALLOW-FROM ... in the GET and POST method headers.

Here is the request:

Host: localhost:52136
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://localhost:52136/
Content-Type: application/x-www-form-urlencoded
Content-Length: 796
Connection: keep-alive
Upgrade-Insecure-Requests: 1

And the response:

HTTP/1.1 400 Bad Request
Server: Kestrel
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcR2VydmlsIERvdWJhbFxzb3VyY2VccmVwb3NcQWNvbXBhIGNoYXJ0XE9ubGluZUFnZW5jeQ==?=
X-Powered-By: ASP.NET
Date: Tue, 18 Dec 2018 20:41:55 GMT
Content-Length: 0

When I submit the same form directly from the same url in the browser, I dont get any error.

How to fix it in the iframe?

2 Answers

I encountered same error while using a Asp.net core app (Razor Pages) in Iframe of SharePoint Online site.

Solution:

Add following configuration in Startup.cs file of your asp.net core app. (you may have to add a reference of Microsoft.AspNetCore.Mvc)

Step 1

Enable Content Security Policy to add Parent URL to trusted CORS domains.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>    
    {
        context.Response.Headers.Add("Content-Security-Policy", "frame-ancestors https://mysharepointparentsite.sharepoint.com/");
        await next();
    });
}

Step 2 Enable Ignore Anti Forgery Token validation.

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddRazorPagesOptions(_options =>
    {
        _options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
    });
}

Also, you need to check whether you have not done code for CSRF prevention like below:

options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); in startup file().

This spent 5 hours to find as I tried with JSONP, CORS, and CSRF.

Related