2.0.2 • Published 5 years ago

axios-auto-refresh-jwt v2.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

axios-auto-refresh-jwt

A package to auto refresh jwt tokens. Built with axios and jwt-decode.

installation

npm i axios-auto-refresh-jwt

usage

Let's start by importing:

import createHttp from 'axios-auto-refresh-jwt'

You must now pass an object with the following keys:

  • getTokens: function that should return object with tokens, such as { access: 'abc', refresh: 'abc' }
  • refreshEndpoint: endpoint to refresh token and return a new access token
  • headerType: the name that will be at the beginning of the Authorization in header, such as "Authorization": "<headerType> <access token>"
  • onRefreshed: a callback for when the refresh token endpoint call is successfully made, this will be called by receiving a response object returned by axios.
  • onUnauthorized: This will be called when the server responds with 401, for example, when the refresh token is expired, or when it is tampered with. This pass the error object as argument

complete example using localStorage

import createHttp from 'axios-auto-refresh-jwt'
import { baseURL, logoutRedirectUrl } from "app/settings";
import { removeTokens, getTokens, updateAccess } from "store/localStorage";

// the "store/localStorage" functions handle the tokens in localStorage.
// With redux, this can generate circular dependencies, so
// I recommend that you manipulate tokens directly in local|session storage or in cookies.


// remove tokens from localStorage, and redirect the user
const logoutUser = (error) => {
  removeTokens();
  window.location = logoutRedirectUrl;
};

const config = {
  getTokens,
  refreshEndpoint: "http://127.0.0.1:8000/api/auth/jwt/refresh",
  headerType: "JWT",
  onRefreshed: updateAccess,
  onUnauthorized: logoutUser,
};

// create new instance and set up baseURL
// that's all!
const http = createHttp(config);
http.defaults.baseURL = baseURL;
export default http;


// some functions for example!
const refreshAccess = async (refresh) => {
  const response = await http.post("api/auth/jwt/refresh", {
    refresh,
  });
  return response;
};

const getUserInfo = async () => {
  const response = await http.get("api/auth/users/me");
  return response;
};

export { getUserInfo, refreshAccess };
2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.13

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago