5 Best ways to implement authentication in React.js

Authentication is crucial in any user-based application and in this blog we describe 5 easy ways we can implement authentication with in React.js

08th July, 202410 min readJavaScriptReactJs
5 Best ways to implement authentication in React.js

1. Using Firebase Authentication

Firebase provides a robust and easy-to-integrate authentication system with support for various providers.

Example

  1. Install Firebase:

    npm install firebase
    
  2. Firebase Configuration:

    // src/firebase.js
    import firebase from 'firebase/app';
    import 'firebase/auth';
    
    const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_AUTH_DOMAIN",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_STORAGE_BUCKET",
      messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
      appId: "YOUR_APP_ID"
    };
    
    if (!firebase.apps.length) {
      firebase.initializeApp(firebaseConfig);
    }
    
    export const auth = firebase.auth();
    
  3. Sign-In and Sign-Out:

    // src/components/SignIn.js
    import React from 'react';
    import { auth } from '../firebase';
    
    const SignIn = () => {
      const signInWithGoogle = () => {
        const provider = new firebase.auth.GoogleAuthProvider();
        auth.signInWithPopup(provider);
      };
    
      return <button onClick={signInWithGoogle}>Sign in with Google</button>;
    };
    
    export default SignIn;
    
    // src/components/SignOut.js
    import React from 'react';
    import { auth } from '../firebase';
    
    const SignOut = () => {
      return auth.currentUser && (
        <button onClick={() => auth.signOut()}>Sign Out</button>
      );
    };
    
    export default SignOut;
    

2. Using JSON Web Tokens (JWT)

JWT is a popular method for stateless authentication.

Example

  1. Backend Setup:

    // Node.js Express example for generating JWT
    const express = require('express');
    const jwt = require('jsonwebtoken');
    const bodyParser = require('body-parser');
    
    const app = express();
    app.use(bodyParser.json());
    
    app.post('/login', (req, res) => {
      const { username, password } = req.body;
      // Validate user credentials
      const token = jwt.sign({ username }, 'your_jwt_secret');
      res.json({ token });
    });
    
    app.listen(3001, () => console.log('Server started on port 3001'));
    
  2. React Frontend:

    // src/App.js
    import React, { useState } from 'react';
    
    const App = () => {
      const [token, setToken] = useState('');
    
      const login = async () => {
        const response = await fetch('http://localhost:3001/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ username: 'user', password: 'pass' })
        });
    
        const data = await response.json();
        setToken(data.token);
      };
    
      return (
        <div>
          <button onClick={login}>Login</button>
          {token && <p>Token: {token}</p>}
        </div>
      );
    };
    
    export default App;
    

3. Using Auth0

Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications.

Example

  1. Install Auth0:

    npm install @auth0/auth0-react
    
  2. Auth0 Configuration:

    // src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Auth0Provider } from '@auth0/auth0-react';
    import App from './App';
    
    ReactDOM.render(
      <Auth0Provider
        domain="YOUR_AUTH0_DOMAIN"
        clientId="YOUR_AUTH0_CLIENT_ID"
        redirectUri={window.location.origin}
      >
        <App />
      </Auth0Provider>,
      document.getElementById('root')
    );
    
  3. Login and Logout:

    // src/App.js
    import React from 'react';
    import { useAuth0 } from '@auth0/auth0-react';
    
    const App = () => {
      const { loginWithRedirect, logout, user, isAuthenticated } = useAuth0();
    
      return (
        <div>
          {!isAuthenticated && (
            <button onClick={() => loginWithRedirect()}>Log in</button>
          )}
          {isAuthenticated && (
            <div>
              <button onClick={() => logout({ returnTo: window.location.origin })}>
                Log out
              </button>
              <p>Hello, {user.name}</p>
            </div>
          )}
        </div>
      );
    };
    
    export default App;
    

4. Using Passport.js with Express

Passport.js is a popular library for authentication in Node.js applications.

Example

  1. Backend Setup:

    // server.js
    const express = require('express');
    const passport = require('passport');
    const LocalStrategy = require('passport-local').Strategy;
    const session = require('express-session');
    const bodyParser = require('body-parser');
    
    const app = express();
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
    app.use(passport.initialize());
    app.use(passport.session());
    
    passport.use(new LocalStrategy(
      (username, password, done) => {
        // Replace with your user validation logic
        if (username === 'user' && password === 'pass') {
          return done(null, { id: 1, name: 'User' });
        } else {
          return done(null, false);
        }
      }
    ));
    
    passport.serializeUser((user, done) => {
      done(null, user.id);
    });
    
    passport.deserializeUser((id, done) => {
      // Replace with your user retrieval logic
      done(null, { id: 1, name: 'User' });
    });
    
    app.post('/login', passport.authenticate('local'), (req, res) => {
      res.send('Logged in');
    });
    
    app.listen(3001, () => console.log('Server started on port 3001'));
    
  2. React Frontend:

    // src/App.js
    import React from 'react';
    
    const App = () => {
      const login = async () => {
        const response = await fetch('http://localhost:3001/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: new URLSearchParams({ username: 'user', password: 'pass' })
        });
    
        if (response.ok) {
          alert('Logged in');
        } else {
          alert('Login failed');
        }
      };
    
      return (
        <div>
          <button onClick={login}>Login</button>
        </div>
      );
    };
    
    export default App;
    

5. Using AWS Amplify

AWS Amplify simplifies the integration of cloud-based authentication services.

Example

  1. Install AWS Amplify:

    npm install aws-amplify @aws-amplify/ui-react
    
  2. AWS Amplify Configuration:

    // src/aws-exports.js
    const awsmobile = {
      Auth: {
        region: 'YOUR_REGION',
        userPoolId: 'YOUR_USER_POOL_ID',
        userPoolWebClientId: 'YOUR_USER_POOL_WEB_CLIENT_ID'
      }
    };
    
    export default awsmobile;
    
  3. Configure Amplify:

    // src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import Amplify from 'aws-amplify';
    import config from './aws-exports';
    
    Amplify.configure(config);
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
  4. Authentication Components:

    // src/App.js
    import React from 'react';
    import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
    
    const App = () => {
      return (
        <div>
          <h1>Welcome to AWS Amplify Authentication</h1>
          <AmplifySignOut />
        </div>
      );
    };
    
    export default withAuthenticator(App);
    

These examples cover a range of popular methods to implement authentication in React.js applications, each suitable for different scenarios and requirements.