要求: 点击登录(OAuth2.0统一认证登录)跳转到 window.location.href = 'http://127.0.0.1:9000/oauth2/authorize?response_type=code&client_id=anchoremc-seed&scope=openid&redirect_uri=http://127.0.0.1:8000/signIn'; ,他会重定向到后端的登录页面http://127.0.0.1:9000/login.通过window.name把用户名和密码传递给,后端的登录页面http://127.0.0.1:9000/login做自动填充,怎么做?
前端代码
-
在登录表单的
handleCertificate
方法中,设置window.name
属性。将用户名和密码以 JSON 格式存储在window.name
中。 -
跳转到后端的登录页面。
-
const handleCertificate = async () => { const values = await form.validateFields().catch(error => { console.log(error); }); const { remember, userName, password } = values as SignInForm; if (values && !code) { remember && setLocalStorage('signInfo', { remember, userName, password }); // 将用户名和密码存储到 window.name window.name = JSON.stringify({ userName, password }); // 跳转统一认证 window.location.href = 'http://127.0.0.1:9000/oauth2/authorize?response_type=code&client_id=anchoremc-seed&scope=openid&redirect_uri=http://127.0.0.1:8000/signIn'; } };
后端代码
在后端的登录页面,您需要在页面加载时解析
window.name
。以下是如何在后端获取window.name
的示例: - 在后端的登录页面 JavaScript 中,添加代码以读取
window.name
。 -
<script type="text/javascript"> document.addEventListener("DOMContentLoaded", function() { const userInfo = window.name ? JSON.parse(window.name) : null; if (userInfo) { // 自动填充用户名和密码 document.getElementById('username').value = userInfo.userName; document.getElementById('password').value = userInfo.password; // 提交表单 document.getElementById('form').submit(); } }); </script>
注意事项
- 安全性:直接通过
window.name
传递用户名和密码可能会有安全隐患,确保在生产环境中采取其他措施(如 HTTPS 和 CSRF 防护)以保护用户凭证。 - 清理
window.name
:在处理完数据后,最好清空window.name
以避免后续访问时出现敏感信息。window.name = ''; // 清空