服务器身份验证后如何为前端提供JSON Web令牌? [英] How to provide frontend with JSON web token after server authentication?
问题描述
到目前为止,我只处理服务器渲染的应用程序,在这些应用程序中,用户通过用户名/密码或使用OAuth提供程序(Facebook等)登录后,服务器仅在重定向到相关页面时设置会话cookie.
但是,现在我正在尝试使用更现代"的方法来构建应用程序,其中React处于前端,而JSON API处于后端.显然,此方法的标准选择是使用JSON Web令牌进行身份验证,但是我在弄清楚如何向客户端提供JWT以便可以将其存储在会话/本地存储中或任何地方时遇到麻烦. /p>
更好地说明示例:
-
用户单击链接(
/auth/facebook
)通过Facebook登录 -
用户被重定向并显示Facebook登录表单和/或权限对话框(如有必要)
-
Facebook使用拖曳中的授权码将用户重定向回
/auth/facebook/callback
,服务器将其交换为访问令牌和有关用户的一些信息 -
服务器使用信息在数据库中查找或创建用户,然后创建一个包含用户数据相关子集(例如ID)的JWT
-
???
在这一点上,我只希望将用户重定向到具有JWT的React应用程序的主页(假设为/app
),以便前端可以接管.但是我无法想到一种(优雅的)方式来做到这一点而不会丢失JWT,只能将其放入重定向(/app?authtoken=...
)的查询字符串中-但这会显示在地址栏中,直到我使用replaceState()
或其他方法手动将其删除,对我来说似乎有点奇怪.
真的,我只是想知道这通常是如何完成的,而且我几乎可以肯定我在这里遗漏了一些东西.如果有帮助,服务器是Node(带有Passport的Koa).
为明确起见,我想问的是,使用Osport进行OAuth重定向流程后向客户端提供令牌(以便可以保存)的最佳方法是什么.
我最近遇到了同一问题,并且在这里或其他地方找不到解决方案,所以写了 解决方案
I recently ran across this same issue, and, not finding a solution here or elsewhere, wrote this blog post with my in-depth thoughts.
TL;DR: I came up with 3 possible approaches to send the JWT to the client after OAuth logins/redirects:
- Save the JWT in a cookie, then extract it on the front-end or server in a future step (eg. extract it on the client with JS, or send a request to the server, server uses the cookie to get the JWT, returns the JWT).
- Send the JWT back as part of the query string (which you suggest in your question).
- Send back a server-rendered HTML page with a
<script>
tag that:- Automatically saves the embedded JWT to
localStorage
- Automatically redirects the client to whatever page you like after that.
- Automatically saves the embedded JWT to
(Since logging in with JWTs is essentially equivalent to "saving the JWT to localStorage
, my favorite option was #3, but it's possible there are downsides I haven't considered. I'm interested in hearing what others think here.)
Hope that helps!
这篇关于服务器身份验证后如何为前端提供JSON Web令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!