不要将您的授权令牌放在正文中。将其放在标题中。第一个功能将传递用户名,密码和身份验证类型(即
grant_type=password)。然后,我的第二个功能将使用它来认证请求。不再需要传递任何用户信息,因为我的api根据传入的令牌知道谁在请求。OAuth
2.0的当前文档在此处,您可以在Mozilla的网站上找到有关使用标头与fetch的更多信息。获取文档。
// request the token// subscribe to this event and use the returned json to save your token to state or session storageexport function requestAccessToken(data) { const loginInfo = `${data}&grant_type=password`; return fetch(`${API_URL}Token`, { method: 'POST', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlenpred', }), body: loginInfo, }) .then((response) => response.json()); // in your case set state to returned token}// use said token to authenticate requestexport function requestUserInfo(token) { return fetch(`${API_URL}api/participant/userinfo`, { method: 'GET', headers: new Headers({ Authorization: `Bearer ${token}`, }), }) .then((response) => response.json());}我还建议:
从thunk或saga调用fetch,但这超出了问题的范围。
无需将令牌放在隐藏字段中。顺便说一句,仍然可以访问。只需保持其状态即可。您可以采取其他一些措施来保护它,但是这也不在问题范围之内。



