使用Redux在React中使用OAuth2进行身份验证的公认方法是什么?
我当前的设置涉及使用Redux-Auth-Wrapper包装react-router组件,如果用户未通过身份验证,则调度一个操作,向OAuth提供程序(在这种情况下为Google)发出必要的外部URL GET请求。
OAuth2需要随您的请求一起发送回调URL,因此我设置了一个react-router URL端点/组件,当onComponentDidMount触发时,它会调度操作以解析来自OAuth提供程序的返回哈希,并将该数据存储在redux中存储,并将用户重定向到他们最初请求的页面,该页面存储在OAuth请求的state参数中。
这一切似乎都很骇人听闻。在生产和开发环境之间管理OAuth2回调URL也很困难。有人在使用OAuth2流畅的工作流程吗?
PS:我需要将Auth令牌获取给客户端,以便可以用于发出使用该令牌来检查用户是否有权访问这些资源的客户端API请求。
以下是一个将从Google提取令牌和到期数据并将其存储在本地存储中的函数。可以对其进行修改,以简单地将该数据作为对象返回。
function oAuth2TokenGet() {
// TODO: First try to get the token from sessionStorage here
// Build the oauth request url
const responseType = 'token';
const clientId = 'YOUR-GOOGLE-CLIENT-ID';
const redirectUri = 'YOUR-REDIRECT-URL';
const scope = 'email profile';
const prompt = 'select_account';
const url = `https://accounts.google.com/o/oauth2/v2/auth?response_type=${responseType}&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&prompt=${prompt}`;
// Open a new window
const win = window.open(url, 'name', 'height=600,width=450');
if (win) win.focus();
const pollTimer = window.setInterval(() => {
try {
if (!!win && win.location.href.indexOf(redirectUri) !== -1) {
window.clearInterval(pollTimer);
// Get the URL hash with your token in it
const hash = win.location.hash;
win.close();
// Parse the string hash and convert to object of keys and values
const result = hash.substring(1)
.split('&')
.map(i => i.split('='))
.reduce((prev, curr) => ({
...prev,
[curr[0]]: curr[1],
}), {});
// Calculate when the token expires and store in the result object
result.expires_at = Date.now() + parseInt(hash.expires_in, 10);
// TODO: Persist result in sessionStorage here
}
} catch (err) {
// do something or nothing if window still not redirected after login
}
}, 100);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句