node.js - 验证 Json Web Token 并在登录后重定向

标签 node.js angularjs authentication cookies

我最近读了Cookies vs Tokens对于 Angularjs 并实现了登录和身份验证部分,以允许用户从登录页面登录。该应用程序设置为将帐户模块(负责登录、帐户注册、个人资料等)作为一个单独的页面,该页面将重定向到主应用程序的 SPA。

成功登录后, token 将作为 JWT 发送回登录页面客户端,并通过 js 设置 sessionStorage/localStorage 值。最后,用户被重定向(也通过 js)到主应用程序。问题是因为我通过 js 重定向无法设置 header ,这显然在加载页面时主应用程序中的 auth 失败(因为我的 auth 中间件高于静态和 auth api 请求)。如果我尝试在表单发布后从服务器重定向,而不是在成功时通过 JSON 返回 token ,则 sessionStorage 将不会如博客文章中所述通过 js 设置。

我提出了几个想法,并希望就哪些想法对最佳实践有益提出意见。

  1. 从服务器设置一个响应身份验证 cookie“仅 http”(我们所有的浏览器要求都允许这样做)cookie,该 cookie 在对主应用程序的下一个请求中读取。然后,cookie 将由服务器读取并允许提供 protected 静态 Assets 。我最初的想法是设置 cookie 违背了在每个请求上使用 Authorization header 的目的,因为有时可以读取 cookie,即使它在第一个 api 请求中被删除也是如此。

  2. 允许在没有身份验证的情况下加载前面提到的静态 Assets (html、css、应用程序 js),并且在第一个内部 API 请求(在应用程序中几乎在加载时立即需要),然后可以通过 Angular 的$http 拦截器设置请求授权 header 。如果发回 401,则同一拦截器可以重定向到登录页面。

我认为第二种方法会更简单,因为只需要将 auth 中间件移动到静态文件中间件下,然后更新 Angular 中的 http 拦截器,但我认为让静态文件能够加载可能是不好的做法然后在事后重定向。感谢任何输入。

最佳答案

针对您的第 1 点

... My initial thought was setting a cookie defeats the purpose of using a Authorization header on every request since there is a time the cookie could then be read even if it's removed on the first api request.

授权 header 的使用并不意味着与 cookie 的使用相互排斥。这个想法是在它最适合单页应用程序和 native 移动应用程序中的问题时使用它。然而,由于它确实依赖于某种客户端存储,最好是 sessionStorage,如果在旧浏览器中使用 sessionStorage 存在问题,建议有时甚至使用 cookie 来存储 token 。因此,只要您使用 cookie 来存储 token 而不是用于身份验证,您就没有达到目的。请参阅后续文章中的第 1 点 https://auth0.com/blog/2014/01/27/ten-things-you-should-know-about-tokens-and-cookies/

If you are wondering "but if I store the token in the cookie I'm back to square one". Not really, in this case you are using cookies as a storage mechanism, not as an authentication mechanism (i.e. the cookie won't be used by the web framework to authenticate a user, hence no XSRF attack)

关于node.js - 验证 Json Web Token 并在登录后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22486472/

相关文章:

node.js - Node FTP : Multiple asynchronous calls inside loop

javascript - AngularJS promise 未定义

javascript - 从外部 Controller 按钮提交表单以进行验证

node.js - 带数组参数的 Mongoose 查询

node.js - 运行 Node 应用程序时带有环境变量的 Docker CMD

asp.net-mvc - 使用 Azure AD 的 MVC 5 无法注销

asp.net-core - 如何更改 Microsoft 身份验证提供商登录的默认回调?

security - CouchDB 中的基本 HTTP 身份验证对于跨 EC2 区域的复制是否足够安全?

javascript - 在 Node.js 中写入文件

angularjs - Angular Stripe - 将 Stripe 支付表单转换为 Stripe 元素