使用数据库优先方法在 Blazor WebAssembly 中进行身份验证和授权

Authentication and Authorization in Blazor WebAssembly with Database First Approach

我的问题总结

我的项目比较复杂,但这是我的基本问题。我有一个 Blazor WebAssembly 项目,我只在其中执行基本的 CRUD 操作。

我还有一个小型数据库,假设我有两个 tables UsersRoles。我所做的是以数据库优先的方式创建他们的 classes,通过使用 Scaffold-DbContext 和我 运行 在 Shared 项目上使用这个命令,因为我也想达到这些 class 来自 ServerClient 项目。

当我在创建 Blazor WebAssembly 项目时尝试在身份验证选项卡上使用 Individual User Accounts 时,它会在服务器中创建数据模型。这意味着我无法从 Client 项目访问我的 table。他们需要在 Shared。它也是基于代码优先的。我不想使用迁移。


我试过的

我试图做的是用 Individual User Accounts 个项目创建一个几乎相同的项目,但是我的 Users class 继承了 IdentityUser 而我的 DbContext 继承了 ApiAuthorizationDbContext 但问题从这里开始。

我无法从 NuGet 添加 ApiAuthorization 包,因为它说共享项目与 .NetStandard 2.1 不兼容。

更改共享项目的标准也没有用。


一些问题


我的目标

我想授权 [Authorize] 属性 的用户。由于我无法完成注册,因此无法继续。

使用 2 个 DbContext。标识表(您的或 ASP.NET)不应是共享或客户端项目的一部分。

I want to authorize users with [Authorize] property

真正的授权发生在服务端,客户端没有什么是安全的。您看过模板中完整的(基于 JWT 的)实现了吗?

  • 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)

不,Identity 需要基础 class。而且您的客户端应用程序不需要(也不应该看到)它的大部分属性。

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

这是最好的方法。请注意,您可以为 1 个物理数据库设置 2 个 DbContext。

Link 在需要时通过简单的 UserId(无导航 属性)发送给用户。