microsoft/power-platform-skills / plugins/power-pages/skills/setup-auth
setup-auth
VerifiedUse when the user asks to "set up authentication", "add login", "add logout", "add sign in", "enable auth", "add role-based access", "add authorization", "protect routes", "configure identity provider", "configure Entra ID", "configure Entra External ID", "configure OpenID Connect", "add OIDC", "set up SAML", "set up WS-Federation", "set up local login", "add Facebook login", "add Google sign in", "add Microsoft Account", or otherwise wants to set up authentication (login/logout) and role-based authorization for their Power Pages SPA site using any supported identity provider. Also sets up the IdP app registration for OIDC providers (Okta, Auth0, Entra External ID, and other OIDC) -- reads the provider's docs first, then either guides the user through the provider's console or, when the provider supports it, configures it for the user -- and wires the client ID, authority, and claims mapping into Power Pages.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 225.7 KB |
| assets/auth-report.html | other | 24.1 KB |
| references/authentication-reference.md | markdown | 168.1 KB |
| references/authorization-reference.md | markdown | 8.5 KB |
| references/idp-provisioning-reference.md | markdown | 6.9 KB |
| scripts/validate-auth.js | script | 6.5 KB |
references/authorization-reference.md
View on GitHub# Authorization Reference
This document provides the complete implementation patterns for role-based authorization in Power Pages SPA sites.
## Core Authorization Utilities
Create `src/utils/authorization.ts`:
```typescript
// IMPORTANT: Client-side authorization is for UX only, not security.
// Server-side table permissions enforce actual access control.
// Always configure table permissions via /integrate-webapi.
import { getCurrentUser, isAuthenticated as checkAuthenticated } from '../services/authService';
/**
* Returns the current user's web roles as an array of strings.
*/
export function getUserRoles(): string[] {
const user = getCurrentUser();
return user?.userRoles ?? [];
}
/**
* Checks if the current user has a specific role (case-insensitive).
*/
export function hasRole(roleName: string): boolean {
return getUserRoles().some(
(role) => role.toLowerCase() === roleName.toLowerCase()
);
}
/**
* Checks if the current user has ANY of the specified roles.
*/
export function hasAnyRole(roleNames: string[]): boolean {
return roleNames.some((role) => hasRole(role));
}
/**
* Checks if the current user has ALL of the specified roles.
*/
export function hasAllRoles(roleNames: string[]): boolean {
return roleNames.every((role) => hasRole(role));
}
/**
* Re-export isAuthenticated for convenience.
*/
export function isAuthenticated(): boolean {
return checkAuthenticated();
}
/**
* Checks if the current user has the Administrators role.
*/
export function isAdmin(): boolean {
return hasRole('Administrators');
}
/**
* Checks if the user has elevated access (admin or specified additional roles).
*/
export function hasElevatedAccess(additionalRoles: string[] = []): boolean {
return isAdmin() || hasAnyRole(additionalRoles);
}
```
---
## React Components
### RequireAuth
Create `src/components/RequireAuth.tsx`:
```tsx
import type { ReactNode } from 'react';
import { useAuth } from '../hooks/useAuth';
interface RequireAuthProps {
children: ReactNode;
fallback?: ReactNode;
}
/**
* Renders children only when the user is authenticated.
* Shows the fallback (or nothing) when not authenticated.
*/
export function RequireAuth({ children, fallback }: RequireAuthProps) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return null;
if (!isAuthenticated) return <>{fallback}</> || null;
return <>{children}</>;
}
```
### RequireRole
Create `src/components/RequireRole.tsx`:
```tsx
import type { ReactNode } from 'react';
import { useAuth } from '../hooks/useAuth';
import { hasAnyRole, hasAllRoles } from '../utils/authorization';
interface RequireRoleProps {
roles: string[];
requireAll?: boolean;
children: ReactNode;
fallback?: ReactNode;
}
/**
* Renders children only when the user has the required role(s).
* By default checks if the user has ANY of the listed roles.
* Set requireAll=true to require ALL roles.
*/
export function RequireRole({ roles, requireAll = false, children, fallback }: RequireRoleProps) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) return null;
if (!isAuthenticated) return <>{fallback}</> || null;
const hasAccess = requireAll ? hasAllRoles(roles) : hasAnyRole(roles);
if (!hasAccess) return <>{fallback}</> || null;
return <>{children}</>;
}
```
### useAuthorization Hook
Create `src/hooks/useAuthorization.ts`:
```typescript
import { useMemo } from 'react';
import { useAuth } from './useAuth';
import {
getUserRoles,
hasRole,
hasAnyRole,
hasAllRoles,
isAdmin,
} from '../utils/authorization';
export function useAuthorization() {
const { isAuthenticated } = useAuth();
const roles = useMemo(() => getUserRoles(), [isAuthenticated]);
return {
roles,
hasRole,
hasAnyRole,
hasAllRoles,
isAuthenticated,
isAdmin: isAdmin(),
};
}
```
---
## Vue 3 Patterns
### useAuthorization Composable
Create `src/composables/useAuthorization.ts`:
```typescript
import { computed } from 'vue';
import { useAuth } from './useAuth';
import {
getUserRoles,
hasRole,
hasAnyRole,
hasAllRoles,
isAdmin as checkAdmin,
} from '../utils/authorization';
export function useAuthorization() {
const { isAuthenticated } = useAuth();
const roles = computed(() => getUserRoles());
const isAdmin = computed(() => checkAdmin());
return {
roles,
isAuthenticated,
isAdmin,
hasRole,
hasAnyRole,
hasAllRoles,
};
}
```
### v-role Directive
Create `src/directives/vRole.ts`:
```typescript
import type { Directive } from 'vue';
import { hasRole, hasAnyRole } from '../utils/authorization';
/**
* Directive for role-based element visibility.
*
* Usage:
* <div v-role="'Administrators'">Admin only</div>
* <div v-role="['Administrators', 'Editors']">Admin or Editor</div>
*/
export const vRole: Directive<HTMLElement, string | string[]> = {
mounted(el, binding) {
const roles = binding.value;
const visible = Array.isArray(roles) ? hasAnyRole(roles) : hasRole(roles);
if (!visible) {
el.style.display = 'none';
}
},
updated(el, binding) {
const roles = binding.value;
const visible = Array.isArray(roles) ? hasAnyRole(roles) : hasRole(roles);
el.style.display = visible ? '' : 'none';
},
};
```
---
## Angular Patterns
### Auth Guard
Create `src/app/guards/auth.guard.ts`:
```typescript
import { inject } from '@angular/core';
import { type CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { hasAnyRole } from '../../utils/authorization';
/**
* Route guard that requires authentication.
*/
export const authGuard: CanActivateFn = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated) {
return true;
}
sessionStorage.setItem('redirectUrl', window.location.pathname);
router.navigate(['/']);
return false;
};
/**
* Route guard that requires specific roles.
* Configure required roles in route data: { roles: ['Administrators'] }
*/
export const roleGuard: CanActivateFn = (route) => {
const authService = inject(AuthService);
const router = inject(Router);
if (!authService.isAuthenticated) {
router.navigate(['/']);
return false;
}
const requiredRoles = route.data?.['roles'] as string[] | undefined;
if (requiredRoles && !hasAnyRole(requiredRoles)) {
router.navigate(['/']);
return false;
}
return true;
};
```
### HasRole Directive
Create `src/app/directives/has-role.directive.ts`:
```typescript
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { hasRole } from '../../utils/authorization';
/**
* Structural directive for role-based element visibility.
*
* Usage:
* <div *appHasRole="'Administrators'">Admin only</div>
*/
@Directive({ selector: '[appHasRole]', standalone: true })
export class HasRoleDirective {
@Input() set appHasRole(roleName: string) {
if (hasRole(roleName)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
constructor(
private templateRef: TemplateRef<unknown>,
private viewContainer: ViewContainerRef
) {}
}
```
---
## Common Usage Patterns
### Conditional Navigation
```tsx
{/* React example */}
<nav>
<Link to="/">Home</Link>
<RequireAuth>
<Link to="/dashboard">Dashboard</Link>
</RequireAuth>
<RequireRole roles={['Administrators']}>
<Link to="/admin">Admin</Link>
</RequireRole>
</nav>
```
### Conditional Action Buttons
```tsx
<RequireRole roles={['Administrators', 'Content Editors']}>
<button onClick={handleEdit}>Edit</button>
<button onClick={handleDelete}>Delete</button>
</RequireRole>
```
### Content Sections by Role
```tsx
<RequireAuth fallback={<p>Please sign in to view this content.</p>}>
<p>Welcome, {displayName}!</p>
<RequireRole roles={['Premium Users']} fallback={<p>Upgrade for premium content.</p>}>
<PremiumContent />
</RequireRole>
</RequireAuth>
```
---
## Security Considerations
**Client-side authorization is for UX only, not security.**
- The `window.Microsoft.Dynamic365.Portal.User.userRoles` array is set by the server and cannot be modified by the client in a way that affects server-side checks.
- However, hiding a UI element does NOT prevent a user from calling the underlying API directly.
- **Always configure server-side table permissions** to enforce data access control. Use `/integrate-webapi` to set up proper table permissions and site settings.
- Test both: verify the UI shows/hides correctly AND verify direct API calls respect table permissions.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 469k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 197k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |