├── .eslintrc ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── src ├── App.css ├── App.js ├── App.test.js ├── components │ ├── AuthService.js │ ├── Login.css │ ├── Login.js │ └── withAuth.js ├── index.css ├── index.js ├── logo.svg └── registerServiceWorker.js └── yarn.lock /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "react-app" 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React JWT Authentication System 2 | 3 | First install all the dependencies 4 | ```sh 5 | npm install 6 | ``` 7 | 8 | To start the app type 9 | ```sh 10 | npm start 11 | ``` 12 | 13 | 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jwt-react-auth", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "jwt-decode": "^2.2.0", 7 | "react": "^15.6.1", 8 | "react-dom": "^15.6.1", 9 | "react-router-dom": "^4.2.2", 10 | "react-scripts": "1.0.12" 11 | }, 12 | "scripts": { 13 | "start": "react-scripts start", 14 | "build": "react-scripts build", 15 | "test": "react-scripts test --env=jsdom", 16 | "eject": "react-scripts eject" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pantharshit00/jwt-react-auth/af9058afa7fae6849d788bb1fc44c3417bc01d8e/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 80px; 8 | } 9 | 10 | .App-header { 11 | background-color: #222; 12 | height: 150px; 13 | padding: 20px; 14 | color: white; 15 | } 16 | 17 | .App-intro { 18 | font-size: large; 19 | } 20 | 21 | @keyframes App-logo-spin { 22 | from { transform: rotate(0deg); } 23 | to { transform: rotate(360deg); } 24 | } 25 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | import AuthService from './components/AuthService'; 5 | import withAuth from './components/withAuth'; 6 | const Auth = new AuthService(); 7 | 8 | class App extends Component { 9 | 10 | handleLogout(){ 11 | Auth.logout() 12 | this.props.history.replace('/login'); 13 | } 14 | 15 | render() { 16 | return ( 17 |
18 |
19 | logo 20 |

Welcome {this.props.user.username}

21 |
22 |

23 | 24 |

