question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Update Piranha CMS from 9.1.0 to 10.1.0 - Manager 400 BadRequest

See original GitHub issue

Hi,

I just wanted to upgrade my Piranha version to the latest version. My project ran on .NET 5.0, so I also updated to .NET 6 and the Minimal API. Piranha is running, and my extensions are working fine. However, I can’t perform any operations in the backend anymore. The primary access to the database works because my programmed extensions still have access.

For example, when trying to make a change to a page, I get: “Failed to load resource: the server responded with a status of 400 ()” while when changing or creating users, a JSON error is thrown. Supposedly it is not a valid JSON.

Do you have any idea what could be the reason for this?

All packages are running on 10.1.0.

image

However, the JSON looks valid to me.

JSON
{
	"user": {
		"id": "00000000-0000-0000-0000-000000000000",
		"userName": "asdasd",
		"normalizedUserName": null,
		"email": "asdasd@asasd.de",
		"normalizedEmail": null,
		"emailConfirmed": false,
		"passwordHash": null,
		"securityStamp": null,
		"concurrencyStamp": "9c40dd17-2d04-4e79-b429-ea96533a99f9",
		"phoneNumber": null,
		"phoneNumberConfirmed": false,
		"twoFactorEnabled": false,
		"lockoutEnd": null,
		"lockoutEnabled": false,
		"accessFailedCount": 0
	},
	"roles": [
		{
			"id": "7056d149-3fdc-4e74-86c9-7ec72d9bf450",
			"name": "aaa",
			"normalizedName": "aaa",
			"concurrencyStamp": "6d659fd0-75f1-425b-8089-2a4fa8d701dc"
		},
		{
			"id": "282087c2-19fe-49e5-b7af-8236a4318838",
			"name": "bbb",
			"normalizedName": "bbb",
			"concurrencyStamp": "0e0c4933-1b9e-4d6d-8bfb-b5642bed0d38"
		},
		{
			"id": "5ea95dfa-2eac-4515-bc05-2a2e6893037b",
			"name": "SysAdmin",
			"normalizedName": "SYSADMIN",
			"concurrencyStamp": "55ea375d-b108-4578-ac27-619b2413e577"
		}
	],
	"selectedRoles": ["aaa"],
	"password": "123456!",
	"passwordConfirm": "123456!"
}

I had to merge Program.CS and Startup.CS due to the change to Minimal API. My Programm.cs looks like:

Program.CS
var builder = WebApplication.CreateBuilder(args);
var connectionString = Settings.Item("");

builder.AddPiranha(options =>
{
   options.UseCms();
   options.UseManager();
   options.UseFileStorage(naming: FileStorageNaming.UniqueFolderNames);
   options.UseImageSharp();
   options.UseTinyMCE();
   options.UseMemoryCache();
   options.UseEF<SQLServerDb>(db =>
       db.UseSqlServer(connectionString));

   options.UseIdentityWithSeed<IdentitySQLServerDb>(db =>
           db.UseSqlServer(connectionString),
       io =>
       {

       },
       co =>
       {

       });

   options.UseSecurity(o => o.UsePermission(""));
});

builder.Services.Configure<DataProtectionTokenProviderOptions>(opt =>
{
   opt.TokenLifespan = TimeSpan.FromMinutes(15);
});

builder.Services.AddSingleton<LogService>();
builder.Services.AddSingleton<EmailService>();
builder.Services.AddSingleton<UserService>();

var app = builder.Build();

var system = Settings.Item("");
if (system != "Live" || app.Environment.IsDevelopment() || app.Environment.IsEnvironment("Testing"))
{
   var options = new DeveloperExceptionPageOptions {SourceCodeLineCount = 10};
   app.UseDeveloperExceptionPage(options);
}

app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseCookiePolicy(new CookiePolicyOptions
{
   HttpOnly = HttpOnlyPolicy.Always,
   Secure = CookieSecurePolicy.Always,
   MinimumSameSitePolicy = SameSiteMode.Strict
});

app.UsePiranha(options =>
{
   App.Init(options.Api);

   options.UseManager();
   options.UseTinyMCE();
   options.UseIdentity();
});
App.Blocks.Register<CardBlock>();
App.Blocks.Register<JumbotronBlock>();
App.Blocks.Register<ImageCardBlock>();
App.Blocks.Register<ContactCardBlock>();
app.Run();

Thanks a lot!

Regards

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
vjacquetcommented, May 3, 2022

Because you pass the CookiePolicyOptions to UseCookiePolicy, the options are not resolved so not configured. The hack was never called.

But this is not the problem you have. With your cookie policy settings, the logs show

info: Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter[1]
      Antiforgery token validation failed. The antiforgery token could not be decrypted.

So you have a 400 response with an empty body, which is not a valid response.

I tried to reproduce the framework cookie settings of the antiforgery cookie with Piranha’s manager XsrfCookieName. In my case, the problem was that SameSite was not set to strict mode, which is what the hack does.
In your case, and eventhough your configuration seems to match the default settings for the antiforgery cookie, the problem seems to be with

   HttpOnly = HttpOnlyPolicy.Always,

Piranha’s AuthController.SetAuthCookie sets the cookie to HttpOnly = false and my guess is that it cannot be decrypted because this does not exactly match the “real” settings of the cookie.

Could you please try to replace your CookiePolicyOptions with the following ?

app.UseCookiePolicy(new CookiePolicyOptions
{
    HttpOnly = HttpOnlyPolicy.Always,
    Secure = CookieSecurePolicy.Always,
    MinimumSameSitePolicy = SameSiteMode.Strict,
    OnAppendCookie = context =>
    {
        if (context.CookieName == "XSRF-REQUEST-TOKEN") // Piranha's antiforgery cookie's name
        {
            context.CookieOptions.HttpOnly = false;
        }
    }
});
0reactions
muench-developscommented, May 3, 2022

If you put a breakpoint on the line

context.CookieOptions.HttpOnly = false;

Does it break? If yes, what are the value of the properties of context.CookieOptions ?

Now it works; you were right after the cookie is set, and the whole thing works with your code. Short explanation - I have built my login. If a user has admin rights, he can navigate via a dropdown in the admin area. And there, the user is landed without the cookie set. I have now used the above URL to set the cookie and in conjunction with your code. Best thanks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

XsrfCookie not set as essential · Issue #1829
I used the following workaround to set the SameSite to SameSiteMode.Strict, as it is done for the antiforgery cookie. // HACK: Piranha does...
Read more >
Upgrade to Piranha 10.1 now all saves/posts in ...
NET 6 and upgraded Piranha to 10.1. Everything works except nothing will save from the Piranha manager. All HTTP POST transactions return a...
Read more >
Configuration
The configuration in Piranha can be updated both from the manager interface and from code. To set the configuration in you Startup just...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found