├── .gitignore
├── .vscode
└── settings.json
├── README.md
├── middleware.js
├── models
└── User.js
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
├── server.js
└── src
├── App.css
├── App.js
├── App.test.js
├── Home.jsx
├── Login.jsx
├── Secret.jsx
├── index.css
├── index.js
├── logo.svg
├── registerServiceWorker.js
└── withAuth.jsx
/.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 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "eslint.enable": false
3 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Authentication Example
2 |
3 | This is an example application I created to showcase how to implement authentication on a web application using React and react-router on the frontend and node.js, express, mongodb, and mongoose on the backend.
4 |
5 | The [associated blog post](https://medium.com/@faizanv/authentication-for-your-react-and-express-application-w-json-web-tokens-923515826e0) for this example can be found [here](https://medium.com/@faizanv/authentication-for-your-react-and-express-application-w-json-web-tokens-923515826e0).
6 |
7 | To run the application first clone the repository
8 | ```
9 | git clone https://github.com/faizanv/react-auth-example.git
10 | ```
11 |
12 | Install the dependencies
13 | ```
14 | npm install
15 | ```
16 | Make sure that MongoDB is running
17 | ```
18 | mongod
19 | ```
20 | run the server
21 | ```
22 | npm run server
23 | ```
24 | and then in a separate window/tab run the frontend
25 | ```
26 | npm start
27 | ```
28 | The application should be running at [http://localhost:3000/](http://localhost:3000/)
29 |
30 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
31 | You can find the most recent version of their guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
--------------------------------------------------------------------------------
/middleware.js:
--------------------------------------------------------------------------------
1 | const jwt = require('jsonwebtoken');
2 | const secret = 'mysecretsshhh';
3 |
4 | const withAuth = function(req, res, next) {
5 | const token =
6 | req.body.token ||
7 | req.query.token ||
8 | req.headers['x-access-token'] ||
9 | req.cookies.token;
10 |
11 | if (!token) {
12 | res.status(401).send('Unauthorized: No token provided');
13 | } else {
14 | jwt.verify(token, secret, function(err, decoded) {
15 | if (err) {
16 | res.status(401).send('Unauthorized: Invalid token');
17 | } else {
18 | req.email = decoded.email;
19 | next();
20 | }
21 | });
22 | }
23 | }
24 |
25 | module.exports = withAuth;
--------------------------------------------------------------------------------
/models/User.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 | const bcrypt = require('bcrypt');
3 |
4 | const saltRounds = 10;
5 |
6 | const UserSchema = new mongoose.Schema({
7 | email: { type: String, required: true, unique: true },
8 | password: { type: String, required: true }
9 | });
10 |
11 | UserSchema.pre('save', function(next) {
12 | if (this.isNew || this.isModified('password')) {
13 | const document = this;
14 | bcrypt.hash(this.password, saltRounds, function(err, hashedPassword) {
15 | if (err) {
16 | next(err);
17 | } else {
18 | document.password = hashedPassword;
19 | next();
20 | }
21 | });
22 | } else {
23 | next();
24 | }
25 | });
26 |
27 | UserSchema.methods.isCorrectPassword = function(password, callback) {
28 | bcrypt.compare(password, this.password, function(err, same) {
29 | if (err) {
30 | callback(err);
31 | } else {
32 | callback(err, same);
33 | }
34 | });
35 | }
36 |
37 | module.exports = mongoose.model('User', UserSchema);
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-auth-example",
3 | "version": "1.0.0",
4 | "private": true,
5 | "dependencies": {
6 | "bcrypt": "^5.0.1",
7 | "body-parser": "^1.19.0",
8 | "cookie-parser": "^1.4.5",
9 | "express": "^4.17.1",
10 | "jsonwebtoken": "^8.5.1",
11 | "mongoose": "^5.12.4",
12 | "react": "^17.0.2",
13 | "react-dom": "^17.0.2",
14 | "react-router-dom": "^5.2.0",
15 | "react-scripts": "4.0.3"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test --env=jsdom",
21 | "eject": "react-scripts eject",
22 | "server": "node server.js",
23 | "server-dev": "nodemon server.js"
24 | },
25 | "proxy": "http://localhost:8080",
26 | "devDependencies": {
27 | "nodemon": "^2.0.0"
28 | },
29 | "browserslist": [
30 | ">0.2%",
31 | "not dead",
32 | "not ie <= 11",
33 | "not op_mini all"
34 | ]
35 | }
36 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faizanv/react-auth-example/6d3a4802464d6220c9b76eed595f04d58e9c6a1a/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
22 | React Auth Example
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": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": "./index.html",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const bodyParser = require('body-parser');
3 | const cookieParser = require('cookie-parser');
4 | const path = require('path');
5 | const jwt = require('jsonwebtoken');
6 | const mongoose = require('mongoose');
7 | const User = require('./models/User');
8 | const withAuth = require('./middleware');
9 |
10 | const app = express();
11 |
12 | const secret = 'mysecretsshhh';
13 |
14 | app.use(bodyParser.urlencoded({ extended: false }));
15 | app.use(bodyParser.json());
16 | app.use(cookieParser());
17 |
18 | const mongo_uri = 'mongodb://localhost/react-auth';
19 | mongoose.connect(mongo_uri, { useNewUrlParser: true, useUnifiedTopology: true }, function(err) {
20 | if (err) {
21 | throw err;
22 | } else {
23 | console.log(`Successfully connected to ${mongo_uri}`);
24 | }
25 | });
26 |
27 | app.use(express.static(path.join(__dirname, 'public')));
28 |
29 |
30 | app.get('/', function (req, res) {
31 | res.sendFile(path.join(__dirname, 'public', 'index.html'));
32 | });
33 |
34 | app.get('/api/home', function(req, res) {
35 | res.send('Welcome!');
36 | });
37 |
38 | app.get('/api/secret', withAuth, function(req, res) {
39 | res.send('The password is potato');
40 | });
41 |
42 | app.post('/api/register', function(req, res) {
43 | const { email, password } = req.body;
44 | const user = new User({ email, password });
45 | user.save(function(err) {
46 | if (err) {
47 | console.log(err);
48 | res.status(500).send("Error registering new user please try again.");
49 | } else {
50 | res.status(200).send("Welcome to the club!");
51 | }
52 | });
53 | });
54 |
55 | app.post('/api/authenticate', function(req, res) {
56 | const { email, password } = req.body;
57 | User.findOne({ email }, function(err, user) {
58 | if (err) {
59 | console.error(err);
60 | res.status(500)
61 | .json({
62 | error: 'Internal error please try again'
63 | });
64 | } else if (!user) {
65 | res.status(401)
66 | .json({
67 | error: 'Incorrect email or password'
68 | });
69 | } else {
70 | user.isCorrectPassword(password, function(err, same) {
71 | if (err) {
72 | res.status(500)
73 | .json({
74 | error: 'Internal error please try again'
75 | });
76 | } else if (!same) {
77 | res.status(401)
78 | .json({
79 | error: 'Incorrect email or password'
80 | });
81 | } else {
82 | // Issue token
83 | const payload = { email };
84 | const token = jwt.sign(payload, secret, {
85 | expiresIn: '1h'
86 | });
87 | res.cookie('token', token, { httpOnly: true }).sendStatus(200);
88 | }
89 | });
90 | }
91 | });
92 | });
93 |
94 | app.get('/checkToken', withAuth, function(req, res) {
95 | res.sendStatus(200);
96 | });
97 |
98 | app.listen(process.env.PORT || 8080);
99 |
--------------------------------------------------------------------------------
/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-title {
18 | font-size: 1.5em;
19 | }
20 |
21 | .App-intro {
22 | font-size: large;
23 | }
24 |
25 | @keyframes App-logo-spin {
26 | from { transform: rotate(0deg); }
27 | to { transform: rotate(360deg); }
28 | }
29 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Link, Route, Switch } from 'react-router-dom';
3 | import withAuth from './withAuth';
4 | import Home from './Home';
5 | import Secret from './Secret';
6 | import Login from './Login';
7 |
8 | class App extends Component {
9 | render() {
10 | return (
11 |
12 |
13 | - Home
14 | - Secret
15 | - Login
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | );
25 | }
26 | }
27 |
28 | export default App;
29 |
--------------------------------------------------------------------------------
/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 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/Home.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 |
3 | export default class Home extends Component {
4 | constructor() {
5 | super();
6 | this.state = {
7 | message: 'Loading...'
8 | }
9 | }
10 |
11 | componentDidMount() {
12 | fetch('/api/home')
13 | .then(res => res.text())
14 | .then(res => this.setState({message: res}));
15 | }
16 |
17 | render() {
18 | return (
19 |
20 |
Home
21 |
{this.state.message}
22 |
23 | );
24 | }
25 | }
--------------------------------------------------------------------------------
/src/Login.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 |
3 | export default class Login extends Component {
4 | constructor(props) {
5 | super(props)
6 | this.state = {
7 | email : '',
8 | password: ''
9 | };
10 | }
11 |
12 | handleInputChange = (event) => {
13 | const { value, name } = event.target;
14 | this.setState({
15 | [name]: value
16 | });
17 | }
18 |
19 | onSubmit = (event) => {
20 | event.preventDefault();
21 | fetch('/api/authenticate', {
22 | method: 'POST',
23 | body: JSON.stringify(this.state),
24 | headers: {
25 | 'Content-Type': 'application/json'
26 | }
27 | })
28 | .then(res => {
29 | if (res.status === 200) {
30 | this.props.history.push('/');
31 | } else {
32 | const error = new Error(res.error);
33 | throw error;
34 | }
35 | })
36 | .catch(err => {
37 | console.error(err);
38 | alert('Error logging in please try again');
39 | });
40 | }
41 |
42 | render() {
43 | return (
44 |
64 | );
65 | }
66 | }
--------------------------------------------------------------------------------
/src/Secret.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 |
3 | export default class Secret extends Component {
4 | constructor() {
5 | super();
6 | this.state = {
7 | message: 'Loading...'
8 | }
9 | }
10 |
11 | componentDidMount() {
12 | fetch('/api/secret')
13 | .then(res => res.text())
14 | .then(res => this.setState({message: res}));
15 | }
16 |
17 | render() {
18 | return (
19 |
20 |
Secret
21 |
{this.state.message}
22 |
23 | );
24 | }
25 | }
--------------------------------------------------------------------------------
/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 { BrowserRouter } from "react-router-dom";
4 | import './index.css';
5 | import App from './App';
6 | import registerServiceWorker from './registerServiceWorker';
7 |
8 | ReactDOM.render(
9 |
10 |
11 | ,
12 | document.getElementById('root'));
13 |
14 | registerServiceWorker();
15 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
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 | // This is running on localhost. Lets check if a service worker still exists or not.
37 | checkValidServiceWorker(swUrl);
38 |
39 | // Add some additional logging to localhost, pointing developers to the
40 | // service worker/PWA documentation.
41 | navigator.serviceWorker.ready.then(() => {
42 | console.log(
43 | 'This web app is being served cache-first by a service ' +
44 | 'worker. To learn more, visit https://goo.gl/SC7cgQ'
45 | );
46 | });
47 | } else {
48 | // Is not local host. Just register service worker
49 | registerValidSW(swUrl);
50 | }
51 | });
52 | }
53 | }
54 |
55 | function registerValidSW(swUrl) {
56 | navigator.serviceWorker
57 | .register(swUrl)
58 | .then(registration => {
59 | registration.onupdatefound = () => {
60 | const installingWorker = registration.installing;
61 | installingWorker.onstatechange = () => {
62 | if (installingWorker.state === 'installed') {
63 | if (navigator.serviceWorker.controller) {
64 | // At this point, the old content will have been purged and
65 | // the fresh content will have been added to the cache.
66 | // It's the perfect time to display a "New content is
67 | // available; please refresh." message in your web app.
68 | console.log('New content is available; please refresh.');
69 | } else {
70 | // At this point, everything has been precached.
71 | // It's the perfect time to display a
72 | // "Content is cached for offline use." message.
73 | console.log('Content is cached for offline use.');
74 | }
75 | }
76 | };
77 | };
78 | })
79 | .catch(error => {
80 | console.error('Error during service worker registration:', error);
81 | });
82 | }
83 |
84 | function checkValidServiceWorker(swUrl) {
85 | // Check if the service worker can be found. If it can't reload the page.
86 | fetch(swUrl)
87 | .then(response => {
88 | // Ensure service worker exists, and that we really are getting a JS file.
89 | if (
90 | response.status === 404 ||
91 | response.headers.get('content-type').indexOf('javascript') === -1
92 | ) {
93 | // No service worker found. Probably a different app. Reload the page.
94 | navigator.serviceWorker.ready.then(registration => {
95 | registration.unregister().then(() => {
96 | window.location.reload();
97 | });
98 | });
99 | } else {
100 | // Service worker found. Proceed as normal.
101 | registerValidSW(swUrl);
102 | }
103 | })
104 | .catch(() => {
105 | console.log(
106 | 'No internet connection found. App is running in offline mode.'
107 | );
108 | });
109 | }
110 |
111 | export function unregister() {
112 | if ('serviceWorker' in navigator) {
113 | navigator.serviceWorker.ready.then(registration => {
114 | registration.unregister();
115 | });
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/withAuth.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Redirect } from 'react-router-dom';
3 |
4 | export default function withAuth(ComponentToProtect) {
5 | return class extends Component {
6 | constructor() {
7 | super();
8 | this.state = {
9 | loading: true,
10 | redirect: false,
11 | };
12 | }
13 |
14 | componentDidMount() {
15 | fetch('/checkToken')
16 | .then(res => {
17 | if (res.status === 200) {
18 | this.setState({ loading: false });
19 | } else {
20 | const error = new Error(res.error);
21 | throw error;
22 | }
23 | })
24 | .catch(err => {
25 | console.error(err);
26 | this.setState({ loading: false, redirect: true });
27 | });
28 | }
29 |
30 |
31 | render() {
32 | const { loading, redirect } = this.state;
33 | if (loading) {
34 | return null;
35 | }
36 | if (redirect) {
37 | return ;
38 | }
39 | return ;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------