前端单点登录 (SSO) 是一种用户身份验证和授权方法,使用户能够使用一组登录凭据访问多个应用程序或网站,从而消除重复登录和注册。 这改善了用户体验,降低了维护成本,并增强了安全性。
前端 SSO 实现有几种关键方法:
这种广泛使用的方法利用了浏览器的 cookie 机制。 首次登录中央身份验证页面(例如页面 A)时,会创建一个包含用户数据和过期时间的加密 cookie。 Cookie 的域设置为顶级域(例如 example.com),从而允许在该域内的应用程序之间共享(a.example.com、b.example.com 等)。随后访问其他应用程序会检查此 cookie;如果存在,用户将自动登录;否则,重定向至认证页面。 虽然简单,但这种方法仅限于同域应用程序,面临跨域挑战,并且对 cookie 大小和数量有限制。
示例:设置和检索 cookie。
设置cookie(页面A):
<code class="language-javascript">// Generate an encrypted cookie value const encryptedValue = encrypt(userinfo); // Set the cookie document.cookie = `sso_token=${encryptedValue};domain=.example.com;path=/;max-age=86400;`;</code>
检索和使用 cookie(页面 B):
<code class="language-javascript">// Retrieve the cookie const cookieValue = document.cookie .split(';') .find((cookie) => cookie.trim().startsWith('sso_token=')) .split('=')[1]; // Decrypt the cookie const userinfo = decrypt(cookieValue); // Log in directly login(userinfo);</code>
这种无状态方法涉及在认证中心成功登录后生成加密令牌(包含用户信息和过期时间)。该令牌存储在客户端(localStorage 或 sessionStorage)。 后续应用访问验证token;有效的令牌授予直接访问权限,而无效的令牌则重定向到身份验证中心。 基于令牌的 SSO 支持跨域功能并避免 cookie 限制,但需要额外的存储和网络开销,并且如果令牌被泄露,则会带来安全风险。
示例:存储和验证令牌。
存储令牌(页面 A):
<code class="language-javascript">// Generate the token value const token = generateToken(userinfo); // Store the token localStorage.setItem('sso_token', token);</code>
检索和使用令牌(其他页面):
<code class="language-javascript">// Retrieve the token const token = localStorage.getItem('sso_token'); // Validate the token const userinfo = verifyToken(token); // Log in directly login(userinfo);</code>
此方法利用 OAuth 2.0 的授权代码流程。 首次登录会触发对认证中心的请求,认证中心返回授权码并重定向到应用程序的回调 URL。 应用程序将此代码交换为存储在客户端的访问和刷新令牌(包含用户数据和过期时间)。 后续应用程序访问会检查有效的访问令牌,如果找到则自动登录,否则重定向到身份验证中心。 虽然遵守 OAuth 2.0 标准并支持各种客户端类型(Web、移动、桌面),但它更加复杂,需要多个请求和重定向。
示例:授权代码流程。
发送授权请求(页面 A):
<code class="language-javascript">// Generate an encrypted cookie value const encryptedValue = encrypt(userinfo); // Set the cookie document.cookie = `sso_token=${encryptedValue};domain=.example.com;path=/;max-age=86400;`;</code>
处理回调(页面A):
<code class="language-javascript">// Retrieve the cookie const cookieValue = document.cookie .split(';') .find((cookie) => cookie.trim().startsWith('sso_token=')) .split('=')[1]; // Decrypt the cookie const userinfo = decrypt(cookieValue); // Log in directly login(userinfo);</code>
Leapcell 是一个用于 Web 托管、异步任务和 Redis 的尖端无服务器平台,提供:
探索文档并尝试一下!
在 X 上关注我们:@LeapcellHQ
在我们的博客上阅读更多内容
以上是单点登录 (SSO) 变得简单的详细内容。更多信息请关注PHP中文网其他相关文章!