我试图在React Native应用中到期的新access_token
过期,但是当我发布refresh_token
时却收到错误消息“令牌已被撤消”
RemoteConsole.js:80 Possible Unhandled Promise Rejection (id: 0):
Object {
"error": "invalid_request",
"error_description": "The refresh token is invalid.",
"hint": "Token has been revoked",
"message": "The refresh token is invalid.",
}
我被困住了。我究竟做错了什么?这是我的代码
import React from 'react';
import { Provider } from 'react-redux';
import axios from 'axios';
import { AsyncStorage } from 'react-native';
import { base, clientId } from 'react-native-dotenv';
import JwtDecode from 'jwt-decode';
import FormData from 'form-data';
import store from './src/store';
import Router from './src/router';
let currentTime;
let decoded;
AsyncStorage.getItem('userToken').then((result) => {
currentTime = Date.now() / 1000;
decoded = JwtDecode(result);
});
const isValidToken = () => currentTime < decoded.exp;
axios.interceptors.response.use((config) => {
const originalRequest = config;
if (AsyncStorage.getItem('userToken') && !isValidToken()) {
return issueToken().then((response) => {
originalRequest.headers.Authorization = `Bearer ${response.access_token}`;
return Promise.resolve(originalRequest);
});
}
return config;
}, (error) => {
if (error.response && error.response.data) {
return Promise.reject(error.response.data);
}
return Promise.reject(error.message);
});
function issueToken() {
return new Promise((resolve, reject) => {
let refreshToken;
AsyncStorage.getItem('refreshToken').then((response) => {
refreshToken = response;
const url = `${base}/oauth/token`;
const formData = new FormData();
formData.append('grant_type', 'refresh_token');
formData.append('client_id', clientId);
formData.append('refresh_token', refreshToken);
console.log(refreshToken);
return axios({
method: 'POST',
url,
data: formData,
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
})
.then((data) => {
AsyncStorage.setItem('userToken', data.data.access_token);
AsyncStorage.setItem('refreshToken', data.data.refresh_token);
const expireTime = (new Date().getTime() / 1000) + data.data.expires_in;
AsyncStorage.setItem('expiresIn', expireTime);
resolve(data.data);
})
.catch((error) => {
reject(error);
});
});
});
}
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Router />
</Provider>
);
}
}
非常感谢您的帮助。