Aspnetcore: Blazor server app with authorization, after scaffold identity - logout not working

Created on 12 Dec 2019  路  17Comments  路  Source: dotnet/aspnetcore

In blazor server app with authorization, after scaffold identity into an MVC project with authorization, user can't logout from blazor ( LoginDisplay.razor ).
When user click on logout button in LoginDisplay.razor, it makes bad request

Request URL:https://localhost:5001/Identity/Account/LogOut
Request Method:POST
Remote Address:127.0.0.1:5001
Status Code:400 ( Bad Request)
Version:HTTP/2.0

after this bad POST request :

  • no redirection to another page
  • user stil logged in
  • blazor disconected
  • complete white document is rendered.

Using this documentation.
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=netcore-cli#scaffold-identity-into-an-mvc-project-with-authorization

To Reproduce

  1. dotnet new blazorserver --auth Individual
  2. create new user for testing ( [email protected] / Pass12345! )
  3. login and logout and it's working
  4. install if not already ( dotnet tool install --global dotnet-aspnet-codegenerator --version 3.1.0 )
  5. add package to project | dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 3.1.0
  6. add package to project | dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 3.1.0
  7. do a scaffold | dotnet aspnet-codegenerator identity -dc BlazorScaffoldedIdentity.Data.ApplicationDbContext --force
  8. logout from blazor - not working
  9. using instructions from ScaffoldingReadMe.txt
  10. logout from blazor - not working

    NOTE:

  11. if user go to https://localhost:5001/Identity/Account/Manage , then from _MangeNav.cshtml can succesfuly LogOut from app.

WORKAROUND NUMBER 1:

  1. Add [IgnoreAntiforgeryToken] in "LogOut.cshtml.cs" file

WORKAROUND NUMBER 2:

  1. delete files in areas/pages/account "LogOut.cshtml" and "LogOut.cshtml.cs", and create new file that is like the one before scaffold ( "LogOut.cshtml" )
  2. if not using --force , then Building project ...Build Failed. ( but possibly to specify every file except "LogOut.cshtml" , --files "Account.Register;Account.Login" )
  @page
  @using Microsoft.AspNetCore.Identity
  @attribute [IgnoreAntiforgeryToken]
  @inject SignInManager<IdentityUser> SignInManager
  @functions {
      public async Task<IActionResult> OnPost()
      {
          if (SignInManager.IsSignedIn(User)){await SignInManager.SignOutAsync();}
          return Redirect("~/");
      }
  }

REPOS

and the orginal version with wrong behaviour
https://github.com/sikira/BlazorScaffoldedIdentity/tree/withbug

repo with sample project with workaround
https://github.com/sikira/BlazorScaffoldedIdentity/tree/master

SIDE NOTES:
  1. This behaviour happend in version 3.0.100 and in 3.1.0, but in .Net Core 3.0.100 this is writen in console:
    info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
    Executed endpoint '/_blazor'
    Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executed endpoint '/_blazor'
    info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
    Request finished in 21743.366ms 101
    Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 21743.366ms 101
    info: Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter[1]
    Antiforgery token validation failed. The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken".
    Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken".
    at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext)
    at Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)
    Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter: Information: Antiforgery token validation failed. The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken".
    Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken".
    at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.ValidateRequestAsync(HttpContext httpContext)
    at Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.ValidateAntiforgeryTokenAuthorizationFilter.OnAuthorizationAsync(AuthorizationFilterContext context)
    info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[3]
    Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter'.
    Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.ViewFeatures.Filters.AutoValidateAntiforgeryTokenAuthorizationFilter'.
    info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
    Executing HttpStatusCodeResult, setting HTTP status code 400
    Microsoft.AspNetCore.Mvc.StatusCodeResult: Information: Executing HttpStatusCodeResult, setting HTTP status code 400
    info: Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker[4]

Further technical details

  • ASP.NET Core version 3.1.100

.NET Core SDK (reflecting any global.json):
Version: 3.1.100
Commit: cd82f021f4

Runtime Environment:
OS Name: Windows
OS Version: 10.0.17763
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.100\

