Full stack Django: Quick start with JWT auth and React/Redux (Part III)

In the previous two parts, we created a simple backend and frontend with user authentication.

In this final part, we would perform our first authenticated call to the API and implement JWT Refresh Token workflow.

Calling an API

Let’s create a simple helper, that would add Authentication header with token from our state.


Now we can create our first API action, in a new file actions/echo.js

When action came into redux-api-middleware the headers function would be called, and the Authorization header would be expanded.

Save the API call result in the store with the simple reducer:


Let’s call it. The simplest thing that we can do, is to perform API calls on componentDidMount just after when a user goes into the App page.


We connect the App component with the state. As soon as component became mounted, the echo action would go to the redux-api-middleware that would perform the actual API call. On complete, ECHO_SUCCEED message would be dispatch down to the echo reducer. The message would be saved in the state.echo.message that would cause UI reconciliation.

Everything would work fine, till the Access token became expired. Just imagine the situation, when a user opens an application after a while. A user has a valid Refresh token, and the Access token already expired. API requests fire immediately from different components of an application. But we can’t execute them right now, till Access token became updated.

JWT Workflow

So, here is the trick. We going to wrap redux-api-middleware into out custom middleware, that postpone actions till valid access token received

If everything is fine, we just delegate an action to the rsaaMiddleware(next)

But if we have a Refresh token and our Access token is expired, the action goes to the postponedRSAAs list, and refresAccessToken action fired instead. Since all middlewares works like a chain, and there is no loop in message processing, we catch TOKEN_RECEIVED in the custom nextCheckPostponed function that passed as next parameter to the redux-api-middleware

As soon as new Access Token received, we could fire postponed actions.

Now you can just replace an import apiMiddleware in the store.js to make everything works

That’s our simple application.

Having JWT workflow implemented in the middleware allows to keep actions code free from authentication flow details.

The sample code available at the https://github.com/viewflow/cookbook/tree/master/_articles/redux_jwt_auth

Reusable workflow library #django #python http://viewflow.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store