交易令牌的用户名和密码

Trade username and password for a token

我有一个 Node.js 应用程序,它在 MongoDB 前面提供了几种不同的路线。我需要确保只有经过身份验证的请求才能访问这些路由。

理想情况下,我想对其进行设置,以便用户名和密码进入 API,并在响应中返回一个令牌。我不介意自己管理 MongoDB 内的令牌,但我需要确保我们返回的令牌可以发出经过身份验证的请求。我不想强迫用户每次都发送他们的凭据,只是令牌。

看了几天关于护照的资料,目前有307攻略。我在这里描述的是哪种策略?

Which strategy am I describing here?

您描述的是 Local Strategy

根据他们的描述:

This module lets you authenticate using a username and password in your Node.js applications.

I don't want to force the user to send their credentials each time, just the token.

Passport 身份验证策略只提供各种方式来验证(或简单来说登录)用户,而不是如何保持登录。登录持久性通常通过用户会话完成。

解决此问题的一种方法是将本地策略与 express session middleware 相结合。两者的结合允许一个相当简单的身份验证系统,它要求用户登录一次然后保持会话。

In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.

Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.

PassportJS docs举例说明如何实现。

为此,您应该更喜欢为登录生成 JWT 令牌,然后使用该令牌始终对用户操作进行身份验证。

实施这种令牌登录系统需要以下步骤

  1. 登录时生成令牌
  2. 验证何时提供令牌并使用解码数据识别用户

使用适当的中间件以保护您的 api。

这是您可以关注的 link:

https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens