简体   繁体   English

如何在 Next.js + Redux-saga 中刷新 window 时设置授权 header?

[英]How to set Authorization header when refresh window in Next.js + Redux-saga?

I am trying to set Authorization header with JWT Bearer token.我正在尝试使用 JWT 不记名令牌设置授权 header。

When refresh window, header is reset.刷新 window 时,header 被复位。 I set header when "componentDidMount" from localstorage, but much repeated and get undefined localstorage from pre-rendering.我在 localstorage 的“componentDidMount”时设置了 header,但是重复了很多,并且从预渲染中获得了未定义的 localstorage。

axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('accesstoken');

How and where can add global function that set header with value of localstorage?如何以及在何处添加将 header 设置为 localstorage 值的全局 function? or any other Good solution?或任何其他好的解决方案?

I see from your question that you're using redux-saga ,so instead of having this logic in componentDidMount you can implement auth flow saga that is responsible for setting JWT token in api client and will be invoked during the app bootstrap:我从您的问题中看到您正在使用redux-saga ,因此您可以在componentDidMount中实现负责在 api 客户端中设置 JWT 令牌并将在应用程序引导期间调用的身份验证流传奇,而不是在 componentDidMount 中使用此逻辑:

function* authSaga() {
  // This part will be invoked only once during the app startup
  const token = JSON.parse(localStorage.getItem('accessToken'));
  if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  // Further auth flow logic goes here
  while(true) {
    if (!token) {
      const { payload } = yield take(SIGN_IN_ACTION);
      yield call(axios.post, '/your-sign-in-endpoint', payload);
    }

    yield take(SIGN_OUT_ACTION);
     // etc
  }
}

function* rootSaga() {
  yield all([
    fork(saga1),
    fork(saga2),
    ...
    fork(authSaga),
  ]);
}

In addition, I highly recommend you to refer to this thread which contains great authentication flow recipes using redux-saga.此外,我强烈建议您参考这个线程,其中包含使用 redux-saga 的出色身份验证流程配方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM