delon-auth-authentication-authorization
Implement authentication and authorization using @delon/auth. Use this skill when adding login/logout flows, JWT token management, role-based access control (RBAC), route guards, HTTP interceptors, and session management. Integrates with Firebase Auth and custom permission systems. Ensures secure token storage, automatic token refresh, and consistent authorization checks across components and services.
What this skill does
# @delon/auth Authentication & Authorization Skill
This skill helps implement authentication and authorization using @delon/auth library.
## Core Principles
### Token Management
- **JWT Storage**: Secure token storage using DA_SERVICE_TOKEN
- **Auto Refresh**: Automatic token renewal before expiration
- **Interceptors**: Automatic token injection in HTTP requests
- **Logout**: Clean token removal and session cleanup
### Authorization
- **RBAC**: Role-based access control
- **Permissions**: Fine-grained permission checking
- **Guards**: Route protection with role/permission checks
- **ACL Integration**: Works with @delon/acl for UI-level controls
## Configuration
### App Config
```typescript
// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideDelonAuth, DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { JWTTokenModel } from '@delon/auth';
export const appConfig: ApplicationConfig = {
providers: [
provideDelonAuth({
token_send_key: 'Authorization',
token_send_template: 'Bearer ${token}',
token_send_place: 'header',
login_url: '/passport/login',
ignores: [/\/login/, /assets\//],
allow_anonymous_key: 'allow_anonymous',
executeOtherInterceptors: true,
refreshTime: 3000, // Refresh token check interval (ms)
refreshOffset: 6000 // Refresh token before expiration (ms)
})
]
};
```
### Token Model
```typescript
// src/app/core/models/auth-token.model.ts
import { JWTTokenModel } from '@delon/auth';
export interface AuthTokenModel extends JWTTokenModel {
token: string;
uid: string;
email: string;
displayName: string;
role: string;
permissions: string[];
exp: number;
}
```
## Authentication Service
```typescript
// src/app/core/services/auth.service.ts
import { Injectable, inject } from '@angular/core';
import { Router } from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { Auth, signInWithEmailAndPassword, signOut, User } from '@angular/fire/auth';
import { AuthTokenModel } from '@core/models/auth-token.model';
import { signal, computed } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthService {
private auth = inject(Auth);
private tokenService = inject<ITokenService>(DA_SERVICE_TOKEN);
private router = inject(Router);
// State
private currentUser = signal<User | null>(null);
private authToken = signal<AuthTokenModel | null>(null);
// Computed
isAuthenticated = computed(() => this.tokenService.get()?.token != null);
userRole = computed(() => this.authToken()?.role);
userPermissions = computed(() => this.authToken()?.permissions || []);
constructor() {
// Listen to Firebase Auth state
this.auth.onAuthStateChanged(async (user) => {
this.currentUser.set(user);
if (user) {
await this.refreshToken();
} else {
this.clearSession();
}
});
}
/**
* Login with email and password
*/
async login(email: string, password: string): Promise<void> {
try {
const credential = await signInWithEmailAndPassword(this.auth, email, password);
const token = await credential.user.getIdToken();
const tokenData = await this.parseToken(token);
// Store token in @delon/auth
this.tokenService.set(tokenData);
this.authToken.set(tokenData);
// Navigate to dashboard
await this.router.navigateByUrl('/dashboard');
} catch (error) {
console.error('Login failed:', error);
throw error;
}
}
/**
* Logout
*/
async logout(): Promise<void> {
try {
await signOut(this.auth);
this.clearSession();
await this.router.navigateByUrl('/passport/login');
} catch (error) {
console.error('Logout failed:', error);
throw error;
}
}
/**
* Refresh token
*/
async refreshToken(): Promise<void> {
const user = this.currentUser();
if (!user) return;
try {
const token = await user.getIdToken(true); // Force refresh
const tokenData = await this.parseToken(token);
this.tokenService.set(tokenData);
this.authToken.set(tokenData);
} catch (error) {
console.error('Token refresh failed:', error);
await this.logout();
}
}
/**
* Check if user has specific role
*/
hasRole(role: string): boolean {
return this.userRole() === role;
}
/**
* Check if user has specific permission
*/
hasPermission(permission: string): boolean {
return this.userPermissions().includes(permission);
}
/**
* Check if user has any of the specified permissions
*/
hasAnyPermission(permissions: string[]): boolean {
const userPerms = this.userPermissions();
return permissions.some(p => userPerms.includes(p));
}
/**
* Check if user has all of the specified permissions
*/
hasAllPermissions(permissions: string[]): boolean {
const userPerms = this.userPermissions();
return permissions.every(p => userPerms.includes(p));
}
/**
* Parse JWT token
*/
private async parseToken(token: string): Promise<AuthTokenModel> {
// Decode JWT payload
const payload = JSON.parse(atob(token.split('.')[1]));
// Load user permissions from Firestore (custom claims)
const permissions = await this.loadUserPermissions(payload.uid);
return {
token,
uid: payload.uid,
email: payload.email,
displayName: payload.name || payload.email,
role: payload.role || 'member',
permissions,
exp: payload.exp
};
}
/**
* Load user permissions from Firestore
*/
private async loadUserPermissions(uid: string): Promise<string[]> {
// Implementation: query user's permissions from Firestore
// This is placeholder - implement based on your schema
return ['read:tasks', 'write:tasks'];
}
/**
* Clear session
*/
private clearSession(): void {
this.tokenService.clear();
this.authToken.set(null);
this.currentUser.set(null);
}
}
```
## Auth Guard
```typescript
// src/app/core/guards/auth.guard.ts
import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';
import { AuthService } from '@core/services/auth.service';
/**
* Guard to protect routes requiring authentication
*/
export const authGuard: CanActivateFn = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) {
return true;
}
return router.createUrlTree(['/passport/login']);
};
```
## Role Guard
```typescript
// src/app/core/guards/role.guard.ts
import { inject } from '@angular/core';
import { Router, CanActivateFn, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from '@core/services/auth.service';
/**
* Guard to protect routes by role
*/
export const roleGuard: CanActivateFn = (route: ActivatedRouteSnapshot) => {
const authService = inject(AuthService);
const router = inject(Router);
const requiredRole = route.data['role'] as string;
if (!requiredRole) {
console.warn('Role guard used without required role');
return true;
}
if (authService.hasRole(requiredRole)) {
return true;
}
// Redirect to unauthorized page
return router.createUrlTree(['/exception/403']);
};
/**
* Usage in routes:
* {
* path: 'admin',
* component: AdminComponent,
* canActivate: [authGuard, roleGuard],
* data: { role: 'admin' }
* }
*/
```
## Permission Guard
```typescript
// src/app/core/guards/permission.guard.ts
import { inject } from '@angular/core';
import { Router, CanActivateFn, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from '@core/services/auth.service';
/**
* Guard to protect routes by permissions
*/
export const permissionGuard: CanActivateFn = (route: ActivatedRouteSnapshot) => {
const authService = inRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.