Back to Snippets

React Higher Order Component For Role Based Authentication And Authorization

JavaScript Security April 13, 2026

This React higher-order component handles authentication and authorization by wrapping the provided component with authentication checks, ensuring only authorized users can access the component based on their roles. It is useful for restricting access to certain parts of an application. The component utilizes React Context API for state management and React Router for navigation, including error handling for unauthorized access attempts. It requires setup of the AuthContext and React Router in the application.

Snippet Stats

Lines 35
Characters 1,208
Read 1 min
javascript • 35 lines
import React, { useContext } from 'react';
import { Redirect, Route } from 'react-router-dom';
import { AuthContext } from './AuthContext';

/**
 * Higher-order component for authentication and authorization.
 *
 * @param {React.Component} WrappedComponent The component to wrap with authentication checks.
 * @param {string[]} allowedRoles The roles allowed to access the wrapped component.
 * @return {React.Component} The wrapped component with authentication checks.
 */
const withAuth = (WrappedComponent, allowedRoles) => {
  const AuthenticatedComponent = ({ ...props }) => {
    const { user } = useContext(AuthContext);

    // Check if the user is authenticated
    if (!user) {
      // Redirect to the login page if the user is not authenticated
      return <Redirect to='/login' />;
    }

    // Check if the user has the required role
    if (!allowedRoles.includes(user.role)) {
      // Return an error message if the user does not have the required role
      return <div>Unauthorized: User {user.username} does not have the required role</div>;
    }

    // Render the wrapped component if the user is authenticated and has the required role
    return <WrappedComponent {...props} />;
  };

  return AuthenticatedComponent;
};

export default withAuth;

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This React higher order component handles authentication and authorization by checking user credentials before rendering the wrapped component. It uti...

React Higher Order Component For Authentication And Authorization In Large Scale Applications

PHP
This snippet provides a custom WordPress plugin that utilizes hooks to modify the user registration process, allowing for additional validation and cu...

WordPress Custom Plugin Hooks For User Registration

PHP
Complete form handling pattern — nonce verification, input sanitization, validation with error messages, and secure redirect. Production-ready.

Sanitize and Validate Form Input