Coder Social home page Coder Social logo

mvanroon / react-native-axios-jwt Goto Github PK

View Code? Open in Web Editor NEW
30.0 3.0 9.0 190 KB

Axios interceptor to store, transmit, clear and automatically refresh tokens for authentication in a React Native environment

Home Page: https://www.npmjs.com/package/react-native-axios-jwt

JavaScript 1.00% TypeScript 99.00%
react-native axios jwt jwt-token interceptor async-storage

react-native-axios-jwt's Introduction

react-native-axios-jwt

Store, clear, transmit and automatically refresh JWT authentication tokens in a React Native environment.

Looking for a web alternative? Check out axios-jwt

What does it do?

Applies a request interceptor to your axios instance.

The interceptor automatically adds a header (default: Authorization) with an access token to all requests. It stores accessToken and refreshToken in AsyncStorage 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.

Installation

2. Install this library

With npm:

npm install react-native-axios-jwt

With Yarn:

yarn add react-native-axios-jwt

How do I use it?

  1. Create an axios instance.
  2. Define a token refresh function.
  3. Configure the interceptor.
  4. Store tokens on login with setAuthTokens function.
  5. Clear tokens on logout with clearAuthTokens function.

Applying the interceptor

// api.ts

import axios from 'axios'
import {
  type AuthTokenInterceptorConfig,
  type AuthTokens,
  type TokenRefreshRequest,
  applyAuthTokenInterceptor,
} from 'react-native-axios-jwt'

const BASE_URL = 'https://api.example.com'

// 1. Create an axios instance that you wish to apply the interceptor to
export const axiosInstance = axios.create({
  baseURL: BASE_URL,
})

// 2. Define token refresh function.
// It is an async function that takes a refresh token and returns a promise
// that resolves in fresh access token and refresh token.
// You can also return only an access token in a case when a refresh token stays the same.
const requestRefresh: TokenRefreshRequest = async (
  refreshToken: string,
): Promise<AuthTokens> => {
  // Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor
  // because this will result in an infinite loop when trying to refresh the token.
  // Use the global axios client or a different instance.
  const response = await axios.post(`${BASE_URL}/auth/refresh_token`, {
    token: refreshToken,
  })

  const {
    access_token: newAccessToken,
    refresh_token: newRefreshToken,
  } = response.data

  return {
    accessToken: newAccessToken,
    refreshToken: newAccessToken,
  }
}

const config: AuthTokenInterceptorConfig = {
  requestRefresh,
}

// 3. Add interceptor to your axios instance
applyAuthTokenInterceptor(axiosInstance, config)

Login

// login.ts

import { setAuthTokens } from 'react-native-axios-jwt'

import { axiosInstance } from './api'

// 4. Log in with POST request with the email and password.
// Get access token and refresh token in response.
// Call `setAuthTokens` with the tokens.
const login = async (params: LoginRequestParams): void => {
  const response = await axiosInstance.post('/auth/login', params)

  const {
    access_token: accessToken,
    refresh_token: refreshToken,
  } = response.data

  // Save tokens to AsyncStorage.
  await setAuthTokens({
    accessToken,
    refreshToken,
  })
}

Usage

// usage.ts

import {
  getAccessToken,
  getRefreshToken,
  isLoggedIn,
} from 'react-native-axios-jwt';

// Check if the user is logged in.
if (isLoggedIn()) {
  // Assume the user is logged in because we have a refresh token stored in AsyncStorage.
}

// Use access token.
const doSomethingWithAccessToken = async (): void => {
  const accessToken = await getAccessToken()

  console.log(accessToken)
}

// Use refresh token.
const doSomethingWithRefreshToken = async (): void => {
  const refreshToken = await getRefreshToken()

  console.log(refreshToken)
}

Logout

// logout.ts

import { clearAuthTokens } from 'react-native-axios-jwt'

// 5. Log out by clearing the auth tokens from AsyncStorage.
const logout = async (): void => {
  await clearAuthTokens()
}

Configuration

applyAuthTokenInterceptor(axiosInstance, {
  header = 'Authorization',  // header name
  headerPrefix = 'Bearer ',  // header value prefix
  requestRefresh,  // async function that resolves in fresh access token (and refresh token)
})

Caveats

  • Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.

react-native-axios-jwt's People

Contributors

dependabot[bot] avatar jasonpraful avatar kahakai avatar mvanroon avatar peter-slump avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-axios-jwt's Issues

Can't install

npm install [email protected]

npm ERR! code ETARGET
npm ERR! notarget No matching version found for [email protected]
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

Could not resolve dependency: axios@"~0"

npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/axios
npm ERR!   axios@"^1.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer axios@"~0" from [email protected]
npm ERR! node_modules/react-native-axios-jwt
npm ERR!   react-native-axios-jwt@"^1.7.1" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/axios
npm ERR!   peer axios@"~0" from [email protected]
npm ERR!   node_modules/react-native-axios-jwt
npm ERR!     react-native-axios-jwt@"^1.7.1" from the root project

How to fix?
This forces the use of --legacy-peer-deps for every installation (

Login State

Hi.
How to get current login state?
There's nothing to do with isLoggedIn function.

Connect with jsx

Any success in using it with libraries like react-navigation and make use of isLoggedIn to conditional render something?

Sending empty request

Changing the issue to the one I currently have :)

I've managed to make it run, kind of. However, login post request is sending empty request, It seems to be this lib specific, but not sure.

  const handleLogin = async (email, password) => {
    const response = await axiosInstance.post('/auth/token/obtain/', {
      email: email,
      password: password,
    });
    await setAuthTokens({
      accessToken: response.data.access_token,
      refreshToken: response.data.refresh_token,
    });
  };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.