npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@automatiseerjouwproces/nextauth-azure-roles

v1.0.0

Published

NextAuth.js Azure AD provider with App Roles and role-based access control

Readme

NextAuth Azure Roles

A reusable NextAuth.js provider for Azure AD authentication with App Roles support and automatic role-based access control.

Features

  • 🔐 Azure AD authentication with NextAuth.js
  • 👥 Automatic role mapping from Azure AD App Roles
  • 🎭 Role-based access control (RBAC)
  • 🔄 Automatic user creation and role synchronization
  • 📊 Support for both App Roles and Group-based roles
  • 🎨 Built-in UI components for authentication
  • 🛡️ Type-safe with TypeScript

Installation

npm install @automatiseerjouwproces/nextauth-azure-roles
# or
yarn add @automatiseerjouwproces/nextauth-azure-roles
# or
pnpm add @automatiseerjouwproces/nextauth-azure-roles

Prerequisites

  • Next.js 14+
  • NextAuth.js 4.24+
  • Prisma ORM
  • Azure AD App Registration with App Roles configured

Setup

1. Azure AD Configuration

Create an Azure AD App Registration and configure:

  1. App Roles in your Azure AD application manifest:
{
  "appRoles": [
    {
      "allowedMemberTypes": ["User"],
      "description": "Admin users can manage all features",
      "displayName": "Admin",
      "id": "ccbedf5e-1a0c-4bdc-8241-254025666d8c",
      "isEnabled": true,
      "value": "YourApp.Admin"
    },
    {
      "allowedMemberTypes": ["User"],
      "description": "Regular users",
      "displayName": "User",
      "id": "583fd075-fcae-4f12-b456-491643dc910d",
      "isEnabled": true,
      "value": "YourApp.User"
    }
  ]
}
  1. API Permissions:

    • User.Read
    • Directory.Read.All
    • Application.Read.All
  2. Redirect URIs:

    • Add https://yourdomain.com/api/auth/callback/azure-ad

2. Environment Variables

Add to your .env.local:

# Azure AD
AZURE_AD_CLIENT_ID=your-client-id
AZURE_AD_CLIENT_SECRET=your-client-secret
AZURE_AD_TENANT_ID=your-tenant-id
AZURE_AD_SERVICE_PRINCIPAL_ID=your-service-principal-id

# NextAuth
NEXTAUTH_URL=https://yourdomain.com
NEXTAUTH_SECRET=your-secret-key

3. Prisma Schema

Add the required models to your schema.prisma:

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  image     String?
  role      String   @default("USER") // ADMIN or USER
  azureId   String?  @unique
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  accounts Account[]
  sessions Session[]
  
  @@map("users")
}

// Add NextAuth required models (Account, Session, VerificationToken)
// See: https://next-auth.js.org/adapters/prisma

4. NextAuth Configuration

Create src/app/api/auth/[...nextauth]/route.ts:

import { createAzureADAuthHandler } from '@automatiseerjouwproces/nextauth-azure-roles'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

const handler = createAzureADAuthHandler({
  prisma,
  roleMapping: {
    'YourApp.Admin': 'ADMIN',
    'YourApp.User': 'USER'
  },
  pages: {
    signIn: '/auth/signin',
    error: '/auth/error'
  }
})

export { handler as GET, handler as POST }

5. Session Provider

Wrap your app with SessionProvider:

// app/providers.tsx
'use client'

import { SessionProvider } from 'next-auth/react'

export function Providers({ children }: { children: React.ReactNode }) {
  return <SessionProvider>{children}</SessionProvider>
}

// app/layout.tsx
import { Providers } from './providers'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}

Usage

Auth Guard Component

Protect routes with role-based access:

import { AuthGuard } from '@automatiseerjouwproces/nextauth-azure-roles'

export default function AdminPage() {
  return (
    <AuthGuard requiredRole="ADMIN">
      <div>Admin only content</div>
    </AuthGuard>
  )
}

Sign In Page

import { AzureSignInButton } from '@automatiseerjouwproces/nextauth-azure-roles'

export default function SignInPage() {
  return (
    <div>
      <h1>Sign In</h1>
      <AzureSignInButton />
    </div>
  )
}

Access User Session

'use client'

import { useSession } from 'next-auth/react'

export default function Profile() {
  const { data: session } = useSession()

  return (
    <div>
      <p>Name: {session?.user?.name}</p>
      <p>Email: {session?.user?.email}</p>
      <p>Role: {session?.user?.role}</p>
    </div>
  )
}

Get User Initials

import { getInitialsFromName } from '@automatiseerjouwproces/nextauth-azure-roles'

const initials = getInitialsFromName('John Doe') // Returns 'JD'

API Reference

createAzureADAuthHandler(options)

Creates a NextAuth handler with Azure AD provider configured.

Options:

  • prisma (required): Prisma client instance
  • roleMapping (required): Object mapping Azure AD roles to your app roles
  • pages (optional): Custom auth pages
  • debug (optional): Enable debug logging

<AuthGuard>

Component to protect routes based on user roles.

Props:

  • requiredRole (optional): Required role to access the content
  • fallback (optional): Component to show when access is denied
  • children (required): Content to protect

<AzureSignInButton>

Pre-styled sign in button for Azure AD.

Props:

  • className (optional): Additional CSS classes
  • callbackUrl (optional): Redirect URL after sign in

getInitialsFromName(name)

Utility to extract initials from a full name.

Parameters:

  • name (string): Full name

Returns: Initials (e.g., "JD" for "John Doe")

Role Mapping

The package automatically maps Azure AD App Roles to your application roles:

roleMapping: {
  'YourApp.Admin': 'ADMIN',      // Azure AD role -> App role
  'YourApp.User': 'USER',
  'YourApp.Manager': 'MANAGER'
}

Users without any mapped roles will be denied access.

Type Safety

The package extends NextAuth types:

import type { Session } from 'next-auth'

// Session type includes:
interface Session {
  user: {
    id: string
    name?: string
    email?: string
    image?: string
    role: string  // Added by this package
  }
}

Troubleshooting

Role not detected

Ensure:

  1. User is assigned the role in Azure AD
  2. Service Principal ID is correct in env variables
  3. API permissions are granted admin consent
  4. Role value matches your roleMapping configuration

Session not persisting

Check:

  1. NEXTAUTH_URL matches your domain
  2. NEXTAUTH_SECRET is set
  3. Cookies are not blocked
  4. HTTPS is used in production

Examples

See the /examples directory for complete implementations:

  • Basic setup
  • Multi-tenant configuration
  • Custom role logic
  • Group-based roles

Contributing

Contributions are welcome! Please read our Contributing Guide.

License

MIT © Automatiseer Jouw Proces

Support