{"id":13494748,"url":"https://github.com/joshgeller/react-redux-jwt-auth-example","last_synced_at":"2025-03-28T14:31:44.941Z","repository":{"id":47550572,"uuid":"45349761","full_name":"joshgeller/react-redux-jwt-auth-example","owner":"joshgeller","description":"Sample project showing possible authentication flow using React, Redux, React-Router, and JWT","archived":true,"fork":false,"pushed_at":"2018-09-17T08:49:29.000Z","size":145,"stargazers_count":1579,"open_issues_count":25,"forks_count":237,"subscribers_count":40,"default_branch":"master","last_synced_at":"2024-10-31T09:37:11.136Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/joshgeller.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-11-01T17:19:39.000Z","updated_at":"2024-10-03T20:44:53.000Z","dependencies_parsed_at":"2022-09-05T22:21:56.729Z","dependency_job_id":null,"html_url":"https://github.com/joshgeller/react-redux-jwt-auth-example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshgeller%2Freact-redux-jwt-auth-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshgeller%2Freact-redux-jwt-auth-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshgeller%2Freact-redux-jwt-auth-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/joshgeller%2Freact-redux-jwt-auth-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/joshgeller","download_url":"https://codeload.github.com/joshgeller/react-redux-jwt-auth-example/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246046063,"owners_count":20714895,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T19:01:27.738Z","updated_at":"2025-03-28T14:31:44.316Z","avatar_url":"https://github.com/joshgeller.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"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!\n\n### Goal\n\nThis project is an example of one possible authentication flow using [react](https://github.com/facebook/react), [redux](https://github.com/rackt/redux), [react-router](https://github.com/rackt/react-router), [redux-router](https://github.com/rackt/redux-router), and [JSON web tokens (JWT)](http://jwt.io/). It is based on the implementation of a [higher-order component](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750)\nto wrap protected views and perform authentication logic prior to rendering them.\n\n**Note:** The focus here is on the client-side flow. The server included in this example is for demonstration purposes only.\nIt contains some hard-coded API endpoints and is obviously not intended for any\nkind of production environment.\n\n---\n\n### Running the Example Locally\n````\n1. git clone https://github.com/joshgeller/react-redux-jwt-auth-example.git\n2. npm install\n3. export NODE_ENV=development\n4. node server.js\n````\nThen visit `localhost:3000` in your browser.\n\n---\n\n### General Flow\n\nThe overall flow goes something like this:\n\n1. The log in form dispatches an action creator which triggers a POST to the server\n2. The server validates login credentials and returns a valid JWT or 401 Unauthorized response as needed\n3. The original action creator parses the server response and dispatches success or failure actions accordingly\n4. Success actions trigger an update of the auth state, passing along the token and any decoded data from the JWT payload\n5. A higher-order authentication component receives the new auth state as props\n6. If authentication was successful, the higher-order component renders its child component and passes the auth props down to it\n7. Before mounting, the child fetches data from the server using the token it received from its parent wrapper\n\nTaking a look at the code should make this more clear!\n\n---\n\n### How It Works\n\nThe higher-order component that does the heavy lifting is in `components/AuthenticatedComponent`. Notice that we are exporting a function which returns the higher-order component. The function takes a single argument: a child component it will wrap.\n\n\n```javascript\nimport React from 'react';\nimport {connect} from 'react-redux';\nimport {pushState} from 'redux-router';\n\nexport function requireAuthentication(Component) {\n\n    class AuthenticatedComponent extends React.Component {\n\n        componentWillMount() {\n            this.checkAuth();\n        }\n\n        componentWillReceiveProps(nextProps) {\n            this.checkAuth();\n        }\n\n        checkAuth() {\n            if (!this.props.isAuthenticated) {\n                let redirectAfterLogin = this.props.location.pathname;\n                this.props.dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));\n            }\n        }\n\n        render() {\n            return (\n                \u003cdiv\u003e\n                    {this.props.isAuthenticated === true\n                        ? \u003cComponent {...this.props}/\u003e\n                        : null\n                    }\n                \u003c/div\u003e\n            )\n\n        }\n    }\n\n    const mapStateToProps = (state) =\u003e ({\n        token: state.auth.token,\n        userName: state.auth.userName,\n        isAuthenticated: state.auth.isAuthenticated\n    });\n\n    return connect(mapStateToProps)(AuthenticatedComponent);\n\n}\n```\nA glance at `routes/index.js` shows you how to wrap a view or component using this function:\n\n```javascript\nimport {HomeView, LoginView, ProtectedView} from '../views';\nimport {requireAuthentication} from '../components/AuthenticatedComponent';\n\nexport default(\n    \u003cRoute path='/' component={App}\u003e\n        \u003cIndexRoute component={HomeView}/\u003e\n        \u003cRoute path=\"login\" component={LoginView}/\u003e\n        \u003cRoute path=\"protected\" component={requireAuthentication(ProtectedView)}/\u003e\n    \u003c/Route\u003e\n);\n```\n\nWhen we call `requireAuthentication(ProtectedView)`, we create an instance of `AuthenticatedComponent` and pass along our `ProtectedView` as an argument. `AuthenticatedComponent` connects to the Redux store, subscribing to the appropriate authentication state variables. It then handles authentication logic in its lifecycle methods to ensure that the protected component is not rendered if the store does not indicate successful authentication.\n\n---\n\n### redux-auth-wrapper\n\nThe [redux-auth-wrapper](https://github.com/mjrussell/redux-auth-wrapper) library uses this higher-order component approach to deliver a comprehensive authentication/authorization solution for those looking for something a bit more polished than this demonstration.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoshgeller%2Freact-redux-jwt-auth-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjoshgeller%2Freact-redux-jwt-auth-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjoshgeller%2Freact-redux-jwt-auth-example/lists"}