Search code examples
asp.net-coreblazorasp.net-core-identityblazor-webassembly

Authentication and Authorization in Blazor WebAssembly with Database First Approach


Summary of my problem

My project is more complex but here is my problem at very basic level. I have a Blazor WebAssembly project where I do just basic CRUD operations.

I also have a small database and lets say I have two tables Users and Roles. What I do is to create their classes in Database-First fashion, by using Scaffold-DbContext and I run this command on the Shared project because I also want to reach to these classes from both Server and Client projects.

When I try to used Individual User Accounts on Authentication tab when creating a Blazor WebAssembly project, it creates the data models in the server. Which means I cannot access to my tables from Client Project. They need to be in Shared. Also it is Code-First based. I don't want to use migrations.


What I tried

What I tried to do is to create an identical -almost- project with Individual User Accounts projects but my Users class inherits IdentityUser and my DbContext inherits ApiAuthorizationDbContext but problem starts here.

I cannot add ApiAuthorization package from NuGet because it says Shared project does not compatible with .NetStandard 2.1.

Also changing Shared project's standard didn't work.


Some Questions

  • Can't I just add my users table on the Shared and use Identity from that table? (Since it's just a single table of rather larger database)

  • Do I need two databases for this? One for Identity, one for rest of the application?

  • Do I need to use Identity for Authentication & Authorization? What else can I use? Or Can I use a custom one where I can use it as I described earlier (Having models in Shared project)


My Goal

I want to authorize users with [Authorize] property. Since I cannot accomplish the registration, I cannot proceed.


Solution

  • Use 2 DbContexts. The Identity tables (yours or ASP.NET) should not be part of the Shared or Client projects.

    I want to authorize users with [Authorize] property

    The real authorization happens on the server, nothing in the client is safe. Have you looked at the complete (JWT based) implementation in the template?

    • Can't I just add my users table on the Shared and use Identity from that table? (Since it's just a single table of rather larger database)

    No, Identity needs the base class. And your client app doesn't need (and shouldn't see) most of its properties.

    • Do I need two databases for this? One for Identity, one for rest of the application?

    That is the best way. Note that you can have 2 DbContexts for 1 physical Db.

    Link to the User wit a simple UserId (no Nav property) when needed.