Authentication with jsowebtoken

1

I have an application that in backend works with nodeJS , in the same control or well authenticate process, the problem I have in frontend , I use token to authenticate and in frontend I keep it in the LocalStorage of the browser, but I do not know how to enter it in the header and then in the backend get it in middleware .

Thanks in advance ... Salu2s

    
asked by Travv 13.10.2017 в 22:23
source

1 answer

1

According to the specification, the token must go in the header Authorization . To avoid repeating the process you can make a utilitarian function that prepares the requests:

export const $http = (path, { method, query, body }) => {
  /* Accept y Content-Type solo son necesarios si vas a trabajar con una API basada en JSON */
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: 'Bearer ${localStorage.getItem('token')}',
  };

  /* URL construction */
  let _url = '<URL a tu endpoint>/${path}';

  Object.keys(query || {}).forEach((key) => {
    _url += '${key}=${query[key]}&';
  });

  /* Request payload */
  const requestBody = {
    method: method || 'GET',
    headers,
  };

  if (method === 'POST' || method === 'PUT') {
    requestBody.body = JSON.stringify(body);
  }

  return fetch(_url, requestBody);
};

So you use it in the following way for example:

export const create = async (data) => {
  const res = await $http('/users', {
    method: 'POST',
    body: data,
  });
  return res.json();
};

Obviously instead of fetch you can use libraries like Axios . In the backend you should only write a middleware for your server that gets the Authorization header and check if the token exists or is valid.

    
answered by 13.10.2017 / 22:44
source