redux-saga-jwt-auth
v1.0.5-beta.0
Published
Token management for single page application
Downloads
4
Maintainers
Readme
redux-saga-jwt
Features
- Multiple token management
- 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
- 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));
}
- 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));
}
- Remove your token when user logs out
function* logoutSaga() {
yield put(myAppActions.remove());
yield call(yourLogoutApi);
}
- 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);