In this tutorial, we briefly analyze how REST requests to API are implemented, requiring the user to be authorized, and create an asynchronous “wrapper” for the request, which will check the authorization and update it in a timely manner. { "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSld", "refresh_token": "1eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgS", "expires_in": 124234149563 } function saveToken(token) { sessionStorage.setItem('tokenData', JSON.stringify(token)); } function getTokenData(login, password) { return fetch('api/auth', { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ login, password, }), }) .then((res) => { if (res.status === 200) { const tokenData = res.json(); saveToken(JSON.stringify(tokenData)); // sessionStorage, , return Promise.resolve() } return Promise.reject(); }); } function refreshToken(token) { return fetch('api/auth/refreshToken', { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ token, }), }) .then((res) => { if (res.status === 200) { const tokenData = res.json(); saveToken(JSON.stringify(tokenData)); // sessionStorage, , return Promise.resolve(); } return Promise.reject(); }); } export async function fetchWithAuth(url, options) { const loginUrl = '/login'; // url let tokenData = null; // tokenData if (sessionStorage.authToken) { // sessionStorage tokenData, tokenData = JSON.parse(localStorage.tokenData); } else { return window.location.replace(loginUrl); // , } if (!options.headers) { // headers, options.headers = {}; } if (tokenData) { if (Date.now() >= tokenData.expires_on * 1000) { // try { const newToken = await refreshToken(tokenData.refresh_token); // , refresh_token saveToken(newToken); } catch () { // - , return window.location.replace(loginUrl); } } options.headers.Authorization = `Bearer ${tokenData.token}`; // headers } return fetch(url, options); // , headers } import fetchWithAuth from './api'; function getData() { return fetchWithAuth('api/data', options) } Source: https://habr.com/ru/post/456188/
All Articles