redux-saga-jwt-auth
TypeScript icon, indicating that this package has built-in type declarations

1.0.5-beta.0 • Public • Published

redux-saga-jwt

npm version CircleCI Coverage Status license

Features

  1. Multiple token management
  2. Support Typescript

Installation

npm i redux-saga-jwt

Setup

import { createJWT, createActionCreators } from "redux-saga-jwt";

const jwt = createJWT();

export const myAppSelector = jwt.createSelectors("myApp");
export const myAppActions = createActionCreators("myApp");

const rootReducer = combineReducers({
  jwt: jwt.reducer,
})

const sagaMiddleware = createSagaMiddleware();

sagaMiddleware.run(function* () {
  yield all([
    jwt.saga,
  ])
});

Example

git clone https://github.com/kencckw/redux-saga-jwt.git && cd example && npm i && npm start

Usage

  1. Set token after login
function* loginSaga(action) {
    const {username, password} = action.payload;
    const tokenObject: ITokenObject = yield call(yourLoginApi, username, password)
    yield put(myAppActions.set(tokenObject));
}
  1. Listen EXPIRED and refresh your token.

Redux-saga-jwt will load the token and check the token status on application start.

import { EXPIRED } from "redux-saga-jwt";

function* refreshTokenListener() {
    yield takeEvery(EXPIRED, refreshSaga);
}

function* refreshToken(action) {
    const {id} = action.payload;
    const tokenObject = yield select(myAppSelector);
    const newToken = yield call(yourRefreshApi, tokenObject.refreshToken);
    yield put(myAppActions.set(newToken));
}
  1. Remove your token when user logs out
function* logoutSaga() {
    yield put(myAppActions.remove());
    yield call(yourLogoutApi);
}
  1. Selectors

If token is null, isTokenExpired will return true

function mapStateToProps(state) {
    return {
        token: myAppSelector.getToken(state),
        isAuthenticated: !myAppSelector.isTokenExpired(state),
    };
}

Advance usage

By overriding the default config of redux-saga-jwt, you can customize your state location or implement your own storage logic.

interface IJWTConfig<S> {
    setTokens: (tokens: IJWTState) => any;
    getTokens: () => IJWTState;
    stateSelector?: (state: S) => IJWTState;
}

const defaultConfigs: IJWTConfig<any> = {
    getTokens: () => JSON.parse(localStorage.getItem("jwt") || null),
    setTokens: tokens => localStorage.setItem("jwt", JSON.stringify(tokens)),
    stateSelector: state => state.jwt,
};
import { createJWT, createActionCreators } from "redux-saga-jwt";

const jwt = createJWT(yourConfigs);

Package Sidebar

Install

npm i redux-saga-jwt-auth

Weekly Downloads

2

Version

1.0.5-beta.0

License

MIT

Unpacked Size

21.9 kB

Total Files

19

Last publish

Collaborators

  • dian.mushkov