c# - 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.
解决方案
首先,一般来说,当我们使用 JWT 认证时,工作流程如下:
- 客户端向服务器发送请求(包含用户信息,例如:名称和密码)以获取令牌
- 服务器接收用户信息并检查授权。如果验证成功,服务器会生成一个 JWT 令牌。
- 客户端接收令牌并将其存储在本地某处。
- 客户端在未来的请求中发送令牌。
- 服务器从请求标头中获取令牌,通过使用 a) 来自令牌的标头 b) 来自令牌的有效负载 c) 服务器已经拥有的密钥再次计算哈希。
- if ("newly computed hash" = "hash come in token"),token有效,否则被调和或无效
配置您的应用程序后,将使用身份和 JWT 身份验证。当用户登录时,您可以将用户信息发送到服务器端并检查当前用户是否有效,然后生成 JWT 令牌,在客户端您可以将令牌存储在 Web 存储中。之后,当您想通过将此令牌传递到身份验证 HTTP 标头来访问资源时。更多详细信息请参考以下文章:JWT Authentication In ASP.NET Core
推荐阅读
- sql - 在 Postgresql 中的两个表上使用横向
- javascript - Firebase/JS - 在加载页面之前触发 JavaScript?
- node.js - 如何将 JSON 对象作为文件发送
- javascript - 在 Ionic Angular 应用程序中从 Firebase 数据库查询的“Where”子句放在哪里?
- reactjs - 如何在 redux 中获得以前的状态?
- php - 如何编辑我的代码以将小数分隔符从点更改为逗号。(文本包含在输出中)
- qlikview - QMC 服务器问题:不允许打开 QVS@servername 的任何选项卡
- database - 在 MySQL 中的到期日期前 1 个月从数据库发送电子邮件
- sql - 如何知道 a 列是否包含所有 NULL
- sql - 暂存表查询以表形式返回