Note: This example is very out-of-date. It might point you in the right direction, but I plan to re-write it from scratch. I won't be accepting any PRs in the meantime. Sorry about that!
This project is an learning project to show possibility authentication flow using react, redux, react-router, redux-router, and JSON web tokens (JWT). It is based on the implementation of a higher-order component to wrap protected views and perform authentication logic prior to rendering them.
Note: The focus here is on the client-side flow. The server included in this example is for demonstration purposes only. It contains some hard-coded API endpoints and is obviously not intended for any kind of production environment.
1. git clone https://github.com/coolerwind/react-redux-jwt-auth-learning.git
2. npm install
3. export NODE_ENV=development
4. node server.js
Then visit localhost:3000
in your browser.
The overall flow goes something like this:
- The log in form dispatches an action creator which triggers a POST to the server
- The server validates login credentials and returns a valid JWT or 401 Unauthorized response as needed
- The original action creator parses the server response and dispatches success or failure actions accordingly
- Success actions trigger an update of the auth state, passing along the token and any decoded data from the JWT payload
- A higher-order authentication component receives the new auth state as props
- If authentication was successful, the higher-order component renders its child component and passes the auth props down to it
- Before mounting, the child fetches data from the server using the token it received from its parent wrapper