在 React 中使用 Axios 进行令牌身份验证

Token Authentication with Axios in React

我用 Axios 在 React 中创建了一个登录系统,它给了我一个登录令牌。我已保存此登录令牌和响应 (LoginToken):(Login.js)

export default class Login extends Component {
 state = {
      redirect: false,
      redirectHR:false,
      email: "",
      password: "",
      isLogin: false,
      loggedIn: false,
      returnedEmail: "",
      returnedFirstName:"",
      returnedLastName:"",
      returnedCompanyName:"",
      returnedCompanyCode:" ",
      LoginToken:" ",
    }
        axios.post('/api/auth/login/', data, {headers:headers, withCredentials:true}).then(
          res => {
            if(res.data != null){
              console.log(res.data);
              this.setState({
                loggedIn: true,
                returnedEmail: res.data.email,
                returnedFirstName: res.data.first_name,
                returnedLastName: res.data.last_name,
                returnedCompanyName: res.data.company_name,
                returnedCompanyCode: res.data.company_code,
                LoginToken: res.data.token,  
              })
              console.log(this.state.LoginToken);
            }else{
              console.log("failed to log in");
            }
          }
        ).catch(error => {
          console.error(error.response);

        })
      }
....

现在我想在另一个组件中将此 LoginToken 用作 header (AdditionalInfo.js) 类似于:

const headers = {
 'Authorization': 'Token your_Token'
}
export class AdditionalInfo extends Component {
  state = {
    locations:[],
  }

  componentDidMount() {
    axios.get('/api/jobs/list-locations/',{headers:headers, withCredentials:true}).then(res=>{
      console.log(res)
      this.setState({locations:res.data})
    })
  }

而不是your_token,应该是我保存在其他组件中的LoginToken。我尝试使用道具,但它没有用,如果我不添加这个 header,我会收到 401 错误,我无法从 api 接收信息。我应该如何在此文件中导入 LoginToken?

您可以使用 localStorage Web Api 来存储令牌并在任何地方使用它。

存储它:- localStorage.setItem('LoginToken', res.data.token);

检索它:- let loginToken = localStorage.getItem('LoginToken')

我想如果你不使用 redux,最好的情况是将它存储在 localStorage 上并跨不同的组件获取它。

export default class Login extends Component {
 state = {
      redirect: false,
      redirectHR:false,
      email: "",
      password: "",
      isLogin: false,
      loggedIn: false,
      returnedEmail: "",
      returnedFirstName:"",
      returnedLastName:"",
      returnedCompanyName:"",
      returnedCompanyCode:" ",
      LoginToken:" ",
    }
        axios.post('/api/auth/login/', data, {headers:headers, withCredentials:true}).then(
          res => {
            if(res.data != null){
              console.log(res.data);
              // store the token in the localstorage
              window.localStorage.setItem("token", res.data.token);
              this.setState({
                loggedIn: true,
                returnedEmail: res.data.email,
                returnedFirstName: res.data.first_name,
                returnedLastName: res.data.last_name,
                returnedCompanyName: res.data.company_name,
                returnedCompanyCode: res.data.company_code,
                LoginToken: res.data.token,  
              })
              console.log(this.state.LoginToken);
            }else{
              console.log("failed to log in");
            }
          }
        ).catch(error => {
          console.error(error.response);

        })
      }
....

在其他组件中获取令牌

const headers = {
 'Authorization': `Token window.localStorage.getItem("token")`
}
export class AdditionalInfo extends Component {
  state = {
    locations:[],
  }

  componentDidMount() {
    axios.get('/api/jobs/list-locations/',{headers:headers, withCredentials:true}).then(res=>{
      console.log(res)
      this.setState({locations:res.data})
    })
  }

(或者你应该创建一个 HOC 来将令牌推送到 props。)


export default withToken = (wrapperComponent) => {
   let token = window.localStorage.getItem("token");
   if(!token){
       // push to login
       this.props.history.push('/login');
   }else{
       <wrapperComponent token={token}>
   }
}

并且通过使用 hoc,您可以直接访问组件 props 中的令牌。