2017-06-07 1 views
1

Reactjs、redux、axios、およびredux-thunkを使用してログインフォームを作成します。私は2つのトークンを持っています - 一つはaccess tokenrefresh tokenという名前です。認証リフレッシュトークン

ユーザーが認証されると、access tokenを12時間保存する必要があります。 refresh tokenも提供され、30日間続きます。

access tokenが期限切れになったら、access tokenが期限切れの場合、タイムスタンプ(日付)を確認する必要があります。

有効期限が切れたaccess tokenを更新するにはどうすればよいですか?トークンのデータは次のようになりますので、私は、チェック対象のタイムスタンプしている:ここで

{ 
    "access_token": "toolongtoinclude", 
    "token_type": "bearer", 
    "refresh_token": "toolongtoinclude", 
    "expires_in": 43199, 
    "scope": "read write", 
    "roles": [ 
    "USER" 
    ], 
    "profile_id": "b4d1e37d-7d05-4eb3-98de-0580d3074a0d", 
    "jti": "e975db65-e3b7-4034-a6e4-9a3023c3d175" 
} 

は、ストレージからのトークンを、セーブ取得し、更新するための私の行動です。私はトークンをリフレッシュする方法については分かりません。

https://github.com/mzabriskie/axios#interceptors

私は、これはあなたを助けることができると思います。このうち

export function submitLoginUser(values, dispatch) { 
    dispatch({type: constants.LOADING_PAGE, payload: { common: true }}) 
    return axios.post(Config.API_URL + '/oauth/token', { 
      username: values.email, 
      password: values.password, 
      scope: Config.WEBSERVICES_SCOPE, 
      grant_type: Config.WEBSERVICES_GRANT_TYPE_PASSWORD 
     }, 
     { 
      transformRequest: function (data) { 
       var str = []; 
       for (var p in data) { 
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p])); 
       } 

       return str.join('&'); 
      }, 
      headers: { 
       'Authorization': 'Basic ' + window.btoa(Config.WEBSERVICES_AUTH), 
       'Content-Type': 'application/x-www-form-urlencoded' 
      } 
     }) 
     .then(response => { 
      const {access_token, refresh_token} = response.data; 
      dispatch({type: constants.LOADING_PAGE, payload: { common: false }}) 
      dispatch({ 
       type: constants.LOGIN_SUCCESS, 
       payload: { 
        access_token: access_token, 
        refresh_token: refresh_token 
       } 
      }); 
      saveTokens(response) 
      browserHistory.push('/questions'); 
      refreshToken(response); 
     }) 
     .catch(error => { 
      dispatch({type: constants.LOADING_PAGE, payload: { common: false }}) 
      //401 Error catch 
      if(error.response.status === 401) { 
       throw new SubmissionError({username: 'User is not authenticated', _error: message.LOGIN.loginUnAuth}) 
      } 
      //Submission Error 
      throw new SubmissionError({username: 'User does not exist', _error: message.LOGIN.loginFailed}) 
     }) 
} 

/** 
* Save tokens in local storage and automatically add token within request 
* @param params 
*/ 
export function saveTokens(params) { 
    const {access_token, refresh_token} = params.data; 
    localStorage.setItem('access_token', access_token); 
    if (refresh_token) { 
     localStorage.setItem('refresh_token', refresh_token); 
    } 
    //todo fix this later 
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${access_token}` 
} 

/** 
* 
*/ 
export function getTokens() { 
    let accessToken = localStorage.getItem('access_token'); 
    return accessToken 
} 

/** 
* update the get requests 
*/ 
export function updateTokenFromStorage() { 
    const tokenLocalStorage = getTokens(); 
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${tokenLocalStorage}`; 
} 

/** 
* Refresh user access token 
*/ 
export function refreshToken(dispatch) { 
    //check timestamp 
    //check access expired - 401 

    //request new token, pass refresh token 
    //store both new access and refresh tokens 

} 
+0

すべてのログを取得するのではなく、テストするために私の店で使用することを試みたコードです。このインターセプタはあなたのトークンがまだ有効かどうかをチェックします。そうでない場合は、新しいルートに送信するか、メッセージを表示します。 –

+0

このヴァーターをありがとうございます - 私は斧の傍受者を調べます。 – Filth

答えて

0

チェック。あなたはあなたの要求を傍受し、あなたの検証を行います。

EDITここ

は、私はすべてのあなたのリクエストにインターセプタを作成しない理由をバック

import { createStore, applyMiddleware, compose } from 'redux' 
import { devTools, persistState } from 'redux-devtools' 
import axios from 'axios' 
import Middleware from '../middleware' 
import Reducer from '../reducers/reducer' 
import DevTools from '../containers/DevTools' 

let finalCreateStore 

if (__DEVELOPMENT__ && __DEVTOOLS__) { 

    finalCreateStore = compose(
    applyMiddleware.apply(this, Middleware), 
    // Provides support for DevTools: 
     DevTools.instrument(), 
    // Optional. Lets you write ?debug_session=<key> in address bar to persist debug sessions 
    persistState(getDebugSessionKey()) 
)(createStore) 
} else { 
    finalCreateStore = compose(
    applyMiddleware.apply(this, Middleware) 
)(createStore) 
} 

function getDebugSessionKey() { 
    // You can write custom logic here! 
    // By default we try to read the key from ?debug_session=<key> in the address bar 
    const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/) 
    return (matches && matches.length > 0)? matches[1] : null 
} 

axios.interceptors.response.use((err) => { 
    if (err.status === 401) { 
     console.log('ACCESS TOKEN EXPIRED!'); 
    } 
}); 


export const store = finalCreateStore(Reducer) 
+0

このバターのおかげで - 私はちょうどインターセプターの機能が呼び出されるつもりは混乱している? – Filth

+0

あなたの問題を解決するかどうかを確認しようとしましたか?あなたのindex.jsやルートコンポーネント、ストアなどを作成する場所に追加してみてください。そこに試してみてください。私はこれが良い場所だと思うが、後でもっと良い場所で考えることができる。 –

+0

これは半分の問題です。私はこれをどのように使用するのか分かりません。以前は使用していませんでした。私は自分の店のindex.jsファイルを見て、これをテストするために何が書けますか? – Filth

関連する問題