Host (useful for support):
Version: 3.1.0
Commit: 65f04fb6db

.NET Core SDKs installed:
3.0.100 [C:\Program Files\dotnet\sdk]
3.1.100 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

  • VS Code 1.40.2

[blazor]
[identity]
[scaffold]
[logout]

area-blazor area-identity bug

Most helpful comment

@pm64 your comment intrigued me to try to investigate more, and i find out that the issue is actually about antiforgery token. Another and better fix would be to put atribute [IgnoreAntiforgeryToken] on top of LogoutModel class in "LogOut.cshtml.cs" file. I've add this fix to orginal issue.

All 17 comments

Thanks for contacting us.
Unfortunately Identity scaffolder doesn't work well with Blazor projects yet. We plan to handle this as part of 5.0 release.

enetstudio tnx for suggestion, but it didn't work for me on this issue. This "a" element is a GET request, not POST, and i don't see how it would work without further modification on logout page. Maybe i'm missing something.

@sikira have you been able to determine WHY your workaround is necessary? Without your workaround, in the scaffolded Logout.cshtml.cs, placing breakpoints everywhere shows that no code associated with this page is ever executed. Why is this? Also, a blank page is rendered (instead of the "not found" behavior), which is equally perplexing, since the framework is acknowledging that the page exists. Do you have any insight into this behavior? I'm baffled as to why OnPost() in the scaffolded Logout.cshtml.cs is not executed.

@pm64 your comment intrigued me to try to investigate more, and i find out that the issue is actually about antiforgery token. Another and better fix would be to put atribute [IgnoreAntiforgeryToken] on top of LogoutModel class in "LogOut.cshtml.cs" file. I've add this fix to orginal issue.

@sikira amazing catch!! This is precisely the issue, You have saved me many hours of hair-pulling and cursing. Huge thanks!

@sikira you might be interested in another issue I discovered in the ASP.Net Core Identity scaffolder: https://github.com/dotnet/aspnetcore/issues/18200

@sikira It works perfectly for me

@mkArtakMSFT Is there any guidance available for how to customize Blazor/Identity without scaffolding? Specifically, I want to add username to the login page. (figured this out)

While we wait for 5.0, what's the best practice?

@MisinformedDNA could you please tell, how did you create custom login page for blazor server? I'm struggling to figure it out. I tried to just use SignInManager.PasswordSignInAsync in my form, but it seems it's for Http based authentication like in MVC projects, not for blazor.

Maybe you inherited scaffolded form somehow or used another SignInManager method?

@sikira Thank you so much for that. That really saved some time for me trying to find out why this was happening.

@mkArtakMSFT I'm able to reproduce this as well with the latest bits.

@javiercn So it looks like what's happening here is the default Blazor Server template adds a custom LogOut.cshtml that has the [IgnoreAntiforgeryToken] attribute, but then when you scaffold in Identity that file gets overridden.

I know we have other places in the Identity scaffolder where it won't scaffold certain files if they already exist. Should we maybe implement that logic more generally? Or is there a way to align the logout logic used by Blazor Server with the default logout logic used by the default Identity UI?

@danroth27 is this what @HaoK is going to help out with?

@mkArtakMSFT I think we need to understand what the fix should be first.

I chatted with @vijayrkn and @javiercn about this. Currently when you say that you want to "Override all files" the Identity scaffolder will happily overwrite existing files. There's an important distinction here between overriding the pages in the default Identity UI, and overwriting files already on disk. Just because you said you want to override a page from the default Identity UI, does not necessarily mean that you want to overwrite an existing page that you already have. The Identity scaffolder already has support for letting you choose which pages you want to override.

It seems like it should be an error if you try to override a page that will result in an existing page getting overwritten. We could also provide an option to force overwriting files if they already exists.

The tooling could help you understand when there are existing files that would get overwritten and let you decide if you want to do that or not.

@HaoK @deepchoudhery

This issue was moved to aspnet/Scaffolding#1287

Was this page helpful?
0 / 5 - 0 ratings