├── .editorconfig ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── README.md ├── angular-16-jwt-authentication-authorization-flow.png ├── angular-16-jwt-authentication.png ├── angular.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── _helpers │ │ └── http.interceptor.ts │ ├── _services │ │ ├── auth.service.spec.ts │ │ ├── auth.service.ts │ │ ├── storage.service.spec.ts │ │ ├── storage.service.ts │ │ ├── user.service.spec.ts │ │ └── user.service.ts │ ├── _shared │ │ ├── event-bus.service.spec.ts │ │ ├── event-bus.service.ts │ │ └── event.class.ts │ ├── app-routing.module.ts │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── board-admin │ │ ├── board-admin.component.css │ │ ├── board-admin.component.html │ │ ├── board-admin.component.spec.ts │ │ └── board-admin.component.ts │ ├── board-moderator │ │ ├── board-moderator.component.css │ │ ├── board-moderator.component.html │ │ ├── board-moderator.component.spec.ts │ │ └── board-moderator.component.ts │ ├── board-user │ │ ├── board-user.component.css │ │ ├── board-user.component.html │ │ ├── board-user.component.spec.ts │ │ └── board-user.component.ts │ ├── home │ │ ├── home.component.css │ │ ├── home.component.html │ │ ├── home.component.spec.ts │ │ └── home.component.ts │ ├── login │ │ ├── login.component.css │ │ ├── login.component.html │ │ ├── login.component.spec.ts │ │ └── login.component.ts │ ├── profile │ │ ├── profile.component.css │ │ ├── profile.component.html │ │ ├── profile.component.spec.ts │ │ └── profile.component.ts │ └── register │ │ ├── register.component.css │ │ ├── register.component.html │ │ ├── register.component.spec.ts │ │ └── register.component.ts ├── assets │ └── .gitkeep ├── favicon.ico ├── index.html ├── main.ts └── styles.css ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.json /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /.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": "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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular 16 JWT Authentication & Authorization example with Rest API 2 | 3 | Build Angular 16 JWT Authentication & Authorization example with Rest Api, HttpOnly Cookie and JWT (including HttpInterceptor, Router & Form Validation). 4 | - JWT Authentication Flow for User Registration (Signup) & User Login 5 | - Project Structure with HttpInterceptor, Router 6 | - Way to implement HttpInterceptor 7 | - How to store JWT token in HttpOnly Cookie 8 | - Creating Login, Signup Components with Form Validation 9 | - Angular Components for accessing protected Resources 10 | - How to add a dynamic Navigation Bar to Angular App 11 | - Working with Browser Session Storage 12 | 13 | ## Flow for User Registration and User Login 14 | For JWT – Token based Authentication with Rest API, we’re gonna call 2 endpoints: 15 | - POST `api/auth/signup` for User Registration 16 | - POST `api/auth/signin` for User Login 17 | - POST `api/auth/signout` for User Logout 18 | 19 | You can take a look at following flow to have an overview of Requests and Responses that Angular 16 JWT Authentication & Authorization Client will make or receive. 20 | 21 | ![angular-16-jwt-authentication-authorization-flow](angular-16-jwt-authentication-authorization-flow.png) 22 | 23 | ## Angular JWT App Diagram with Router and HttpInterceptor 24 | ![angular-16-jwt-authentication](angular-16-jwt-authentication.png) 25 | 26 | For more detail, please visit the tutorial: 27 | > [Angular 16 JWT Authentication & Authorization with Web API example](https://www.bezkoder.com/angular-16-jwt-auth/) 28 | 29 | > [Angular 16 Logout when Token is expired](https://www.bezkoder.com/logout-when-token-expired-angular-16/) 30 | 31 | > [Angular 16 Refresh Token with Interceptor & JWT example](https://www.bezkoder.com/angular-16-refresh-token/) 32 | 33 | ## With Spring Boot back-end 34 | 35 | > [Angular 16 + Spring Boot: JWT Authentication and Authorization example](https://www.bezkoder.com/angular-16-spring-boot-jwt-auth/) 36 | 37 | ## With Node.js Express back-end 38 | 39 | > [Angular 16 + Node.js Express: JWT Authentication and Authorization example](https://www.bezkoder.com/node-js-angular-16-jwt-auth/) 40 | 41 | Run `ng serve --port 8081` for a dev server. Navigate to `http://localhost:8081/`. 42 | 43 | ## More practice 44 | > [Angular 16 CRUD example with Rest API](https://www.bezkoder.com/angular-16-crud-example/) 45 | 46 | > [Angular 16 Pagination example](https://www.bezkoder.com/angular-16-pagination-ngx/) 47 | 48 | > [Angular 16 File upload example with Progress bar](https://www.bezkoder.com/angular-16-file-upload/) 49 | 50 | > [Angular 16 Form Validation example](https://www.bezkoder.com/angular-16-form-validation/) 51 | 52 | Fullstack with Node: 53 | > [Angular 16 + Node Express + MySQL example](https://www.bezkoder.com/angular-16-node-js-express-mysql/) 54 | 55 | > [Angular 16 + Node Express + PostgreSQL example](https://www.bezkoder.com/angular-16-node-js-express-postgresql/) 56 | 57 | > [Angular 16 + Node Express + MongoDB example](https://www.bezkoder.com/angular-16-node-js-express-mongodb/) 58 | 59 | > [Angular 16 + Node Express: File upload example](https://www.bezkoder.com/angular-16-node-express-file-upload/) 60 | 61 | Fullstack with Spring Boot: 62 | > [Angular 16 + Spring Boot example](https://www.bezkoder.com/spring-boot-angular-16-crud/) 63 | 64 | > [Angular 16 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-16-mysql/) 65 | 66 | > [Angular 16 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-16-postgresql/) 67 | 68 | > [Angular 16 + Spring Boot + MongoDB example](https://www.bezkoder.com/spring-boot-angular-16-mongodb/) 69 | 70 | > [Angular 16 + Spring Boot: File upload example](https://www.bezkoder.com/angular-16-spring-boot-file-upload/) 71 | 72 | Fullstack with Django: 73 | > [Angular + Django example](https://www.bezkoder.com/django-angular-13-crud-rest-framework/) 74 | 75 | > [Angular + Django + MySQL](https://www.bezkoder.com/django-angular-mysql/) 76 | 77 | > [Angular + Django + PostgreSQL](https://www.bezkoder.com/django-angular-postgresql/) 78 | 79 | > [Angular + Django + MongoDB](https://www.bezkoder.com/django-angular-mongodb/) 80 | 81 | Serverless with Firebase: 82 | > [Angular 16 Firebase CRUD with Realtime DataBase](https://www.bezkoder.com/angular-16-firebase-crud/) 83 | 84 | > [Angular 16 Firestore CRUD example](https://www.bezkoder.com/angular-16-firestore-crud/) 85 | 86 | > [Angular 16 Firebase Storage: File Upload/Display/Delete example](https://www.bezkoder.com/angular-16-firebase-storage/) 87 | 88 | Integration (run back-end & front-end on same server/port) 89 | > [How to integrate Angular with Node Restful Services](https://www.bezkoder.com/integrate-angular-12-node-js/) 90 | 91 | > [How to Integrate Angular with Spring Boot Rest API](https://www.bezkoder.com/integrate-angular-12-spring-boot/) 92 | -------------------------------------------------------------------------------- /angular-16-jwt-authentication-authorization-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/angular-16-jwt-authentication-authorization-flow.png -------------------------------------------------------------------------------- /angular-16-jwt-authentication.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/angular-16-jwt-authentication.png -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-16-jwt-auth": { 7 | "projectType": "application", 8 | "schematics": {}, 9 | "root": "", 10 | "sourceRoot": "src", 11 | "prefix": "app", 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/angular-16-jwt-auth", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": [ 20 | "zone.js" 21 | ], 22 | "tsConfig": "tsconfig.app.json", 23 | "assets": [ 24 | "src/favicon.ico", 25 | "src/assets" 26 | ], 27 | "styles": [ 28 | "src/styles.css" 29 | ], 30 | "scripts": [] 31 | }, 32 | "configurations": { 33 | "production": { 34 | "budgets": [ 35 | { 36 | "type": "initial", 37 | "maximumWarning": "500kb", 38 | "maximumError": "1mb" 39 | }, 40 | { 41 | "type": "anyComponentStyle", 42 | "maximumWarning": "2kb", 43 | "maximumError": "4kb" 44 | } 45 | ], 46 | "outputHashing": "all" 47 | }, 48 | "development": { 49 | "buildOptimizer": false, 50 | "optimization": false, 51 | "vendorChunk": true, 52 | "extractLicenses": false, 53 | "sourceMap": true, 54 | "namedChunks": true 55 | } 56 | }, 57 | "defaultConfiguration": "production" 58 | }, 59 | "serve": { 60 | "builder": "@angular-devkit/build-angular:dev-server", 61 | "configurations": { 62 | "production": { 63 | "browserTarget": "angular-16-jwt-auth:build:production" 64 | }, 65 | "development": { 66 | "browserTarget": "angular-16-jwt-auth:build:development" 67 | } 68 | }, 69 | "defaultConfiguration": "development" 70 | }, 71 | "extract-i18n": { 72 | "builder": "@angular-devkit/build-angular:extract-i18n", 73 | "options": { 74 | "browserTarget": "angular-16-jwt-auth:build" 75 | } 76 | }, 77 | "test": { 78 | "builder": "@angular-devkit/build-angular:karma", 79 | "options": { 80 | "polyfills": [ 81 | "zone.js", 82 | "zone.js/testing" 83 | ], 84 | "tsConfig": "tsconfig.spec.json", 85 | "assets": [ 86 | "src/favicon.ico", 87 | "src/assets" 88 | ], 89 | "styles": [ 90 | "src/styles.css" 91 | ], 92 | "scripts": [] 93 | } 94 | } 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-16-jwt-auth", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test" 10 | }, 11 | "private": true, 12 | "dependencies": { 13 | "@angular/animations": "^16.0.0", 14 | "@angular/common": "^16.0.0", 15 | "@angular/compiler": "^16.0.0", 16 | "@angular/core": "^16.0.0", 17 | "@angular/forms": "^16.0.0", 18 | "@angular/platform-browser": "^16.0.0", 19 | "@angular/platform-browser-dynamic": "^16.0.0", 20 | "@angular/router": "^16.0.0", 21 | "bootstrap": "^4.6.2", 22 | "rxjs": "~7.8.0", 23 | "tslib": "^2.3.0", 24 | "zone.js": "~0.13.0" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "^16.0.2", 28 | "@angular/cli": "~16.0.2", 29 | "@angular/compiler-cli": "^16.0.0", 30 | "@types/jasmine": "~4.3.0", 31 | "jasmine-core": "~4.6.0", 32 | "karma": "~6.4.0", 33 | "karma-chrome-launcher": "~3.2.0", 34 | "karma-coverage": "~2.2.0", 35 | "karma-jasmine": "~5.1.0", 36 | "karma-jasmine-html-reporter": "~2.0.0", 37 | "typescript": "~5.0.2" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/app/_helpers/http.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS, HttpErrorResponse } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { StorageService } from '../_services/storage.service'; 7 | import { EventBusService } from '../_shared/event-bus.service'; 8 | import { EventData } from '../_shared/event.class'; 9 | 10 | @Injectable() 11 | export class HttpRequestInterceptor implements HttpInterceptor { 12 | private isRefreshing = false; 13 | 14 | constructor(private storageService: StorageService, private eventBusService: EventBusService) { } 15 | 16 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 17 | req = req.clone({ 18 | withCredentials: true, 19 | }); 20 | 21 | return next.handle(req).pipe( 22 | catchError((error) => { 23 | // logout when token is expired 24 | /* 25 | if ( 26 | error instanceof HttpErrorResponse && 27 | !req.url.includes('auth/signin') && 28 | error.status === 401 29 | ) { 30 | return this.handle401Error(req, next); 31 | } 32 | */ 33 | return throwError(() => error); 34 | }) 35 | ); 36 | } 37 | 38 | private handle401Error(request: HttpRequest, next: HttpHandler) { 39 | if (!this.isRefreshing) { 40 | this.isRefreshing = true; 41 | 42 | if (this.storageService.isLoggedIn()) { 43 | this.eventBusService.emit(new EventData('logout', null)); 44 | } 45 | } 46 | 47 | return next.handle(request); 48 | } 49 | } 50 | 51 | export const httpInterceptorProviders = [ 52 | { provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true }, 53 | ]; 54 | -------------------------------------------------------------------------------- /src/app/_services/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthService } from './auth.service'; 4 | 5 | describe('AuthService', () => { 6 | let service: AuthService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(AuthService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | const AUTH_API = 'http://localhost:8080/api/auth/'; 6 | 7 | const httpOptions = { 8 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 9 | }; 10 | 11 | @Injectable({ 12 | providedIn: 'root', 13 | }) 14 | export class AuthService { 15 | constructor(private http: HttpClient) {} 16 | 17 | login(username: string, password: string): Observable { 18 | return this.http.post( 19 | AUTH_API + 'signin', 20 | { 21 | username, 22 | password, 23 | }, 24 | httpOptions 25 | ); 26 | } 27 | 28 | register(username: string, email: string, password: string): Observable { 29 | return this.http.post( 30 | AUTH_API + 'signup', 31 | { 32 | username, 33 | email, 34 | password, 35 | }, 36 | httpOptions 37 | ); 38 | } 39 | 40 | logout(): Observable { 41 | return this.http.post(AUTH_API + 'signout', { }, httpOptions); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/_services/storage.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { StorageService } from './storage.service'; 4 | 5 | describe('StorageService', () => { 6 | let service: StorageService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(StorageService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const USER_KEY = 'auth-user'; 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class StorageService { 9 | constructor() {} 10 | 11 | clean(): void { 12 | window.sessionStorage.clear(); 13 | } 14 | 15 | public saveUser(user: any): void { 16 | window.sessionStorage.removeItem(USER_KEY); 17 | window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); 18 | } 19 | 20 | public getUser(): any { 21 | const user = window.sessionStorage.getItem(USER_KEY); 22 | if (user) { 23 | return JSON.parse(user); 24 | } 25 | 26 | return null; 27 | } 28 | 29 | public isLoggedIn(): boolean { 30 | const user = window.sessionStorage.getItem(USER_KEY); 31 | if (user) { 32 | return true; 33 | } 34 | 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/app/_services/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserService', () => { 6 | let service: UserService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(UserService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | const API_URL = 'http://localhost:8080/api/test/'; 6 | 7 | @Injectable({ 8 | providedIn: 'root', 9 | }) 10 | export class UserService { 11 | constructor(private http: HttpClient) {} 12 | 13 | getPublicContent(): Observable { 14 | return this.http.get(API_URL + 'all', { responseType: 'text' }); 15 | } 16 | 17 | getUserBoard(): Observable { 18 | return this.http.get(API_URL + 'user', { responseType: 'text' }); 19 | } 20 | 21 | getModeratorBoard(): Observable { 22 | return this.http.get(API_URL + 'mod', { responseType: 'text' }); 23 | } 24 | 25 | getAdminBoard(): Observable { 26 | return this.http.get(API_URL + 'admin', { responseType: 'text' }); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/_shared/event-bus.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { EventBusService } from './event-bus.service'; 4 | 5 | describe('EventBusService', () => { 6 | let service: EventBusService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(EventBusService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_shared/event-bus.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Subject, Subscription } from 'rxjs'; 3 | import { filter, map } from 'rxjs/operators'; 4 | import { EventData } from './event.class'; 5 | 6 | @Injectable({ 7 | providedIn: 'root', 8 | }) 9 | export class EventBusService { 10 | private subject$ = new Subject(); 11 | 12 | emit(event: EventData) { 13 | this.subject$.next(event); 14 | } 15 | 16 | on(eventName: string, action: any): Subscription { 17 | return this.subject$.pipe( 18 | filter((e: EventData) => e.name === eventName), 19 | map((e: EventData) => e["value"])).subscribe(action); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/_shared/event.class.ts: -------------------------------------------------------------------------------- 1 | export class EventData { 2 | name: string; 3 | value: any; 4 | 5 | constructor(name: string, value: any) { 6 | this.name = name; 7 | this.value = value; 8 | } 9 | } -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | 4 | import { RegisterComponent } from './register/register.component'; 5 | import { LoginComponent } from './login/login.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { BoardUserComponent } from './board-user/board-user.component'; 9 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 10 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 11 | 12 | const routes: Routes = [ 13 | { path: 'home', component: HomeComponent }, 14 | { path: 'login', component: LoginComponent }, 15 | { path: 'register', component: RegisterComponent }, 16 | { path: 'profile', component: ProfileComponent }, 17 | { path: 'user', component: BoardUserComponent }, 18 | { path: 'mod', component: BoardModeratorComponent }, 19 | { path: 'admin', component: BoardAdminComponent }, 20 | { path: '', redirectTo: 'home', pathMatch: 'full' } 21 | ]; 22 | 23 | @NgModule({ 24 | imports: [RouterModule.forRoot(routes)], 25 | exports: [RouterModule] 26 | }) 27 | export class AppRoutingModule { } 28 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 37 | 38 |
39 | 40 |
41 |
42 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(() => TestBed.configureTestingModule({ 7 | imports: [RouterTestingModule], 8 | declarations: [AppComponent] 9 | })); 10 | 11 | it('should create the app', () => { 12 | const fixture = TestBed.createComponent(AppComponent); 13 | const app = fixture.componentInstance; 14 | expect(app).toBeTruthy(); 15 | }); 16 | 17 | it(`should have as title 'angular-16-jwt-auth'`, () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app.title).toEqual('angular-16-jwt-auth'); 21 | }); 22 | 23 | it('should render title', () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | fixture.detectChanges(); 26 | const compiled = fixture.nativeElement as HTMLElement; 27 | expect(compiled.querySelector('.content span')?.textContent).toContain('angular-16-jwt-auth app is running!'); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | import { StorageService } from './_services/storage.service'; 4 | import { AuthService } from './_services/auth.service'; 5 | import { EventBusService } from './_shared/event-bus.service'; 6 | 7 | @Component({ 8 | selector: 'app-root', 9 | templateUrl: './app.component.html', 10 | styleUrls: ['./app.component.css'] 11 | }) 12 | export class AppComponent { 13 | private roles: string[] = []; 14 | isLoggedIn = false; 15 | showAdminBoard = false; 16 | showModeratorBoard = false; 17 | username?: string; 18 | 19 | eventBusSub?: Subscription; 20 | 21 | constructor( 22 | private storageService: StorageService, 23 | private authService: AuthService, 24 | private eventBusService: EventBusService 25 | ) {} 26 | 27 | ngOnInit(): void { 28 | this.isLoggedIn = this.storageService.isLoggedIn(); 29 | 30 | if (this.isLoggedIn) { 31 | const user = this.storageService.getUser(); 32 | this.roles = user.roles; 33 | 34 | this.showAdminBoard = this.roles.includes('ROLE_ADMIN'); 35 | this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR'); 36 | 37 | this.username = user.username; 38 | } 39 | 40 | this.eventBusSub = this.eventBusService.on('logout', () => { 41 | this.logout(); 42 | }); 43 | } 44 | 45 | logout(): void { 46 | this.authService.logout().subscribe({ 47 | next: res => { 48 | console.log(res); 49 | this.storageService.clean(); 50 | 51 | window.location.reload(); 52 | }, 53 | error: err => { 54 | console.log(err); 55 | } 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpClientModule } from '@angular/common/http'; 5 | 6 | import { AppRoutingModule } from './app-routing.module'; 7 | import { AppComponent } from './app.component'; 8 | import { LoginComponent } from './login/login.component'; 9 | import { RegisterComponent } from './register/register.component'; 10 | import { HomeComponent } from './home/home.component'; 11 | import { ProfileComponent } from './profile/profile.component'; 12 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 13 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 14 | import { BoardUserComponent } from './board-user/board-user.component'; 15 | 16 | import { httpInterceptorProviders } from './_helpers/http.interceptor'; 17 | 18 | @NgModule({ 19 | declarations: [ 20 | AppComponent, 21 | LoginComponent, 22 | RegisterComponent, 23 | HomeComponent, 24 | ProfileComponent, 25 | BoardAdminComponent, 26 | BoardModeratorComponent, 27 | BoardUserComponent 28 | ], 29 | imports: [ 30 | BrowserModule, 31 | AppRoutingModule, 32 | FormsModule, 33 | HttpClientModule 34 | ], 35 | providers: [httpInterceptorProviders], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { } 39 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/board-admin/board-admin.component.css -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardAdminComponent } from './board-admin.component'; 4 | 5 | describe('BoardAdminComponent', () => { 6 | let component: BoardAdminComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [BoardAdminComponent] 12 | }); 13 | fixture = TestBed.createComponent(BoardAdminComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-admin', 6 | templateUrl: './board-admin.component.html', 7 | styleUrls: ['./board-admin.component.css'] 8 | }) 9 | export class BoardAdminComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getAdminBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/board-moderator/board-moderator.component.css -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardModeratorComponent } from './board-moderator.component'; 4 | 5 | describe('BoardModeratorComponent', () => { 6 | let component: BoardModeratorComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [BoardModeratorComponent] 12 | }); 13 | fixture = TestBed.createComponent(BoardModeratorComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-moderator', 6 | templateUrl: './board-moderator.component.html', 7 | styleUrls: ['./board-moderator.component.css'] 8 | }) 9 | export class BoardModeratorComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getModeratorBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/board-user/board-user.component.css -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardUserComponent } from './board-user.component'; 4 | 5 | describe('BoardUserComponent', () => { 6 | let component: BoardUserComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [BoardUserComponent] 12 | }); 13 | fixture = TestBed.createComponent(BoardUserComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-user', 6 | templateUrl: './board-user.component.html', 7 | styleUrls: ['./board-user.component.css'] 8 | }) 9 | export class BoardUserComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getUserBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/home/home.component.css -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [HomeComponent] 12 | }); 13 | fixture = TestBed.createComponent(HomeComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getPublicContent().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 8 |
15 |
16 | 17 | 26 |
27 | Username is required! 28 |
29 |
30 |
31 | 32 | 42 |
43 |
Password is required
44 |
45 | Password must be at least 6 characters 46 |
47 |
48 |
49 |
50 | 53 |
54 |
55 | 58 |
59 |
60 | 61 |
62 | Logged in as {{ roles }}. 63 |
64 |
65 |
-------------------------------------------------------------------------------- /src/app/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [LoginComponent] 12 | }); 13 | fixture = TestBed.createComponent(LoginComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { StorageService } from '../_services/storage.service'; 4 | 5 | @Component({ 6 | selector: 'app-login', 7 | templateUrl: './login.component.html', 8 | styleUrls: ['./login.component.css'] 9 | }) 10 | export class LoginComponent implements OnInit { 11 | form: any = { 12 | username: null, 13 | password: null 14 | }; 15 | isLoggedIn = false; 16 | isLoginFailed = false; 17 | errorMessage = ''; 18 | roles: string[] = []; 19 | 20 | constructor(private authService: AuthService, private storageService: StorageService) { } 21 | 22 | ngOnInit(): void { 23 | if (this.storageService.isLoggedIn()) { 24 | this.isLoggedIn = true; 25 | this.roles = this.storageService.getUser().roles; 26 | } 27 | } 28 | 29 | onSubmit(): void { 30 | const { username, password } = this.form; 31 | 32 | this.authService.login(username, password).subscribe({ 33 | next: data => { 34 | this.storageService.saveUser(data); 35 | 36 | this.isLoginFailed = false; 37 | this.isLoggedIn = true; 38 | this.roles = this.storageService.getUser().roles; 39 | this.reloadPage(); 40 | }, 41 | error: err => { 42 | this.errorMessage = err.error.message; 43 | this.isLoginFailed = true; 44 | } 45 | }); 46 | } 47 | 48 | reloadPage(): void { 49 | window.location.reload(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | {{ currentUser.username }} Profile 5 |

6 |
7 |

8 | Email: 9 | {{ currentUser.email }} 10 |

11 | Roles: 12 |
    13 |
  • 14 | {{ role }} 15 |
  • 16 |
17 |
18 | 19 | 20 | Please login. 21 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ProfileComponent } from './profile.component'; 4 | 5 | describe('ProfileComponent', () => { 6 | let component: ProfileComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ProfileComponent] 12 | }); 13 | fixture = TestBed.createComponent(ProfileComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { StorageService } from '../_services/storage.service'; 3 | 4 | @Component({ 5 | selector: 'app-profile', 6 | templateUrl: './profile.component.html', 7 | styleUrls: ['./profile.component.css'] 8 | }) 9 | export class ProfileComponent implements OnInit { 10 | currentUser: any; 11 | 12 | constructor(private storageService: StorageService) { } 13 | 14 | ngOnInit(): void { 15 | this.currentUser = this.storageService.getUser(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app/register/register.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 8 |
15 |
16 | 17 | 28 |
29 |
Username is required
30 |
31 | Username must be at least 3 characters 32 |
33 |
34 | Username must be at most 20 characters 35 |
36 |
37 |
38 |
39 | 40 | 50 |
51 |
Email is required
52 |
53 | Email must be a valid email address 54 |
55 |
56 |
57 |
58 | 59 | 69 |
70 |
Password is required
71 |
72 | Password must be at least 6 characters 73 |
74 |
75 |
76 |
77 | 78 |
79 | 80 |
81 | Signup failed!
{{ errorMessage }} 82 |
83 |
84 | 85 |
86 | Your registration is successful! 87 |
88 |
89 |
-------------------------------------------------------------------------------- /src/app/register/register.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { RegisterComponent } from './register.component'; 4 | 5 | describe('RegisterComponent', () => { 6 | let component: RegisterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [RegisterComponent] 12 | }); 13 | fixture = TestBed.createComponent(RegisterComponent); 14 | component = fixture.componentInstance; 15 | fixture.detectChanges(); 16 | }); 17 | 18 | it('should create', () => { 19 | expect(component).toBeTruthy(); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | 4 | @Component({ 5 | selector: 'app-register', 6 | templateUrl: './register.component.html', 7 | styleUrls: ['./register.component.css'] 8 | }) 9 | export class RegisterComponent { 10 | form: any = { 11 | username: null, 12 | email: null, 13 | password: null 14 | }; 15 | isSuccessful = false; 16 | isSignUpFailed = false; 17 | errorMessage = ''; 18 | 19 | constructor(private authService: AuthService) { } 20 | 21 | onSubmit(): void { 22 | const { username, email, password } = this.form; 23 | 24 | this.authService.register(username, email, password).subscribe({ 25 | next: data => { 26 | console.log(data); 27 | this.isSuccessful = true; 28 | this.isSignUpFailed = false; 29 | }, 30 | error: err => { 31 | this.errorMessage = err.error.message; 32 | this.isSignUpFailed = true; 33 | } 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-16-jwt-auth/1ac0f4e626e4dfcdb9abb051d68734ccbaf9e371/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular16JwtAuth 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 2 | 3 | import { AppModule } from './app/app.module'; 4 | 5 | 6 | platformBrowserDynamic().bootstrapModule(AppModule) 7 | .catch(err => console.error(err)); 8 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | @import "~bootstrap/dist/css/bootstrap.css"; -------------------------------------------------------------------------------- /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 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /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 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "noImplicitOverride": true, 10 | "noPropertyAccessFromIndexSignature": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "sourceMap": true, 14 | "declaration": false, 15 | "downlevelIteration": true, 16 | "experimentalDecorators": true, 17 | "moduleResolution": "node", 18 | "importHelpers": true, 19 | "target": "ES2022", 20 | "module": "ES2022", 21 | "useDefineForClassFields": false, 22 | "lib": [ 23 | "ES2022", 24 | "dom" 25 | ] 26 | }, 27 | "angularCompilerOptions": { 28 | "enableI18nLegacyMessageIdFormat": false, 29 | "strictInjectionParameters": true, 30 | "strictInputAccessModifiers": true, 31 | "strictTemplates": true 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /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 | "include": [ 11 | "src/**/*.spec.ts", 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | --------------------------------------------------------------------------------