├── src ├── assets │ └── .gitkeep ├── app │ ├── admin │ │ ├── index.ts │ │ ├── admin.component.html │ │ └── admin.component.ts │ ├── home │ │ ├── index.ts │ │ ├── home.component.html │ │ └── home.component.ts │ ├── login │ │ ├── index.ts │ │ ├── login.component.html │ │ └── login.component.ts │ ├── _models │ │ ├── index.ts │ │ ├── role.ts │ │ └── user.ts │ ├── _services │ │ ├── index.ts │ │ ├── user.service.ts │ │ └── authentication.service.ts │ ├── _helpers │ │ ├── index.ts │ │ ├── error.interceptor.ts │ │ ├── jwt.interceptor.ts │ │ ├── auth.guard.ts │ │ └── fake-backend.ts │ ├── app.component.ts │ ├── app-routing.module.ts │ ├── app.component.html │ └── app.module.ts ├── styles.less ├── favicon.ico ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── main.ts ├── index.html ├── test.ts └── polyfills.ts ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── README.md ├── .editorconfig ├── tsconfig.app.json ├── tsconfig.spec.json ├── .browserslistrc ├── .gitignore ├── LICENSE ├── tsconfig.json ├── package.json ├── karma.conf.js └── angular.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/admin/index.ts: -------------------------------------------------------------------------------- 1 | export * from './admin.component'; -------------------------------------------------------------------------------- /src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /src/app/_models/index.ts: -------------------------------------------------------------------------------- 1 | export * from './role'; 2 | export * from './user'; -------------------------------------------------------------------------------- /src/app/_models/role.ts: -------------------------------------------------------------------------------- 1 | export enum Role { 2 | User = 'User', 3 | Admin = 'Admin' 4 | } -------------------------------------------------------------------------------- /src/styles.less: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ -------------------------------------------------------------------------------- /src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; 2 | export * from './user.service'; -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cornflourblue/angular-14-role-based-authorization-example/HEAD/src/favicon.ico -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiUrl: 'http://localhost:4000' 4 | }; 5 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './auth.guard'; 2 | export * from './error.interceptor'; 3 | export * from './fake-backend'; 4 | export * from './jwt.interceptor'; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular-14-role-based-authorization-example 2 | 3 | Angular 14 - Role Based Authorization Tutorial with Example 4 | 5 | Documentation at https://jasonwatmore.com/post/2022/12/22/angular-14-role-based-authorization-tutorial-with-example -------------------------------------------------------------------------------- /src/app/_models/user.ts: -------------------------------------------------------------------------------- 1 | import { Role } from "./role"; 2 | 3 | export interface User { 4 | id: number; 5 | firstName: string; 6 | lastName: string; 7 | username: string; 8 | role: Role; 9 | token?: string; 10 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 14 - Role Based Authorization Tutorial with Example 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } -------------------------------------------------------------------------------- /src/app/admin/admin.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Admin

3 |
4 |

This page can be accessed only by administrators.

5 |

All users from secure (admin only) api end point:

