簡體   English   中英

如何為 CRUD REACT JS 使用訪問令牌

[英]how to use Access-Tokens for CRUD REACT JS

Given 是一個用於管理用戶的應用程序。 以下幫助文件用於此目的:

  • AuthenticationAction.js
  • ManagementAction.js

AuthenticationAction.js 用於身份驗證:

export function authenticateUser(userID, password) {

  console.log("Authenticate")
  return dispatch => {
    dispatch(getAuthenticateUserPendingAction());
    login(userID, password).then(userSession => {
      const action = getAuthenticationSuccessAction(userSession);
      dispatch(action);
    }, error => {
      dispatch(getAuthenticationErrorAction(error));
    }).catch(error => {
      dispatch(getAuthenticationErrorAction(error));
    })
  }

}

function login(userID, password) {
  const hash = Buffer.from(`${userID}:${password}`).toString('base64')

  const requestOptions = {
    method: 'POST',
    headers: {
      'Authorization': `Basic ${hash}`
    },

  };

  return fetch('https://localhost:443/authenticate', requestOptions)
    .then(handleResponse)
    .then(userSession => {
      return userSession;
    });
}

function handleResponse(response) {
  console.log(response)

  const authorizationHeader = response.headers.get('Authorization');
  return response.text().then(text => {

    if (authorizationHeader) {
      var token = authorizationHeader.split(" ")[1];
    }
    if (!response.ok) {
      if (response.status === 401) {
        logout();
      }
      const error = response.statusText;
      return Promise.reject(error);
    } else {
      let userSession = {
        /* user: data, */
        accessToken: token
      }
      return userSession;
    }
  });
}

ManagementAction.js 用於 Crud 函數。

export function createUser(userID, username, password) {

    console.log("Create a User")
    return dispatch => {
        dispatch(getShowUserManagementAction());
        createaUser(userID, username, password).then(userSession => {
            const action = getShowUserManagementActionSuccess(userSession);
            dispatch(action);
        }, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
    }

}

function createaUser(userID, username, password) {
    
    const token = "whatever"
    const requestOptions = {
        method: 'POST',
        headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ userID: userID, userName: username, password: password })

    };
    console.log(requestOptions)
    return fetch('https://localhost:443/user/', requestOptions)
        .then(handleResponse)
        .then(userSession => {
            return userSession;
        });
}  

問題:現在,如果我想使用createaUser function 而不是硬編碼的令牌值和我在login中創建的 accestoken,我如何獲取 accesstoken 以及如何重寫createaUser function?

您可以將創建的令牌存儲在本地存儲中,如下所示:

AuthenticationAction.js

let userSession = {
        /* user: data, */
        accessToken: token
      }
localStorage.setItem("token", userSession.accessToken)

您可以按如下方式訪問它:

ManagementAction.js

function createaUser(userID, username, password) {
    
const token = localStorage.getItem("token")    
const requestOptions = {
        method: 'POST',
        headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },


then 

這樣您就可以在請求中發送您的令牌值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM