Gathering detailed insights and metrics for axios-jwt
Gathering detailed insights and metrics for axios-jwt
Gathering detailed insights and metrics for axios-jwt
Gathering detailed insights and metrics for axios-jwt
vue-axios-jwt
Vue plugin for axios-jwt
@vueuse/integrations
Integration wrappers for utility libraries
axios
Promise based HTTP client for the browser and node.js
react-native-axios-jwt
Axios interceptor to store, transmit, clear and automatically refresh tokens for authentication in a React Native environment
npm install axios-jwt
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
117 Stars
90 Commits
30 Forks
10 Watching
7 Branches
16 Contributors
Updated on 04 Nov 2024
TypeScript (99.03%)
JavaScript (0.97%)
Cumulative downloads
Total Downloads
Last day
21.7%
601
Compared to previous day
Last week
51.6%
4,675
Compared to previous week
Last month
26.4%
17,239
Compared to previous month
Last year
145%
268,643
Compared to previous year
2
2
Store, clear, transmit and automatically refresh JWT authentication tokens. This library can be used in both web and react-native projects.
Applies a request interceptor to your axios instance.
The interceptor automatically adds an access token header (default: Authorization
) to all requests.
It stores accessToken
and refreshToken
in localStorage
(web) or 'AsyncStorage' (React Native) and reads them when needed.
It parses the expiration time of your access token and checks to see if it is expired before every request. If it has expired, a request to refresh and store a new access token is automatically performed before the request proceeds.
1npm install --save axios-jwt # or `yarn add axios-jwt`
You will also need to install react-native-async-storage in order to be able to store and retrieve tokens.
1expo install @react-native-async-storage/async-storage
1npm install --save @react-native-async-storage/async-storage # or `yarn add @react-native-async-storage/async-storage` 2npx pod-install # installs the native iOS packages
setAuthTokens()
clearAuthTokens()
1// api.ts 2 3import { IAuthTokens, TokenRefreshRequest, applyAuthTokenInterceptor, getBrowserLocalStorage } from 'axios-jwt' 4import axios from 'axios' 5 6const BASE_URL = 'https://api.example.com' 7 8// 1. Create an axios instance that you wish to apply the interceptor to 9export const axiosInstance = axios.create({ baseURL: BASE_URL }) 10 11// 2. Define token refresh function. 12const requestRefresh: TokenRefreshRequest = async (refreshToken: string): Promise<IAuthTokens | string> => { 13 14 // Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor (in our case 'axiosInstance') 15 // because this will result in an infinite loop when trying to refresh the token. 16 // Use the global axios client or a different instance 17 const response = await axios.post(`${BASE_URL}/auth/refresh_token`, { token: refreshToken }) 18 19 // If your backend supports rotating refresh tokens, you may also choose to return an object containing both tokens: 20 // return { 21 // accessToken: response.data.access_token, 22 // refreshToken: response.data.refresh_token 23 //} 24 25 return response.data.access_token 26} 27 28// 3. Add interceptor to your axios instance 29applyAuthTokenInterceptor(axiosInstance, { requestRefresh }) 30 31// New to 2.2.0+: initialize with storage: localStorage/sessionStorage/nativeStorage. Helpers: getBrowserLocalStorage, getBrowserSessionStorage 32const getStorage = getBrowserLocalStorage 33 34// You can create you own storage, it has to comply with type StorageType 35applyAuthTokenInterceptor(axiosInstance, { requestRefresh, getStorage })
1// login.ts 2 3import { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'axios-jwt' 4import { axiosInstance } from './api' 5 6// 4. Post email and password and get tokens in return. Call setAuthTokens with the result. 7const login = async (params: ILoginRequest) => { 8 const response = await axiosInstance.post('/auth/login', params) 9 10 // save tokens to storage 11 setAuthTokens({ 12 accessToken: response.data.access_token, 13 refreshToken: response.data.refresh_token 14 }) 15} 16 17// 5. Remove the auth tokens from storage 18const logout = async () => await clearAuthTokens() 19 20// Check if refresh token exists 21if (await isLoggedIn()) { 22 // assume we are logged in because we have a refresh token 23} 24 25// Get access to tokens 26const accessToken = await getAccessToken() 27const refreshToken = await getRefreshToken()
1applyAuthTokenInterceptor(axiosInstance, { 2 requestRefresh, // async function that takes a refreshToken and returns a promise the resolves in a fresh accessToken 3 header: "Authorization", // header name 4 headerPrefix: "Bearer ", // header value prefix 5})
1import { applyAuthTokenInterceptor, setAuthTokens, clearAuthTokens } from 'axios-jwt'; 2import axios from 'axios'; 3 4const BASE_URL = 'https://api.example.com' 5 6// 1. Create an axios instance that you wish to apply the interceptor to 7const axiosInstance = axios.create({ baseURL: BASE_URL }) 8 9// 2. Define token refresh function. 10const requestRefresh = (refresh) => { 11 // Notice that this is the global axios instance, not the axiosInstance! <-- important 12 return axios.post(`${BASE_URL}/auth/refresh_token`, { refresh }) 13 .then(response => response.data.access_token) 14}; 15 16// 3. Apply interceptor 17applyAuthTokenInterceptor(axiosInstance, { requestRefresh }); // Notice that this uses the axiosInstance instance. <-- important 18 19// 4. Logging in 20const login = async (params) => { 21 const response = await axiosInstance.post('/auth/login', params) 22 23 // save tokens to storage 24 setAuthTokens({ 25 accessToken: response.data.access_token, 26 refreshToken: response.data.refresh_token 27 }) 28} 29 30// 5. Logging out 31const logout = () => clearAuthTokens() 32 33// Now just make all requests using your axiosInstance instance 34axiosInstance.get('/api/endpoint/that/requires/login').then(response => { }) 35
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
Found 12/26 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
license file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
18 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More