【发布时间】:2018-11-25 18:45:16
【问题描述】:
我的 React 应用程序中有一个 JS 文件,它连接到服务器,发送用户名和密码,从服务器接收一个 oauth 令牌并将令牌存储在本地存储中。 然而,在 react 收到令牌之前,react 会在令牌存储在本地存储之前发送下一个请求。这会导致 401 未经授权的访问。
AuthService.js
login(username, password) {
console.log(username);
return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
headers: {
'Access-Control-Allow-Origin': "*"
}
}).then(res => {
this.fetch(`${this.domain}/Token`, {
method: 'POST',
body: 'grant_type=password&username=' + res[0]
}).then(response => {
var date_token_issue = new Date();
this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
return Promise.resolve(response);
})
})
}
setToken(idToken,expires, date_token_issue ) {
localStorage.setItem('id_token', idToken)
localStorage.setItem('expires', expires)
localStorage.setItem('date_token_issue', date_token_issue)
}
SignIn.jsx
import React, { Component } from 'react'
import AuthService from '../comonents/AuthService';
import Orders from '../../app/orders/orders'
import { Redirect, Switch, Route} from "react-router-dom";
export default function SignIn(AuthComponent){
const Auth = new AuthService('http://localhost:53050');
return class AuthWrapped extends Component {
constructor() {
super();
this.state = {
user: null,
loggedIn: false
}
}
async componentDidMount() {
if (!Auth.loggedIn()) {
const promise = await Auth.login('m.dawaina', 'm.dawaina');
console.log(promise)
this.setState({loggedIn: true});
}
else {
try {
this.setState({loggedIn: true})
const profile = Auth.getProfile()
this.setState({
user: profile
})
}
catch(err){
Auth.logout()
//this.props.history.replace('/login')
}
}
}
render() {
if (this.state.loggedIn) {
return (
<div>
<Redirect to='/orders'/>
<Switch>
<Route path="/orders" component={Orders} />
</Switch>
</div>
)
}
else {
return (
<AuthComponent history={this.props.history} user={this.state.user} />
)
}
}
}
}
我需要一种方法来强制 react 等待 JS 接收到令牌并将其存储在本地存储中,并阻止 react 发送下一个请求,直到它找到存储在本地存储中的令牌。
【问题讨论】:
标签: reactjs asynchronous oauth token fetch