3

I have created an axios instance:

const instance = axios.create({
  baseURL: 'https://example.io/api/',
  timeout: 1000
});

and would like to use it on different components. My webapp is secured with Keycloak and every request that goes to API, needs an authentication token. To get the token, I call the Keycloak method as follows:

    kc
        .init({onLoad: "login-required"})
        .then(authenticated => {
            if (kc.idToken === undefined) {
                return Promise.reject("Can not be authenticated")
            }
            return authenticated && root !== null ? start({authToken: kc.idToken}, root) : Promise.reject("Can not be authenticated")
        })
        .catch(console.log)

When I do the request to the API server, I pass the token as Bearer token in the request header. To avoid passing the token on every request, can I use the intercepter right or what do I have to do?

1
  • 1
    I thinks instance part is fine. You just need to use interception. It seems like you are already managing token. Simple call in interceptor and use it there. Commented Nov 4, 2020 at 12:59

2 Answers 2

10

One way to achieve this is as follows:

Create a file with the following code snippet and name this httpService.js (choose the name of your choice).

import axios from 'axios';    

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${your_token}`;
    // OR config.headers.common['Authorization'] = `Bearer ${your_token}`;
    config.baseURL = 'https://example.io/api/';

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

export default {
  get: axios.get,
  post: axios.post,
  put: axios.put,
  delete: axios.delete,
  patch: axios.patch
};

Now to use it in other parts of your application, add this import:

import http from './httpService';

Example usage:

static getClient = (clientId) => {
    return http.get('/clients/' + clientId);
};

The baseUrl and Authorization header will be automatically configured with every request.

Sign up to request clarification or add additional context in comments.

Comments

0

Axios default configuration can be modified, once you modify the defaults all the service call that made using axios will use the same configuration.

axios.defaults.headers.common['Authorization'] = `Bearer ${AUTH_TOKEN}`;

Please refer to the official docs https://github.com/axios/axios#global-axios-defaults

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.