Search code examples
javascriptnode.jsreactjsaccess-token

how to use Access-Tokens for CRUD REACT JS


Given is an application for managing users. Following help files are used for this purpose:

  • AuthenticationAction.js
  • ManagementAction.js

AuthenticationAction.js is used for authentication:

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 is there for the Crud Functions.

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;
        });
}  

question: Now if I want to use the createaUser function instead of the hardcoded token value with the accestoken I created in login, how do I get the accesstoken and how do I have to rewrite the createaUser function ?


Solution

  • you can store the token you created in the local storage like this:

    AuthenticationAction.js

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

    and you can access it as below:

    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 
    

    so you can send your token value with the request