NextJS 使用外部服务器进行身份验证 [英] NextJS auth with an external server

查看:29
本文介绍了NextJS 使用外部服务器进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Nextjs 中使用身份验证,我想知道在 NextJS 中处理身份验证的最佳策略是什么?

I'm working with auth in Nextjs, I'm wondering what is the best strategy to handle authentication in NextJS ?

这是我的服务结构:

如果我理解得很好,我必须在 NextJS 中处理服务器端渲染,所以我知道我必须将 cookie 从我的外部服务器放到我的 NextJS 客户端,然后处理服务器端渲染检查.为此,我假设我必须在 NextJS 服务器和其他服务之间创建连接.在深入探讨该主题之前,我将与您讨论我可用的可能性.NextJS auth 似乎是一个普通开发的主题.

If I understand well I have to handle the server side rendering in NextJS, so I understand I have to put cookies from my external server to my NextJS client, then handle the server side rendering checkings. To do that I assume I have to create connection between the NextJS server and the other services. Before dive more deeper in the subject I would discuss with you about the possibilities available to me. It seems the NextJS auth is a subject in plain development.

任何提示都会很棒,谢谢

Any hint would be great, Thanks

推荐答案

我最近添加了一个 cookie auth 示例,它解释了您在前端尝试执行的操作.

I've recently added an example with cookie auth which explains what you are trying to do on the frontend.

对于后端,除了用于渲染 Next.js 应用程序的服务器之外,您最好将 API 放在外部服务器中.该 API 将处理数据库和令牌创建业务.那么认证的基础是这样的:

For the backend, optimally you'll have your API in an external server, apart from the server you use for rendering your Next.js app. This API will handle the database and the token creation business. Then the basics of the authentication are like this:

  • 客户端POST向服务器发送一个带有用户名和密码的请求.
  • 服务器获取请求并根据收到的数据生成令牌.
  • 如果验证数据一切顺利,服务器将使用令牌进行响应,例如 { token: "secrettoken" }.
  • 客户端收到令牌并将其保存在 cookie 中.如果一切正常,您可以选择将用户重定向到 /dashboard/profile.
  • 客户端在受限页面上将检查 cookie 是否存在,并可选择根据服务器验证它,您在 getInitialProps 中执行最后一部分.如果 cookie 验证失败,您会将用户重定向.
  • The client POST a request with username and password to the server.
  • The server gets the request and generate a token based on the data received.
  • If everything went okay validating the data, the server responds with the token, e.g., { token: "secrettoken" }.
  • The client receives the token and saves it in a cookie. Optionally you redirect the user to the /dashboard or /profile if everything is okay.
  • The client, on restricted pages, will check if the cookie exists and optionally validate that against the server, you do this last part in getInitialProps. If the cookie validation fails you redirect the user away.

我创建了一个小型库来抽象这个逻辑.

I've created a small library to abstract this logic.

所以最后,您的 Next.js 应用程序不应该知道服务器中发生了什么,它只应该接收令牌、保存、验证它,并在出现问题时重定向用户.

So in the end, your Next.js app shouldn't know what's happening in the server, it only should receive the token, save it, validate it, and redirect the user if something is wrong.

您希望如何在外部服务器上处理令牌创建取决于您.

How you want to handle the token creation, on the external server, is up to you.

这篇关于NextJS 使用外部服务器进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