Step 6: Route data + auth roles
Use route data for roles and enforce access with a router hook.
Optional step: This adds route data for role requirements and enforces it with a router hook. You will also add a small auth status widget to toggle the admin role in the UI. If you want to keep the tutorial beginner-friendly, you can stop after Step 5.
1. Create a tiny auth service
Create src/services/auth-service.ts:
import { DI } from '@aurelia/kernel';
export type User = {
name: string;
roles: string[];
};
export const IAuthService = DI.createInterface<IAuthService>(
'IAuthService',
x => x.singleton(AuthService)
);
export interface IAuthService extends AuthService {}
export class AuthService {
private user: User | null = { name: 'Taylor', roles: ['member'] };
getCurrentUser(): User | null {
return this.user;
}
hasRole(role: string): boolean {
return !!this.user?.roles.includes(role);
}
toggleRole(role: string): void {
if (!this.user) return;
if (this.user.roles.includes(role)) {
this.user = { ...this.user, roles: this.user.roles.filter(item => item !== role) };
return;
}
this.user = { ...this.user, roles: [...this.user.roles, role] };
}
}2. Create a role-based router hook
Create src/role-hook.ts:
Register the hook in src/main.ts:
3. Add protected routes with route data
Create src/pages/admin-page.ts:
Create src/pages/admin-page.html:
Create src/pages/forbidden-page.ts:
Create src/pages/forbidden-page.html:
Update src/my-app.ts to add route data:
4. Add an auth status widget
Create src/components/auth-status.ts:
Create src/components/auth-status.html:
Update src/pages/dashboard-page.html to show it:
Finally, add the Admin link in src/my-app.html:
Recap
Route
datacarries therolesrequirement.The
RoleHookreadsnext.dataand redirects toforbiddenif roles are missing.activeClasskeeps the main nav styled for the active route.
Back to: Extended Tutorial overview
Last updated
Was this helpful?