@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-rolesPrerequisites
- 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:
- 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"
}
]
}API Permissions:
User.ReadDirectory.Read.AllApplication.Read.All
Redirect URIs:
- Add
https://yourdomain.com/api/auth/callback/azure-ad
- Add
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-key3. 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/prisma4. 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 instanceroleMapping(required): Object mapping Azure AD roles to your app rolespages(optional): Custom auth pagesdebug(optional): Enable debug logging
<AuthGuard>
Component to protect routes based on user roles.
Props:
requiredRole(optional): Required role to access the contentfallback(optional): Component to show when access is deniedchildren(required): Content to protect
<AzureSignInButton>
Pre-styled sign in button for Azure AD.
Props:
className(optional): Additional CSS classescallbackUrl(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:
- User is assigned the role in Azure AD
- Service Principal ID is correct in env variables
- API permissions are granted admin consent
- Role value matches your
roleMappingconfiguration
Session not persisting
Check:
NEXTAUTH_URLmatches your domainNEXTAUTH_SECRETis set- Cookies are not blocked
- 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
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📖 Docs: Full Documentation
