├── .browserslistrc ├── .editorconfig ├── .gitignore ├── README.md ├── angular-12-refresh-token-jwt-interceptor-example.png ├── angular.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── _helpers │ │ └── auth.interceptor.ts │ ├── _services │ │ ├── auth.service.spec.ts │ │ ├── auth.service.ts │ │ ├── token-storage.service.spec.ts │ │ ├── token-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 ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css └── test.ts ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.json /.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 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line. 18 | -------------------------------------------------------------------------------- /.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 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | 16 | # IDEs and editors 17 | /.idea 18 | .project 19 | .classpath 20 | .c9/ 21 | *.launch 22 | .settings/ 23 | *.sublime-workspace 24 | 25 | # IDE - VSCode 26 | .vscode/* 27 | !.vscode/settings.json 28 | !.vscode/tasks.json 29 | !.vscode/launch.json 30 | !.vscode/extensions.json 31 | .history/* 32 | 33 | # misc 34 | /.sass-cache 35 | /connect.lock 36 | /coverage 37 | /libpeerconnection.log 38 | npm-debug.log 39 | yarn-error.log 40 | testem.log 41 | /typings 42 | 43 | # System Files 44 | .DS_Store 45 | Thumbs.db 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular 12 JWT Refresh Token example with Http Interceptor 2 | 3 | You can take a look at following flow to have an overview of Requests and Responses that Angular 12 Client will make or receive. 4 | 5 | ## Angular JWT Refresh Token Flow 6 | ![angular-12-refresh-token-jwt-interceptor-example](angular-12-refresh-token-jwt-interceptor-example.png) 7 | 8 | For more detail, please visit: 9 | > [Angular 12 JWT Refresh Token example with Http Interceptor](https://www.bezkoder.com/angular-12-refresh-token/) 10 | 11 | > [Angular 12 JWT Authentication & Authorization with Web API](https://bezkoder.com/angular-12-jwt-auth/) 12 | 13 | ## Fullstack 14 | > [Angular 12 + Spring Boot: JWT Authentication and Authorization example](https://bezkoder.com/angular-12-spring-boot-jwt-auth/) 15 | 16 | > [Angular 12 + Node.js Express: JWT Authentication and Authorization example](https://bezkoder.com/node-js-angular-12-jwt-auth/) 17 | 18 | Open `app/_helpers/auth.interceptor.js`, modify the code to work with **x-access-token** like this: 19 | ```js 20 | ... 21 | 22 | // const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end 23 | const TOKEN_HEADER_KEY = 'x-access-token'; // for Node.js Express back-end 24 | 25 | @Injectable() 26 | export class AuthInterceptor implements HttpInterceptor { 27 | ... 28 | 29 | private addTokenHeader(request: HttpRequest, token: string) { 30 | /* for Spring Boot back-end */ 31 | // return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) }); 32 | 33 | /* for Node.js Express back-end */ 34 | return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, token) }); 35 | } 36 | } 37 | 38 | ... 39 | ``` 40 | 41 | Run `ng serve --port 8081` for a dev server. Navigate to `http://localhost:8081/`. 42 | 43 | ## More practice 44 | > [Angular CRUD Application example with Web API](https://bezkoder.com/angular-12-crud-app/) 45 | 46 | > [Angular Pagination example | ngx-pagination](https://bezkoder.com/angular-12-pagination-ngx/) 47 | 48 | > [Angular File upload example with progress bar & Bootstrap](https://bezkoder.com/angular-12-file-upload/) 49 | 50 | Fullstack with Node.js Express: 51 | > [Angular + Node.js Express + MySQL example](https://bezkoder.com/angular-12-node-js-express-mysql/) 52 | 53 | > [Angular + Node.js Express + PostgreSQL example](https://bezkoder.com/angular-12-node-js-express-postgresql/) 54 | 55 | > [Angular + Node.js Express + MongoDB example](https://bezkoder.com/angular-12-mongodb-node-js-express/) 56 | 57 | > [Angular + Node.js Express: File upload example](https://bezkoder.com/angular-12-node-js-file-upload/) 58 | 59 | Fullstack with Spring Boot: 60 | > [Angular + Spring Boot + MySQL example](https://bezkoder.com/angular-12-spring-boot-mysql/) 61 | 62 | > [Angular + Spring Boot + PostgreSQL example](https://bezkoder.com/angular-12-spring-boot-postgresql/) 63 | 64 | > [Angular + Spring Boot + MongoDB example](https://bezkoder.com/angular-12-spring-boot-mongodb/) 65 | 66 | > [Angular + Spring Boot: File upload example](https://bezkoder.com/angular-12-spring-boot-file-upload/) 67 | 68 | Fullstack with Django: 69 | > [Angular 12 + Django example](https://bezkoder.com/django-angular-12-crud-rest-framework/) 70 | 71 | > [Angular + Django + MySQL](https://bezkoder.com/django-angular-mysql/) 72 | 73 | > [Angular + Django + PostgreSQL](https://bezkoder.com/django-angular-postgresql/) 74 | 75 | > [Angular + Django + MongoDB](https://bezkoder.com/django-angular-mongodb/) 76 | 77 | Serverless with Firebase: 78 | > [Angular 12 Firebase CRUD with Realtime DataBase | AngularFireDatabase](https://bezkoder.com/angular-12-firebase-crud/) 79 | 80 | > [Angular 12 Firestore CRUD example with AngularFireStore](https://bezkoder.com/angular-12-firestore-crud-angularfirestore/) 81 | 82 | > [Angular 12 Firebase Storage: File Upload/Display/Delete example](https://bezkoder.com/angular-12-file-upload-firebase-storage/) 83 | 84 | Integration (run back-end & front-end on same server/port) 85 | > [How to integrate Angular with Node.js Restful Services](https://bezkoder.com/integrate-angular-12-node-js/) 86 | 87 | > [How to Integrate Angular with Spring Boot Rest API](https://bezkoder.com/integrate-angular-12-spring-boot/) -------------------------------------------------------------------------------- /angular-12-refresh-token-jwt-interceptor-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/angular-12-refresh-token-jwt-interceptor-example.png -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "Angular12RefreshToken": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:application": { 10 | "strict": true 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/Angular12RefreshToken", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "assets": [ 26 | "src/favicon.ico", 27 | "src/assets" 28 | ], 29 | "styles": [ 30 | "src/styles.css" 31 | ], 32 | "scripts": [] 33 | }, 34 | "configurations": { 35 | "production": { 36 | "budgets": [ 37 | { 38 | "type": "initial", 39 | "maximumWarning": "500kb", 40 | "maximumError": "1mb" 41 | }, 42 | { 43 | "type": "anyComponentStyle", 44 | "maximumWarning": "2kb", 45 | "maximumError": "4kb" 46 | } 47 | ], 48 | "fileReplacements": [ 49 | { 50 | "replace": "src/environments/environment.ts", 51 | "with": "src/environments/environment.prod.ts" 52 | } 53 | ], 54 | "outputHashing": "all" 55 | }, 56 | "development": { 57 | "buildOptimizer": false, 58 | "optimization": false, 59 | "vendorChunk": true, 60 | "extractLicenses": false, 61 | "sourceMap": true, 62 | "namedChunks": true 63 | } 64 | }, 65 | "defaultConfiguration": "production" 66 | }, 67 | "serve": { 68 | "builder": "@angular-devkit/build-angular:dev-server", 69 | "configurations": { 70 | "production": { 71 | "browserTarget": "Angular12RefreshToken:build:production" 72 | }, 73 | "development": { 74 | "browserTarget": "Angular12RefreshToken:build:development" 75 | } 76 | }, 77 | "defaultConfiguration": "development" 78 | }, 79 | "extract-i18n": { 80 | "builder": "@angular-devkit/build-angular:extract-i18n", 81 | "options": { 82 | "browserTarget": "Angular12RefreshToken:build" 83 | } 84 | }, 85 | "test": { 86 | "builder": "@angular-devkit/build-angular:karma", 87 | "options": { 88 | "main": "src/test.ts", 89 | "polyfills": "src/polyfills.ts", 90 | "tsConfig": "tsconfig.spec.json", 91 | "karmaConfig": "karma.conf.js", 92 | "assets": [ 93 | "src/favicon.ico", 94 | "src/assets" 95 | ], 96 | "styles": [ 97 | "src/styles.css" 98 | ], 99 | "scripts": [] 100 | } 101 | } 102 | } 103 | } 104 | }, 105 | "defaultProject": "Angular12RefreshToken" 106 | } 107 | -------------------------------------------------------------------------------- /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/Angular12RefreshToken'), 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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular12-refresh-token", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve --port 8081", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test" 10 | }, 11 | "private": true, 12 | "dependencies": { 13 | "@angular/animations": "~12.1.0", 14 | "@angular/common": "~12.1.0", 15 | "@angular/compiler": "~12.1.0", 16 | "@angular/core": "~12.1.0", 17 | "@angular/forms": "~12.1.0", 18 | "@angular/platform-browser": "~12.1.0", 19 | "@angular/platform-browser-dynamic": "~12.1.0", 20 | "@angular/router": "~12.1.0", 21 | "rxjs": "~6.6.0", 22 | "tslib": "^2.2.0", 23 | "zone.js": "~0.11.4" 24 | }, 25 | "devDependencies": { 26 | "@angular-devkit/build-angular": "~12.1.4", 27 | "@angular/cli": "~12.1.4", 28 | "@angular/compiler-cli": "~12.1.0", 29 | "@types/jasmine": "~3.8.0", 30 | "@types/node": "^12.11.1", 31 | "jasmine-core": "~3.8.0", 32 | "karma": "~6.3.0", 33 | "karma-chrome-launcher": "~3.1.0", 34 | "karma-coverage": "~2.0.3", 35 | "karma-jasmine": "~4.0.0", 36 | "karma-jasmine-html-reporter": "~1.7.0", 37 | "typescript": "~4.3.2" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/app/_helpers/auth.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { HTTP_INTERCEPTORS, HttpEvent, HttpErrorResponse } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; 4 | 5 | import { TokenStorageService } from '../_services/token-storage.service'; 6 | import { AuthService } from '../_services/auth.service'; 7 | 8 | import { BehaviorSubject, Observable, throwError } from 'rxjs'; 9 | import { catchError, filter, switchMap, take } from 'rxjs/operators'; 10 | 11 | // const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end 12 | const TOKEN_HEADER_KEY = 'x-access-token'; // for Node.js Express back-end 13 | 14 | @Injectable() 15 | export class AuthInterceptor implements HttpInterceptor { 16 | private isRefreshing = false; 17 | private refreshTokenSubject: BehaviorSubject = new BehaviorSubject(null); 18 | 19 | constructor(private tokenService: TokenStorageService, private authService: AuthService) { } 20 | 21 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 22 | let authReq = req; 23 | const token = this.tokenService.getToken(); 24 | if (token != null) { 25 | authReq = this.addTokenHeader(req, token); 26 | } 27 | 28 | return next.handle(authReq).pipe(catchError(error => { 29 | if (error instanceof HttpErrorResponse && !authReq.url.includes('auth/signin') && error.status === 401) { 30 | return this.handle401Error(authReq, next); 31 | } 32 | 33 | return throwError(error); 34 | })); 35 | } 36 | 37 | private handle401Error(request: HttpRequest, next: HttpHandler) { 38 | if (!this.isRefreshing) { 39 | this.isRefreshing = true; 40 | this.refreshTokenSubject.next(null); 41 | 42 | const token = this.tokenService.getRefreshToken(); 43 | 44 | if (token) 45 | return this.authService.refreshToken(token).pipe( 46 | switchMap((token: any) => { 47 | this.isRefreshing = false; 48 | 49 | this.tokenService.saveToken(token.accessToken); 50 | this.refreshTokenSubject.next(token.accessToken); 51 | 52 | return next.handle(this.addTokenHeader(request, token.accessToken)); 53 | }), 54 | catchError((err) => { 55 | this.isRefreshing = false; 56 | 57 | this.tokenService.signOut(); 58 | return throwError(err); 59 | }) 60 | ); 61 | } 62 | 63 | return this.refreshTokenSubject.pipe( 64 | filter(token => token !== null), 65 | take(1), 66 | switchMap((token) => next.handle(this.addTokenHeader(request, token))) 67 | ); 68 | } 69 | 70 | private addTokenHeader(request: HttpRequest, token: string) { 71 | /* for Spring Boot back-end */ 72 | // return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) }); 73 | 74 | /* for Node.js Express back-end */ 75 | return request.clone({ headers: request.headers.set(TOKEN_HEADER_KEY, token) }); 76 | } 77 | } 78 | 79 | export const authInterceptorProviders = [ 80 | { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } 81 | ]; -------------------------------------------------------------------------------- /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(AUTH_API + 'signin', { 19 | username, 20 | password 21 | }, httpOptions); 22 | } 23 | 24 | register(username: string, email: string, password: string): Observable { 25 | return this.http.post(AUTH_API + 'signup', { 26 | username, 27 | email, 28 | password 29 | }, httpOptions); 30 | } 31 | 32 | refreshToken(token: string) { 33 | return this.http.post(AUTH_API + 'refreshtoken', { 34 | refreshToken: token 35 | }, httpOptions); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/app/_services/token-storage.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { TokenStorageService } from './token-storage.service'; 4 | 5 | describe('TokenStorageService', () => { 6 | let service: TokenStorageService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(TokenStorageService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/token-storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const TOKEN_KEY = 'auth-token'; 4 | const REFRESHTOKEN_KEY = 'auth-refreshtoken'; 5 | const USER_KEY = 'auth-user'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class TokenStorageService { 11 | constructor() { } 12 | 13 | signOut(): void { 14 | window.sessionStorage.clear(); 15 | } 16 | 17 | public saveToken(token: string): void { 18 | window.sessionStorage.removeItem(TOKEN_KEY); 19 | window.sessionStorage.setItem(TOKEN_KEY, token); 20 | 21 | const user = this.getUser(); 22 | if (user.id) { 23 | this.saveUser({ ...user, accessToken: token }); 24 | } 25 | } 26 | 27 | public getToken(): string | null { 28 | return window.sessionStorage.getItem(TOKEN_KEY); 29 | } 30 | 31 | public saveRefreshToken(token: string): void { 32 | window.sessionStorage.removeItem(REFRESHTOKEN_KEY); 33 | window.sessionStorage.setItem(REFRESHTOKEN_KEY, token); 34 | } 35 | 36 | public getRefreshToken(): string | null { 37 | return window.sessionStorage.getItem(REFRESHTOKEN_KEY); 38 | } 39 | 40 | public saveUser(user: any): void { 41 | window.sessionStorage.removeItem(USER_KEY); 42 | window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); 43 | } 44 | 45 | public getUser(): any { 46 | const user = window.sessionStorage.getItem(USER_KEY); 47 | if (user) { 48 | return JSON.parse(user); 49 | } 50 | 51 | return {}; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /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 | constructor() { } 13 | 14 | emit(event: EventData) { 15 | this.subject$.next(event); 16 | } 17 | 18 | on(eventName: string, action: any): Subscription { 19 | return this.subject$.pipe( 20 | filter((e: EventData) => e.name === eventName), 21 | map((e: EventData) => e["value"])).subscribe(action); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/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(async () => { 7 | await TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | }); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'Angular12RefreshToken'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.componentInstance; 26 | expect(app.title).toEqual('Angular12RefreshToken'); 27 | }); 28 | 29 | it('should render title', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.nativeElement as HTMLElement; 33 | expect(compiled.querySelector('.content span')?.textContent).toContain('Angular12RefreshToken app is running!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, OnDestroy } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | import { TokenStorageService } from './_services/token-storage.service'; 4 | import { EventBusService } from './_shared/event-bus.service'; 5 | 6 | @Component({ 7 | selector: 'app-root', 8 | templateUrl: './app.component.html', 9 | styleUrls: ['./app.component.css'] 10 | }) 11 | export class AppComponent implements OnInit, OnDestroy { 12 | private roles: string[] = []; 13 | isLoggedIn = false; 14 | showAdminBoard = false; 15 | showModeratorBoard = false; 16 | username?: string; 17 | 18 | eventBusSub?: Subscription; 19 | 20 | constructor(private tokenStorageService: TokenStorageService, private eventBusService: EventBusService) { } 21 | 22 | ngOnInit(): void { 23 | this.isLoggedIn = !!this.tokenStorageService.getToken(); 24 | 25 | if (this.isLoggedIn) { 26 | const user = this.tokenStorageService.getUser(); 27 | this.roles = user.roles; 28 | 29 | this.showAdminBoard = this.roles.includes('ROLE_ADMIN'); 30 | this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR'); 31 | 32 | this.username = user.username; 33 | } 34 | 35 | this.eventBusSub = this.eventBusService.on('logout', () => { 36 | this.logout(); 37 | }); 38 | } 39 | 40 | ngOnDestroy(): void { 41 | if (this.eventBusSub) 42 | this.eventBusSub.unsubscribe(); 43 | } 44 | 45 | logout(): void { 46 | this.tokenStorageService.signOut(); 47 | 48 | this.isLoggedIn = false; 49 | this.roles = []; 50 | this.showAdminBoard = false; 51 | this.showModeratorBoard = false; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /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 { authInterceptorProviders } from './_helpers/auth.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: [authInterceptorProviders], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { } 39 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardAdminComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardAdminComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | import { EventBusService } from '../_shared/event-bus.service'; 4 | import { EventData } from '../_shared/event.class'; 5 | 6 | @Component({ 7 | selector: 'app-board-admin', 8 | templateUrl: './board-admin.component.html', 9 | styleUrls: ['./board-admin.component.css'] 10 | }) 11 | export class BoardAdminComponent implements OnInit { 12 | content?: string; 13 | 14 | constructor(private userService: UserService, private eventBusService: EventBusService) { } 15 | 16 | ngOnInit(): void { 17 | this.userService.getAdminBoard().subscribe( 18 | data => { 19 | this.content = data; 20 | }, 21 | err => { 22 | this.content = err.error.message || err.error || err.message; 23 | 24 | if (err.status === 403) 25 | this.eventBusService.emit(new EventData('logout', null)); 26 | } 27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardModeratorComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardModeratorComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | import { EventBusService } from '../_shared/event-bus.service'; 4 | import { EventData } from '../_shared/event.class'; 5 | 6 | @Component({ 7 | selector: 'app-board-moderator', 8 | templateUrl: './board-moderator.component.html', 9 | styleUrls: ['./board-moderator.component.css'] 10 | }) 11 | export class BoardModeratorComponent implements OnInit { 12 | content?: string; 13 | 14 | constructor(private userService: UserService, private eventBusService: EventBusService) { } 15 | 16 | ngOnInit(): void { 17 | this.userService.getModeratorBoard().subscribe( 18 | data => { 19 | this.content = data; 20 | }, 21 | err => { 22 | this.content = err.error.message || err.error || err.message; 23 | 24 | if (err.status === 403) 25 | this.eventBusService.emit(new EventData('logout', null)); 26 | } 27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardUserComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(BoardUserComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | import { EventBusService } from '../_shared/event-bus.service'; 4 | import { EventData } from '../_shared/event.class'; 5 | 6 | @Component({ 7 | selector: 'app-board-user', 8 | templateUrl: './board-user.component.html', 9 | styleUrls: ['./board-user.component.css'] 10 | }) 11 | export class BoardUserComponent implements OnInit { 12 | content?: string; 13 | 14 | constructor(private userService: UserService, private eventBusService: EventBusService) { } 15 | 16 | ngOnInit(): void { 17 | this.userService.getUserBoard().subscribe( 18 | data => { 19 | this.content = data; 20 | }, 21 | err => { 22 | this.content = err.error.message || err.error || err.message; 23 | 24 | if (err.status === 403) 25 | this.eventBusService.emit(new EventData('logout', null)); 26 | } 27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /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 | data => { 17 | this.content = data; 18 | }, 19 | err => { 20 | this.content = JSON.parse(err.error).message; 21 | } 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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 | 25 | 32 |
33 |
34 | 35 | 44 | 54 |
55 |
56 | 59 |
60 |
61 | 68 |
69 |
70 | 71 |
72 | Logged in as {{ roles }}. 73 |
74 |
75 |
76 | -------------------------------------------------------------------------------- /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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { TokenStorageService } from '../_services/token-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 tokenStorage: TokenStorageService) { } 21 | 22 | ngOnInit(): void { 23 | if (this.tokenStorage.getToken()) { 24 | this.isLoggedIn = true; 25 | this.roles = this.tokenStorage.getUser().roles; 26 | } 27 | } 28 | 29 | onSubmit(): void { 30 | const { username, password } = this.form; 31 | 32 | this.authService.login(username, password).subscribe( 33 | data => { 34 | this.tokenStorage.saveToken(data.accessToken); 35 | this.tokenStorage.saveRefreshToken(data.refreshToken); 36 | this.tokenStorage.saveUser(data); 37 | 38 | this.isLoginFailed = false; 39 | this.isLoggedIn = true; 40 | this.roles = this.tokenStorage.getUser().roles; 41 | this.reloadPage(); 42 | }, 43 | err => { 44 | this.errorMessage = err.error.message; 45 | this.isLoginFailed = true; 46 | } 47 | ); 48 | } 49 | 50 | reloadPage(): void { 51 | window.location.reload(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

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