6 |
7 | 10 |
11 |
-------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | "name": "ng serve", 7 | "type": "pwa-chrome", 8 | "request": "launch", 9 | "preLaunchTask": "npm: start", 10 | "url": "http://localhost:4200/" 11 | }, 12 | { 13 | "name": "ng test", 14 | "type": "chrome", 15 | "request": "launch", 16 | "preLaunchTask": "npm: test", 17 | "url": "http://localhost:9876/debug.html" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | import { environment } from '@environments/environment'; 5 | import { User } from '@app/_models'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class UserService { 9 | constructor(private http: HttpClient) { } 10 | 11 | getAll() { 12 | return this.http.get(`${environment.apiUrl}/users`); 13 | } 14 | 15 | getById(id: number) { 16 | return this.http.get(`${environment.apiUrl}/users/${id}`); 17 | } 18 | } -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Home

3 |
4 |

You're logged in with Angular 14 & JWT!!

5 |

Your role is: {{user.role}}.

6 |

This page can be accessed by all authenticated users.

7 |

Current user from secure api end point:

8 |
9 |
    10 |
  • {{userFromApi.firstName}} {{userFromApi.lastName}}
  • 11 |
12 |
13 |
-------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { AuthenticationService } from './_services'; 4 | import { User, Role } from './_models'; 5 | 6 | @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | user?: User | null; 9 | 10 | constructor(private authenticationService: AuthenticationService) { 11 | this.authenticationService.user.subscribe(x => this.user = x); 12 | } 13 | 14 | get isAdmin() { 15 | return this.user?.role === Role.Admin; 16 | } 17 | 18 | logout() { 19 | this.authenticationService.logout(); 20 | } 21 | } -------------------------------------------------------------------------------- /.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | -------------------------------------------------------------------------------- /src/app/admin/admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { first } from 'rxjs/operators'; 3 | 4 | import { User } from '@app/_models'; 5 | import { UserService } from '@app/_services'; 6 | 7 | @Component({ templateUrl: 'admin.component.html' }) 8 | export class AdminComponent implements OnInit { 9 | loading = false; 10 | users: User[] = []; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit() { 15 | this.loading = true; 16 | this.userService.getAll().pipe(first()).subscribe(users => { 17 | this.loading = false; 18 | this.users = users; 19 | }); 20 | } 21 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # Compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | /bazel-out 8 | 9 | # Node 10 | /node_modules 11 | npm-debug.log 12 | yarn-error.log 13 | 14 | # IDEs and editors 15 | .idea/ 16 | .project 17 | .classpath 18 | .c9/ 19 | *.launch 20 | .settings/ 21 | *.sublime-workspace 22 | 23 | # Visual Studio Code 24 | .vscode/* 25 | !.vscode/settings.json 26 | !.vscode/tasks.json 27 | !.vscode/launch.json 28 | !.vscode/extensions.json 29 | .history/* 30 | 31 | # Miscellaneous 32 | /.angular/cache 33 | .sass-cache/ 34 | /connect.lock 35 | /coverage 36 | /libpeerconnection.log 37 | testem.log 38 | /typings 39 | 40 | # System files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | apiUrl: 'http://localhost:4000' 8 | }; 9 | 10 | /* 11 | * For easier debugging in development mode, you can import the following file 12 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 13 | * 14 | * This import should be commented out in production mode because it will have a negative impact 15 | * on performance if an error is thrown. 16 | */ 17 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 18 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | (id: string): T; 13 | keys(): string[]; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting(), 21 | ); 22 | 23 | // Then we find all the tests. 24 | const context = require.context('./', true, /\.spec\.ts$/); 25 | // And load the modules. 26 | context.keys().forEach(context); 27 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { first } from 'rxjs/operators'; 3 | 4 | import { User } from '@app/_models'; 5 | import { UserService, AuthenticationService } from '@app/_services'; 6 | 7 | @Component({ templateUrl: 'home.component.html' }) 8 | export class HomeComponent { 9 | loading = false; 10 | user: User; 11 | userFromApi?: User; 12 | 13 | constructor( 14 | private userService: UserService, 15 | private authenticationService: AuthenticationService 16 | ) { 17 | this.user = this.authenticationService.userValue; 18 | } 19 | 20 | ngOnInit() { 21 | this.loading = true; 22 | this.userService.getById(this.user.id).pipe(first()).subscribe(user => { 23 | this.loading = false; 24 | this.userFromApi = user; 25 | }); 26 | } 27 | } -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | import { HomeComponent } from './home'; 5 | import { AdminComponent } from './admin'; 6 | import { LoginComponent } from './login'; 7 | import { AuthGuard } from './_helpers'; 8 | import { Role } from './_models'; 9 | 10 | const routes: Routes = [ 11 | { 12 | path: '', 13 | component: HomeComponent, 14 | canActivate: [AuthGuard] 15 | }, 16 | { 17 | path: 'admin', 18 | component: AdminComponent, 19 | canActivate: [AuthGuard], 20 | data: { roles: [Role.Admin] } 21 | }, 22 | { 23 | path: 'login', 24 | component: LoginComponent 25 | }, 26 | 27 | // otherwise redirect to home 28 | { path: '**', redirectTo: '' } 29 | ]; 30 | 31 | @NgModule({ 32 | imports: [RouterModule.forRoot(routes)], 33 | exports: [RouterModule] 34 | }) 35 | export class AppRoutingModule { } 36 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 |
12 | 13 |
14 | 15 | 16 | -------------------------------------------------------------------------------- /src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if ([401, 403].includes(err.status) && this.authenticationService.userValue) { 15 | // auto logout if 401 Unauthorized or 403 Forbidden response returned from api 16 | this.authenticationService.logout(); 17 | } 18 | 19 | const error = err.error.message || err.statusText; 20 | return throwError(() => error); 21 | })) 22 | } 23 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Jason Watmore 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { environment } from '@environments/environment'; 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Injectable() 9 | export class JwtInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | // add auth header with jwt if user is logged in and request is to api url 14 | const user = this.authenticationService.userValue; 15 | const isLoggedIn = user?.token; 16 | const isApiUrl = request.url.startsWith(environment.apiUrl); 17 | if (isLoggedIn && isApiUrl) { 18 | request = request.clone({ 19 | setHeaders: { 20 | Authorization: `Bearer ${user.token}` 21 | } 22 | }); 23 | } 24 | 25 | return next.handle(request); 26 | } 27 | } -------------------------------------------------------------------------------- /src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '@app/_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) { } 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const user = this.authenticationService.userValue; 15 | if (user) { 16 | // check if route is restricted by role 17 | const { roles } = route.data; 18 | if (roles && !roles.includes(user.role)) { 19 | // role not authorized so redirect to home page 20 | this.router.navigate(['/']); 21 | return false; 22 | } 23 | 24 | // authorized so return true 25 | return true; 26 | } 27 | 28 | // not logged in so redirect to login page with the return url 29 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "allowSyntheticDefaultImports": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "strict": true, 10 | "noImplicitOverride": true, 11 | "noPropertyAccessFromIndexSignature": false, 12 | "noImplicitReturns": true, 13 | "noFallthroughCasesInSwitch": true, 14 | "sourceMap": true, 15 | "declaration": false, 16 | "downlevelIteration": true, 17 | "experimentalDecorators": true, 18 | "moduleResolution": "node", 19 | "importHelpers": true, 20 | "target": "es2020", 21 | "module": "es2020", 22 | "lib": [ 23 | "es2020", 24 | "dom" 25 | ], 26 | "paths": { 27 | "@app/*": ["src/app/*"], 28 | "@environments/*": ["src/environments/*"] 29 | } 30 | }, 31 | "angularCompilerOptions": { 32 | "enableI18nLegacyMessageIdFormat": false, 33 | "strictInjectionParameters": true, 34 | "strictInputAccessModifiers": true, 35 | "strictTemplates": true 36 | } 37 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-14-example", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve --open", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test" 10 | }, 11 | "private": true, 12 | "dependencies": { 13 | "@angular/animations": "^14.2.0", 14 | "@angular/common": "^14.2.0", 15 | "@angular/compiler": "^14.2.0", 16 | "@angular/core": "^14.2.0", 17 | "@angular/forms": "^14.2.0", 18 | "@angular/platform-browser": "^14.2.0", 19 | "@angular/platform-browser-dynamic": "^14.2.0", 20 | "@angular/router": "^14.2.0", 21 | "rxjs": "~7.5.0", 22 | "tslib": "^2.3.0", 23 | "zone.js": "~0.11.4" 24 | }, 25 | "devDependencies": { 26 | "@angular-devkit/build-angular": "^14.2.8", 27 | "@angular/cli": "~14.2.8", 28 | "@angular/compiler-cli": "^14.2.0", 29 | "@types/jasmine": "~4.0.0", 30 | "jasmine-core": "~4.3.0", 31 | "karma": "~6.4.0", 32 | "karma-chrome-launcher": "~3.1.0", 33 | "karma-coverage": "~2.2.0", 34 | "karma-jasmine": "~5.1.0", 35 | "karma-jasmine-html-reporter": "~2.0.0", 36 | "typescript": "~4.7.2" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { AppComponent } from './app.component'; 10 | import { AppRoutingModule } from './app-routing.module'; 11 | 12 | import { JwtInterceptor, ErrorInterceptor } from './_helpers'; 13 | import { HomeComponent } from './home'; 14 | import { AdminComponent } from './admin'; 15 | import { LoginComponent } from './login'; 16 | 17 | @NgModule({ 18 | imports: [ 19 | BrowserModule, 20 | ReactiveFormsModule, 21 | HttpClientModule, 22 | AppRoutingModule 23 | ], 24 | declarations: [ 25 | AppComponent, 26 | HomeComponent, 27 | AdminComponent, 28 | LoginComponent 29 | ], 30 | providers: [ 31 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 32 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 33 | 34 | // provider used to create fake backend 35 | fakeBackendProvider 36 | ], 37 | bootstrap: [AppComponent] 38 | }) 39 | 40 | export class AppModule { } -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | jasmine: { 17 | // you can add configuration options for Jasmine here 18 | // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html 19 | // for example, you can disable the random execution with `random: false` 20 | // or set a specific seed with `seed: 4321` 21 | }, 22 | clearContext: false // leave Jasmine Spec Runner output visible in browser 23 | }, 24 | jasmineHtmlReporter: { 25 | suppressAll: true // removes the duplicated traces 26 | }, 27 | coverageReporter: { 28 | dir: require('path').join(__dirname, './coverage/angular-14-example'), 29 | subdir: '.', 30 | reporters: [ 31 | { type: 'html' }, 32 | { type: 'text-summary' } 33 | ] 34 | }, 35 | reporters: ['progress', 'kjhtml'], 36 | port: 9876, 37 | colors: true, 38 | logLevel: config.LOG_INFO, 39 | autoWatch: true, 40 | browsers: ['Chrome'], 41 | singleRun: false, 42 | restartOnFileChange: true 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { HttpClient } from '@angular/common/http'; 4 | import { BehaviorSubject, Observable } from 'rxjs'; 5 | import { map } from 'rxjs/operators'; 6 | 7 | import { environment } from '@environments/environment'; 8 | import { User } from '@app/_models'; 9 | 10 | @Injectable({ providedIn: 'root' }) 11 | export class AuthenticationService { 12 | private userSubject: BehaviorSubject; 13 | public user: Observable; 14 | 15 | constructor( 16 | private router: Router, 17 | private http: HttpClient 18 | ) { 19 | this.userSubject = new BehaviorSubject(JSON.parse(localStorage.getItem('user')!)); 20 | this.user = this.userSubject.asObservable(); 21 | } 22 | 23 | public get userValue() { 24 | return this.userSubject.value; 25 | } 26 | 27 | login(username: string, password: string) { 28 | return this.http.post(`${environment.apiUrl}/users/authenticate`, { username, password }) 29 | .pipe(map(user => { 30 | // store user details and jwt token in local storage to keep user logged in between page refreshes 31 | localStorage.setItem('user', JSON.stringify(user)); 32 | this.userSubject.next(user); 33 | return user; 34 | })); 35 | } 36 | 37 | logout() { 38 | // remove user from local storage to log user out 39 | localStorage.removeItem('user'); 40 | this.userSubject.next(null); 41 | this.router.navigate(['/login']); 42 | } 43 | } -------------------------------------------------------------------------------- /src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | Normal User - U: user P: user
4 | Administrator - U: admin P: admin 5 |
6 |
7 |

Angular 14 Role Based Auth Example

8 |
9 |
10 |
11 | 12 | 13 |
14 |
Username is required
15 |
16 |
17 |
18 | 19 | 20 |
21 |
Password is required
22 |
23 |
24 | 28 |
{{error}}
29 |
30 |
31 |
32 |
-------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Component({ templateUrl: 'login.component.html' }) 9 | export class LoginComponent implements OnInit { 10 | loginForm!: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | error = ''; 14 | 15 | constructor( 16 | private formBuilder: FormBuilder, 17 | private route: ActivatedRoute, 18 | private router: Router, 19 | private authenticationService: AuthenticationService 20 | ) { 21 | // redirect to home if already logged in 22 | if (this.authenticationService.userValue) { 23 | this.router.navigate(['/']); 24 | } 25 | } 26 | 27 | ngOnInit() { 28 | this.loginForm = this.formBuilder.group({ 29 | username: ['', Validators.required], 30 | password: ['', Validators.required] 31 | }); 32 | } 33 | 34 | // convenience getter for easy access to form fields 35 | get f() { return this.loginForm.controls; } 36 | 37 | onSubmit() { 38 | this.submitted = true; 39 | 40 | // stop here if form is invalid 41 | if (this.loginForm.invalid) { 42 | return; 43 | } 44 | 45 | this.loading = true; 46 | this.authenticationService.login(this.f.username.value, this.f.password.value) 47 | .pipe(first()) 48 | .subscribe({ 49 | next: () => { 50 | // get return url from query parameters or default to home page 51 | const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 52 | this.router.navigateByUrl(returnUrl); 53 | }, 54 | error: error => { 55 | this.error = error; 56 | this.loading = false; 57 | } 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes recent versions of Safari, Chrome (including 12 | * Opera), Edge on the desktop, and iOS and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** 22 | * By default, zone.js will patch all possible macroTask and DomEvents 23 | * user can disable parts of macroTask/DomEvents patch by setting following flags 24 | * because those flags need to be set before `zone.js` being loaded, and webpack 25 | * will put import in the top of bundle, so user need to create a separate file 26 | * in this directory (for example: zone-flags.ts), and put the following flags 27 | * into that file, and then add the following code before importing zone.js. 28 | * import './zone-flags'; 29 | * 30 | * The flags allowed in zone-flags.ts are listed here. 31 | * 32 | * The following flags will work for all browsers. 33 | * 34 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 35 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 36 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 37 | * 38 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 39 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 40 | * 41 | * (window as any).__Zone_enable_cross_context_check = true; 42 | * 43 | */ 44 | 45 | /*************************************************************************************************** 46 | * Zone JS is required by default for Angular itself. 47 | */ 48 | import 'zone.js'; // Included with Angular CLI. 49 | 50 | 51 | /*************************************************************************************************** 52 | * APPLICATION IMPORTS 53 | */ 54 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-14-example": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "less" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/angular-14-example", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "inlineStyleLanguage": "less", 26 | "assets": [ 27 | "src/favicon.ico", 28 | "src/assets" 29 | ], 30 | "styles": [ 31 | "src/styles.less" 32 | ], 33 | "scripts": [] 34 | }, 35 | "configurations": { 36 | "production": { 37 | "budgets": [ 38 | { 39 | "type": "initial", 40 | "maximumWarning": "500kb", 41 | "maximumError": "1mb" 42 | }, 43 | { 44 | "type": "anyComponentStyle", 45 | "maximumWarning": "2kb", 46 | "maximumError": "4kb" 47 | } 48 | ], 49 | "fileReplacements": [ 50 | { 51 | "replace": "src/environments/environment.ts", 52 | "with": "src/environments/environment.prod.ts" 53 | } 54 | ], 55 | "outputHashing": "all" 56 | }, 57 | "development": { 58 | "buildOptimizer": false, 59 | "optimization": false, 60 | "vendorChunk": true, 61 | "extractLicenses": false, 62 | "sourceMap": true, 63 | "namedChunks": true 64 | } 65 | }, 66 | "defaultConfiguration": "production" 67 | }, 68 | "serve": { 69 | "builder": "@angular-devkit/build-angular:dev-server", 70 | "configurations": { 71 | "production": { 72 | "browserTarget": "angular-14-example:build:production" 73 | }, 74 | "development": { 75 | "browserTarget": "angular-14-example:build:development" 76 | } 77 | }, 78 | "defaultConfiguration": "development" 79 | }, 80 | "extract-i18n": { 81 | "builder": "@angular-devkit/build-angular:extract-i18n", 82 | "options": { 83 | "browserTarget": "angular-14-example:build" 84 | } 85 | }, 86 | "test": { 87 | "builder": "@angular-devkit/build-angular:karma", 88 | "options": { 89 | "main": "src/test.ts", 90 | "polyfills": "src/polyfills.ts", 91 | "tsConfig": "tsconfig.spec.json", 92 | "karmaConfig": "karma.conf.js", 93 | "inlineStyleLanguage": "less", 94 | "assets": [ 95 | "src/favicon.ico", 96 | "src/assets" 97 | ], 98 | "styles": [ 99 | "src/styles.less" 100 | ], 101 | "scripts": [] 102 | } 103 | } 104 | } 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | import { Role } from '@app/_models'; 7 | 8 | const users = [ 9 | { id: 1, username: 'admin', password: 'admin', firstName: 'Admin', lastName: 'User', role: Role.Admin }, 10 | { id: 2, username: 'user', password: 'user', firstName: 'Normal', lastName: 'User', role: Role.User } 11 | ]; 12 | 13 | @Injectable() 14 | export class FakeBackendInterceptor implements HttpInterceptor { 15 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 16 | const { url, method, headers, body } = request; 17 | 18 | return handleRoute(); 19 | 20 | function handleRoute() { 21 | switch (true) { 22 | case url.endsWith('/users/authenticate') && method === 'POST': 23 | return authenticate(); 24 | case url.endsWith('/users') && method === 'GET': 25 | return getUsers(); 26 | case url.match(/\/users\/\d+$/) && method === 'GET': 27 | return getUserById(); 28 | default: 29 | // pass through any requests not handled above 30 | return next.handle(request); 31 | } 32 | 33 | } 34 | 35 | // route functions 36 | 37 | function authenticate() { 38 | const { username, password } = body; 39 | const user = users.find(x => x.username === username && x.password === password); 40 | if (!user) return error('Username or password is incorrect'); 41 | return ok({ 42 | id: user.id, 43 | username: user.username, 44 | firstName: user.firstName, 45 | lastName: user.lastName, 46 | role: user.role, 47 | token: `fake-jwt-token.${user.id}` 48 | }); 49 | } 50 | 51 | function getUsers() { 52 | if (!isAdmin()) return unauthorized(); 53 | return ok(users); 54 | } 55 | 56 | function getUserById() { 57 | if (!isLoggedIn()) return unauthorized(); 58 | 59 | // only admins can access other user records 60 | if (!isAdmin() && currentUser()?.id !== idFromUrl()) return unauthorized(); 61 | 62 | const user = users.find(x => x.id === idFromUrl()); 63 | return ok(user); 64 | } 65 | 66 | // helper functions 67 | 68 | function ok(body: any) { 69 | return of(new HttpResponse({ status: 200, body })) 70 | .pipe(delay(500)); // delay observable to simulate server api call 71 | } 72 | 73 | function unauthorized() { 74 | return throwError(() => ({ status: 401, error: { message: 'unauthorized' } })) 75 | .pipe(materialize(), delay(500), dematerialize()); // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648); 76 | } 77 | 78 | function error(message: string) { 79 | return throwError(() => ({ status: 400, error: { message } })) 80 | .pipe(materialize(), delay(500), dematerialize()); 81 | } 82 | 83 | function isLoggedIn() { 84 | const authHeader = headers.get('Authorization') || ''; 85 | return authHeader.startsWith('Bearer fake-jwt-token'); 86 | } 87 | 88 | function isAdmin() { 89 | return currentUser()?.role === Role.Admin; 90 | } 91 | 92 | function currentUser() { 93 | if (!isLoggedIn()) return; 94 | const id = parseInt(headers.get('Authorization')!.split('.')[1]); 95 | return users.find(x => x.id === id); 96 | } 97 | 98 | function idFromUrl() { 99 | const urlParts = url.split('/'); 100 | return parseInt(urlParts[urlParts.length - 1]); 101 | } 102 | } 103 | } 104 | 105 | export const fakeBackendProvider = { 106 | // use fake backend in place of Http service for backend-less development 107 | provide: HTTP_INTERCEPTORS, 108 | useClass: FakeBackendInterceptor, 109 | multi: true 110 | }; --------------------------------------------------------------------------------