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

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

问题描述

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

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

这里是我的服务结构:

如果我理解得很好,我必须在NextJS中处理服务器端渲染,所以我知道我必须将来自外部服务器的cookie放到我的NextJS客户端,然后处理服务器端渲染checkings。为此,我假设我必须在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天全站免登陆