6 |
7 |

8 | Token: 9 | {{ currentUser.accessToken.substring(0, 20) }} ... 10 | {{ currentUser.accessToken.substr(currentUser.accessToken.length - 20) }} 11 |

12 |

13 | Email: 14 | {{ currentUser.email }} 15 |

16 | Roles: 17 |
    18 |
  • 19 | {{ role }} 20 |
  • 21 |
22 |
23 | 24 | 25 | Please login. 26 | -------------------------------------------------------------------------------- /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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ ProfileComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(ProfileComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TokenStorageService } from '../_services/token-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 token: TokenStorageService) { } 13 | 14 | ngOnInit(): void { 15 | this.currentUser = this.token.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 | 27 |
28 |
Username is required
29 |
30 | Username must be at least 3 characters 31 |
32 |
33 | Username must be at most 20 characters 34 |
35 |
36 |
37 |
38 | 39 | 48 |
49 |
Email is required
50 |
51 | Email must be a valid email address 52 |
53 |
54 |
55 |
56 | 57 | 66 |
67 |
Password is required
68 |
69 | Password must be at least 6 characters 70 |
71 |
72 |
73 |
74 | 75 |
76 | 77 |
78 | Signup failed!
{{ errorMessage }} 79 |
80 |
81 | 82 |
83 | Your registration is successful! 84 |
85 |
86 |
-------------------------------------------------------------------------------- /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(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ RegisterComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(RegisterComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } 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 implements OnInit { 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 | ngOnInit(): void { 22 | } 23 | 24 | onSubmit(): void { 25 | const { username, email, password } = this.form; 26 | 27 | this.authService.register(username, email, password).subscribe( 28 | data => { 29 | console.log(data); 30 | this.isSuccessful = true; 31 | this.isSignUpFailed = false; 32 | }, 33 | err => { 34 | this.errorMessage = err.error.message; 35 | this.isSignUpFailed = true; 36 | } 37 | ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /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 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-12-jwt-refresh-token/a427f19c9f21c6a8c674bf91b8a20db4639f44da/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular12RefreshToken 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /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/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 Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 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 | * IE11 requires the following for NgClass support on SVG elements 23 | */ 24 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 25 | 26 | /** 27 | * Web Animations `@angular/platform-browser/animations` 28 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 29 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 30 | */ 31 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 32 | 33 | /** 34 | * By default, zone.js will patch all possible macroTask and DomEvents 35 | * user can disable parts of macroTask/DomEvents patch by setting following flags 36 | * because those flags need to be set before `zone.js` being loaded, and webpack 37 | * will put import in the top of bundle, so user need to create a separate file 38 | * in this directory (for example: zone-flags.ts), and put the following flags 39 | * into that file, and then add the following code before importing zone.js. 40 | * import './zone-flags'; 41 | * 42 | * The flags allowed in zone-flags.ts are listed here. 43 | * 44 | * The following flags will work for all browsers. 45 | * 46 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 47 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 48 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 49 | * 50 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 51 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 52 | * 53 | * (window as any).__Zone_enable_cross_context_check = true; 54 | * 55 | */ 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by default for Angular itself. 59 | */ 60 | import 'zone.js'; // Included with Angular CLI. 61 | 62 | 63 | /*************************************************************************************************** 64 | * APPLICATION IMPORTS 65 | */ 66 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /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 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /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 | } 16 | -------------------------------------------------------------------------------- /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 | "noImplicitReturns": true, 10 | "noFallthroughCasesInSwitch": true, 11 | "sourceMap": true, 12 | "declaration": false, 13 | "downlevelIteration": true, 14 | "experimentalDecorators": true, 15 | "moduleResolution": "node", 16 | "importHelpers": true, 17 | "target": "es2017", 18 | "module": "es2020", 19 | "lib": [ 20 | "es2018", 21 | "dom" 22 | ] 23 | }, 24 | "angularCompilerOptions": { 25 | "enableI18nLegacyMessageIdFormat": false, 26 | "strictInjectionParameters": true, 27 | "strictInputAccessModifiers": true, 28 | "strictTemplates": true 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /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 | } 19 | --------------------------------------------------------------------------------