stavroskasidis / BlazorWithIdentity

A project template for a blazor hosted app using cookie based authentication with ef core identity.
MIT License
458 stars 106 forks source link

Does it work with Blazor Server? #17

Closed mysteryx93 closed 4 years ago

mysteryx93 commented 4 years ago

Does this approach work with Blazor Server? There are implementation differences.

One thing I don't understand... where is the login token actually being stored?

stavroskasidis commented 4 years ago
  1. You don't have to do all that for server side Blazor, authentication there works the same way it would work for an Mvc or razor pages app. You just add your authentication in startup and decorate your pages with Authorize

  2. This code sample uses aspnet identity, which uses cookies to store the login info. The cookies then are automatically included in http requests to the server. The server authentication middleware checks the cookies to see if you are authenticated or not.

mysteryx93 commented 4 years ago

but Blazor doesn't allow for the use of cookies... Microsoft also officially says to use plain Razor page instead of Blazor for login. How do you return the cookie via Blazor?

stavroskasidis commented 4 years ago

Blazor Server supports the same authentication as mvc/razor pages. It supports identity/cookies out of the box, I have done it in production. Sure, you may need a controller or a razor page to create the cookie, but it works. Everything is running on the server and it is using the same authentication/authorization middlewares.

In a production project we have @attribute [Authorize] in the _Host.razor page and a different razor page for login. So the whole blazor app is behind authorization, and ofc you can also add @attribute [Authorize(Role = "Admin"] to blazor pages that you want to use roles/policies and stuff.

mysteryx93 commented 4 years ago

In production you have a Razor login page, yes that's how it's normally done.

But in this project, the login is a Blazor page, so how does it set the cookie? AFAIK the only way to set cookies is via JS interop... unless Blazor WebAssembly works differently.

stavroskasidis commented 4 years ago

Login from blazor calls the AuthorizeController, Login method that calls await _signInManager.SignInAsync(user, parameters.RememberMe); which actually writes a set-cookie header in the response. Then the browser automatically sees this header in the response and creates the cookie.

mysteryx93 commented 4 years ago

Really? So what I'm getting is that WebAssembly supports cookie creation but not Blazor Server unless using JS interop. Thanks!

neozhu commented 1 year ago

@mysteryx93 I have implemented it. for server side blazor application base on cookie authentication. you can refer to https://github.com/neozhu/CleanArchitectureWithBlazorServer