首页 > 解决方案 > How to use DotNet Core 5.0 authentication with Next.js

问题描述

I have a Next.js website I'm working on and a dotnet core API connected to a SQL Server database. I have a login page and intend to create a page to add new users and was wondering how I could do this using dotnet core identity? I added the NextAuth.js package thinking I could utilize it, however it seems to work best if connecting directly to the database and not go through an API.

I managed to return the token to NextAuth.js but I don't know where to go from there. How can I use next-auth to manage the session? Or is there a better way to go about doing this without using NextAuth.js?

My reason for using dotnet core identity is because it already has support for roles and setup is fairly simple and makes authorizing different sections of the API easy. Based on a user's role, they should be authorized to access certain routes or view certain pages.

I tried looking at the following doc from microsoft Intro to auth for SPA, but it's not exactly clear to me how I can manage the session.

标签: c#reactjsasp.net-core.net-corenext.js

解决方案


首先,一般来说,当我们使用 JWT 认证时,工作流程如下:

  1. 客户端向服务器发送请求(包含用户信息,例如:名称和密码)以获取令牌
  2. 服务器接收用户信息并检查授权。如果验证成功,服务器会生成一个 JWT 令牌。
  3. 客户端接收令牌并将其存储在本地某处。
  4. 客户端在未来的请求中发送令牌。
  5. 服务器从请求标头中获取令牌,通过使用 a) 来自令牌的标头 b) 来自令牌的有效负载 c) 服务器已经拥有的密钥再次计算哈希。
  6. if ("newly computed hash" = "hash come in token"),token有效,否则被调和或无效

配置您的应用程序后,将使用身份和 JWT 身份验证。当用户登录时,您可以将用户信息发送到服务器端并检查当前用户是否有效,然后生成 JWT 令牌,在客户端您可以将令牌存储在 Web 存储中。之后,当您想通过将此令牌传递到身份验证 HTTP 标头来访问资源时。更多详细信息请参考以下文章:JWT Authentication In ASP.NET Core


推荐阅读