There is no "best" way to do authentication.
(没有“最佳”身份验证方法。)
There are just multiple different ways and you have to decide which fits your situation the best. (只有多种不同的方式,您必须决定哪种方式最适合您的情况。)
First, you need to decide how you're going to deliver your credential which likely depends upon what type of client you're using.
(首先,您需要确定如何交付凭据,这可能取决于您使用的客户端类型。)
- Token in a cookie (often works best for browser access)
(Cookie中的令牌(通常最适合浏览器访问))
- Token in a custom header (often used for programmatic access for APIs)
(自定义标头中的令牌(通常用于API的编程访问))
- Token in query parameter (not as common)
(查询参数中的令牌(不常见))
Once you decide how the token is going to be delivered, you then have to figure out how the client is going to get their token.
(一旦确定了令牌的交付方式,则必须弄清楚客户端将如何获取其令牌。)
This would typically be some sort of form submission that contains credentials (such as username and password) and the return from a successful verification of those credentials would be the token. (这通常是某种形式的表单提交,其中包含凭据(例如用户名和密码),并且成功验证这些凭据后返回的将是令牌。)
To process this form, you'd create a POST request handler in Express and verify the credentials, returning a token if the credentials are valid.
(要处理此表单,您需要在Express中创建POST请求处理程序并验证凭据,如果凭据有效,则返回令牌。)
Then, within Express, you'd create a router that contains the authenticated routes and add some middleware to that router that verifies that a valid token is present on the request before allowing the request to proceed.
(然后,在Express中,您将创建一个包含经过身份验证的路由的路由器,并向该路由器添加一些中间件,以在允许请求继续进行之前验证请求上是否存在有效令牌。)
This will protect all the routes on this router. (这将保护此路由器上的所有路由。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…