25 |
26 | ); 27 | } 28 | } 29 | 30 | export default withAuth(App); 31 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | }); 9 | -------------------------------------------------------------------------------- /src/components/AuthService.js: -------------------------------------------------------------------------------- 1 | import decode from 'jwt-decode'; 2 | export default class AuthService { 3 | constructor(domain) { 4 | this.domain = domain || 'http://localhost:8080' 5 | this.fetch = this.fetch.bind(this) 6 | this.login = this.login.bind(this) 7 | this.getProfile = this.getProfile.bind(this) 8 | } 9 | 10 | login(username, password) { 11 | // Get a token 12 | return this.fetch(`${this.domain}/login`, { 13 | method: 'POST', 14 | body: JSON.stringify({ 15 | username, 16 | password 17 | }) 18 | }).then(res => { 19 | this.setToken(res.token) 20 | return Promise.resolve(res); 21 | }) 22 | } 23 | 24 | loggedIn() { 25 | // Checks if there is a saved token and it's still valid 26 | const token = this.getToken() 27 | return !!token && !this.isTokenExpired(token) // handwaiving here 28 | } 29 | 30 | isTokenExpired(token) { 31 | try { 32 | const decoded = decode(token); 33 | if (decoded.exp < Date.now() / 1000) { 34 | return true; 35 | } 36 | else 37 | return false; 38 | } 39 | catch (err) { 40 | return false; 41 | } 42 | } 43 | 44 | setToken(idToken) { 45 | // Saves user token to localStorage 46 | localStorage.setItem('id_token', idToken) 47 | } 48 | 49 | getToken() { 50 | // Retrieves the user token from localStorage 51 | return localStorage.getItem('id_token') 52 | } 53 | 54 | logout() { 55 | // Clear user token and profile data from localStorage 56 | localStorage.removeItem('id_token'); 57 | } 58 | 59 | getProfile() { 60 | return decode(this.getToken()); 61 | } 62 | 63 | 64 | fetch(url, options) { 65 | // performs api calls sending the required authentication headers 66 | const headers = { 67 | 'Accept': 'application/json', 68 | 'Content-Type': 'application/json' 69 | } 70 | 71 | if (this.loggedIn()) { 72 | headers['Authorization'] = 'Bearer ' + this.getToken() 73 | } 74 | 75 | return fetch(url, { 76 | headers, 77 | ...options 78 | }) 79 | .then(this._checkStatus) 80 | .then(response => response.json()) 81 | } 82 | 83 | _checkStatus(response) { 84 | // raises an error in case response status is not a success 85 | if (response.status >= 200 && response.status < 300) { 86 | return response 87 | } else { 88 | var error = new Error(response.statusText) 89 | error.response = response 90 | throw error 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /src/components/Login.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css?family=Raleway'); 2 | 3 | .center{ 4 | font-family: 'Raleway', sans-serif; 5 | background-color: #1abc9c; 6 | position: absolute; 7 | height: 100%; 8 | width: 100%; 9 | display: flex; 10 | justify-content: center; 11 | align-items: center; 12 | } 13 | 14 | .card{ 15 | background-color: #fff; 16 | border-radius: 15px; 17 | padding: 0.8rem; 18 | } 19 | 20 | .card > form{ 21 | display: flex; 22 | flex-direction: column; 23 | } 24 | 25 | .card h1{ 26 | text-align: center; 27 | margin-top: 0; 28 | margin-bottom: 10px; 29 | } 30 | 31 | .form-item{ 32 | font-family: 'Raleway', sans-serif; 33 | padding: 5px; 34 | margin-bottom: 2rem; 35 | height: 30px; 36 | width: 16rem; 37 | border: 1px solid grey; 38 | } 39 | 40 | .form-submit{ 41 | font-family: 'Raleway', sans-serif; 42 | height: 35px; 43 | color: #fff; 44 | background-color: #1abc9c; 45 | border: none; 46 | letter-spacing: 0.2rem; 47 | transition: 0.3s opacity ease; 48 | cursor: pointer; 49 | } 50 | .form-submit:hover{ 51 | opacity: 0.6; 52 | } 53 | 54 | -------------------------------------------------------------------------------- /src/components/Login.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import './Login.css'; 3 | import AuthService from './AuthService'; 4 | 5 | class Login extends Component { 6 | constructor(){ 7 | super(); 8 | this.handleChange = this.handleChange.bind(this); 9 | this.handleFormSubmit = this.handleFormSubmit.bind(this); 10 | this.Auth = new AuthService(); 11 | } 12 | componentWillMount(){ 13 | if(this.Auth.loggedIn()) 14 | this.props.history.replace('/'); 15 | } 16 | render() { 17 | return ( 18 |
19 |
20 |

Login

21 |
22 | 29 | 36 | 41 |
42 |
43 |
44 | ); 45 | } 46 | 47 | handleFormSubmit(e){ 48 | e.preventDefault(); 49 | 50 | this.Auth.login(this.state.username,this.state.password) 51 | .then(res =>{ 52 | this.props.history.replace('/'); 53 | }) 54 | .catch(err =>{ 55 | alert(err); 56 | }) 57 | } 58 | 59 | handleChange(e){ 60 | this.setState( 61 | { 62 | [e.target.name]: e.target.value 63 | } 64 | ) 65 | } 66 | } 67 | 68 | export default Login; -------------------------------------------------------------------------------- /src/components/withAuth.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import AuthService from './AuthService'; 3 | 4 | export default function withAuth(AuthComponent) { 5 | const Auth = new AuthService('http://localhost:8080'); 6 | return class AuthWrapped extends Component { 7 | constructor() { 8 | super(); 9 | this.state = { 10 | user: null 11 | } 12 | } 13 | componentWillMount() { 14 | if (!Auth.loggedIn()) { 15 | this.props.history.replace('/login') 16 | } 17 | else { 18 | try { 19 | const profile = Auth.getProfile() 20 | this.setState({ 21 | user: profile 22 | }) 23 | } 24 | catch(err){ 25 | Auth.logout() 26 | this.props.history.replace('/login') 27 | } 28 | } 29 | } 30 | 31 | render() { 32 | if (this.state.user) { 33 | return ( 34 | 35 | ) 36 | } 37 | else { 38 | return null 39 | } 40 | } 41 | }; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import registerServiceWorker from './registerServiceWorker'; 6 | import { Route, BrowserRouter as Router } from 'react-router-dom'; 7 | 8 | // Our Components 9 | import Login from './components/Login'; 10 | 11 | ReactDOM.render( 12 | 13 |
14 | 15 | 16 |
17 |
18 | , document.getElementById('root') 19 | ); 20 | registerServiceWorker(); 21 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/registerServiceWorker.js: -------------------------------------------------------------------------------- 1 | // In production, we register a service worker to serve assets from local cache. 2 | 3 | // This lets the app load faster on subsequent visits in production, and gives 4 | // it offline capabilities. However, it also means that developers (and users) 5 | // will only see deployed updates on the "N+1" visit to a page, since previously 6 | // cached resources are updated in the background. 7 | 8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. 9 | // This link also includes instructions on opting out of this behavior. 10 | 11 | const isLocalhost = Boolean( 12 | window.location.hostname === 'localhost' || 13 | // [::1] is the IPv6 localhost address. 14 | window.location.hostname === '[::1]' || 15 | // 127.0.0.1/8 is considered localhost for IPv4. 16 | window.location.hostname.match( 17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 18 | ) 19 | ); 20 | 21 | export default function register() { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (!isLocalhost) { 36 | // Is not local host. Just register service worker 37 | registerValidSW(swUrl); 38 | } else { 39 | // This is running on localhost. Lets check if a service worker still exists or not. 40 | checkValidServiceWorker(swUrl); 41 | } 42 | }); 43 | } 44 | } 45 | 46 | function registerValidSW(swUrl) { 47 | navigator.serviceWorker 48 | .register(swUrl) 49 | .then(registration => { 50 | registration.onupdatefound = () => { 51 | const installingWorker = registration.installing; 52 | installingWorker.onstatechange = () => { 53 | if (installingWorker.state === 'installed') { 54 | if (navigator.serviceWorker.controller) { 55 | // At this point, the old content will have been purged and 56 | // the fresh content will have been added to the cache. 57 | // It's the perfect time to display a "New content is 58 | // available; please refresh." message in your web app. 59 | console.log('New content is available; please refresh.'); 60 | } else { 61 | // At this point, everything has been precached. 62 | // It's the perfect time to display a 63 | // "Content is cached for offline use." message. 64 | console.log('Content is cached for offline use.'); 65 | } 66 | } 67 | }; 68 | }; 69 | }) 70 | .catch(error => { 71 | console.error('Error during service worker registration:', error); 72 | }); 73 | } 74 | 75 | function checkValidServiceWorker(swUrl) { 76 | // Check if the service worker can be found. If it can't reload the page. 77 | fetch(swUrl) 78 | .then(response => { 79 | // Ensure service worker exists, and that we really are getting a JS file. 80 | if ( 81 | response.status === 404 || 82 | response.headers.get('content-type').indexOf('javascript') === -1 83 | ) { 84 | // No service worker found. Probably a different app. Reload the page. 85 | navigator.serviceWorker.ready.then(registration => { 86 | registration.unregister().then(() => { 87 | window.location.reload(); 88 | }); 89 | }); 90 | } else { 91 | // Service worker found. Proceed as normal. 92 | registerValidSW(swUrl); 93 | } 94 | }) 95 | .catch(() => { 96 | console.log( 97 | 'No internet connection found. App is running in offline mode.' 98 | ); 99 | }); 100 | } 101 | 102 | export function unregister() { 103 | if ('serviceWorker' in navigator) { 104 | navigator.serviceWorker.ready.then(registration => { 105 | registration.unregister(); 106 | }); 107 | } 108 | } 109 | --------------------------------------------------------------------------------