├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── angular.json ├── browserslist ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── _helpers │ │ ├── app.initializer.ts │ │ ├── auth.guard.ts │ │ ├── error.interceptor.ts │ │ ├── fake-backend.ts │ │ ├── index.ts │ │ └── jwt.interceptor.ts │ ├── _models │ │ ├── index.ts │ │ └── user.ts │ ├── _services │ │ ├── authentication.service.ts │ │ ├── index.ts │ │ └── user.service.ts │ ├── app-routing.module.ts │ ├── app.component.html │ ├── app.component.ts │ ├── app.module.ts │ ├── home │ │ ├── home.component.html │ │ ├── home.component.ts │ │ └── index.ts │ └── login │ │ ├── index.ts │ │ ├── login.component.html │ │ └── login.component.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.less └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.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 | # 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 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Jason Watmore 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # angular-9-jwt-refresh-tokens 2 | 3 | Angular 9 - JWT Authentication with Refresh Tokens 4 | 5 | For a demo and further details see https://jasonwatmore.com/post/2020/05/22/angular-9-jwt-authentication-with-refresh-tokens -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-9-jwt-refresh-tokens": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "less" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "aot": true, 26 | "assets": [ 27 | "src/favicon.ico", 28 | "src/assets" 29 | ], 30 | "styles": [ 31 | "src/styles.less" 32 | ], 33 | "scripts": [] 34 | }, 35 | "configurations": { 36 | "production": { 37 | "fileReplacements": [ 38 | { 39 | "replace": "src/environments/environment.ts", 40 | "with": "src/environments/environment.prod.ts" 41 | } 42 | ], 43 | "optimization": true, 44 | "outputHashing": "all", 45 | "sourceMap": false, 46 | "extractCss": true, 47 | "namedChunks": false, 48 | "extractLicenses": true, 49 | "vendorChunk": false, 50 | "buildOptimizer": true, 51 | "budgets": [ 52 | { 53 | "type": "initial", 54 | "maximumWarning": "2mb", 55 | "maximumError": "5mb" 56 | }, 57 | { 58 | "type": "anyComponentStyle", 59 | "maximumWarning": "6kb", 60 | "maximumError": "10kb" 61 | } 62 | ] 63 | } 64 | } 65 | }, 66 | "serve": { 67 | "builder": "@angular-devkit/build-angular:dev-server", 68 | "options": { 69 | "browserTarget": "angular-9-jwt-refresh-tokens:build" 70 | }, 71 | "configurations": { 72 | "production": { 73 | "browserTarget": "angular-9-jwt-refresh-tokens:build:production" 74 | } 75 | } 76 | }, 77 | "extract-i18n": { 78 | "builder": "@angular-devkit/build-angular:extract-i18n", 79 | "options": { 80 | "browserTarget": "angular-9-jwt-refresh-tokens:build" 81 | } 82 | }, 83 | "test": { 84 | "builder": "@angular-devkit/build-angular:karma", 85 | "options": { 86 | "main": "src/test.ts", 87 | "polyfills": "src/polyfills.ts", 88 | "tsConfig": "tsconfig.spec.json", 89 | "karmaConfig": "karma.conf.js", 90 | "assets": [ 91 | "src/favicon.ico", 92 | "src/assets" 93 | ], 94 | "styles": [ 95 | "src/styles.less" 96 | ], 97 | "scripts": [] 98 | } 99 | }, 100 | "lint": { 101 | "builder": "@angular-devkit/build-angular:tslint", 102 | "options": { 103 | "tsConfig": [ 104 | "tsconfig.app.json", 105 | "tsconfig.spec.json", 106 | "e2e/tsconfig.json" 107 | ], 108 | "exclude": [ 109 | "**/node_modules/**" 110 | ] 111 | } 112 | }, 113 | "e2e": { 114 | "builder": "@angular-devkit/build-angular:protractor", 115 | "options": { 116 | "protractorConfig": "e2e/protractor.conf.js", 117 | "devServerTarget": "angular-9-jwt-refresh-tokens:serve" 118 | }, 119 | "configurations": { 120 | "production": { 121 | "devServerTarget": "angular-9-jwt-refresh-tokens:serve:production" 122 | } 123 | } 124 | } 125 | } 126 | }}, 127 | "defaultProject": "angular-9-jwt-refresh-tokens" 128 | } 129 | -------------------------------------------------------------------------------- /browserslist: -------------------------------------------------------------------------------- 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 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('angular-9-jwt-refresh-tokens app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /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-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/angular-9-jwt-refresh-tokens'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-9-jwt-refresh-tokens", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve --open", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "^9.1.1", 15 | "@angular/common": "^9.1.1", 16 | "@angular/compiler": "^9.1.1", 17 | "@angular/core": "^9.1.1", 18 | "@angular/forms": "^9.1.1", 19 | "@angular/platform-browser": "^9.1.1", 20 | "@angular/platform-browser-dynamic": "^9.1.1", 21 | "@angular/router": "^9.1.1", 22 | "rxjs": "^6.5.4", 23 | "tslib": "^1.10.0", 24 | "zone.js": "^0.10.2" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "^0.901.1", 28 | "@angular/cli": "^9.1.1", 29 | "@angular/compiler-cli": "^9.1.1", 30 | "@angular/language-service": "^9.1.1", 31 | "@types/node": "^12.11.1", 32 | "@types/jasmine": "^3.5.0", 33 | "@types/jasminewd2": "^2.0.3", 34 | "codelyzer": "^5.1.2", 35 | "jasmine-core": "^3.5.0", 36 | "jasmine-spec-reporter": "^4.2.1", 37 | "karma": "^4.4.1", 38 | "karma-chrome-launcher": "^3.1.0", 39 | "karma-coverage-istanbul-reporter": "^2.1.0", 40 | "karma-jasmine": "^3.0.1", 41 | "karma-jasmine-html-reporter": "^1.4.2", 42 | "protractor": "^5.4.3", 43 | "ts-node": "^8.3.0", 44 | "tslint": "^6.1.0", 45 | "typescript": "~3.8.3" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/app/_helpers/app.initializer.ts: -------------------------------------------------------------------------------- 1 | import { AuthenticationService } from '@app/_services'; 2 | 3 | export function appInitializer(authenticationService: AuthenticationService) { 4 | return () => new Promise(resolve => { 5 | // attempt to refresh token on app start up to auto authenticate 6 | authenticationService.refreshToken() 7 | .subscribe() 8 | .add(resolve); 9 | }); 10 | } -------------------------------------------------------------------------------- /src/app/_helpers/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '@app/_services'; 5 | 6 | @Injectable({ providedIn: 'root' }) 7 | export class AuthGuard implements CanActivate { 8 | constructor( 9 | private router: Router, 10 | private authenticationService: AuthenticationService 11 | ) { } 12 | 13 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 14 | const user = this.authenticationService.userValue; 15 | if (user) { 16 | // logged in so return true 17 | return true; 18 | } else { 19 | // not logged in so redirect to login page with the return url 20 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 21 | return false; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/app/_helpers/error.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable, throwError } from 'rxjs'; 4 | import { catchError } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Injectable() 9 | export class ErrorInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | return next.handle(request).pipe(catchError(err => { 14 | if ([401, 403].includes(err.status) && this.authenticationService.userValue) { 15 | // auto logout if 401 or 403 response returned from api 16 | this.authenticationService.logout(); 17 | } 18 | 19 | const error = (err && err.error && err.error.message) || err.statusText; 20 | console.error(err); 21 | return throwError(error); 22 | })) 23 | } 24 | } -------------------------------------------------------------------------------- /src/app/_helpers/fake-backend.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS, HttpHeaders } from '@angular/common/http'; 3 | import { Observable, of, throwError } from 'rxjs'; 4 | import { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators'; 5 | 6 | // array in local storage for users 7 | const usersKey = 'angular-9-jwt-refresh-token-users'; 8 | const users = JSON.parse(localStorage.getItem(usersKey)) || []; 9 | 10 | // add test user and save if users array is empty 11 | if (!users.length) { 12 | users.push({ id: 1, firstName: 'Test', lastName: 'User', username: 'test', password: 'test', refreshTokens: [] }); 13 | localStorage.setItem(usersKey, JSON.stringify(users)); 14 | } 15 | 16 | @Injectable() 17 | export class FakeBackendInterceptor implements HttpInterceptor { 18 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 19 | const { url, method, headers, body } = request; 20 | 21 | // wrap in delayed observable to simulate server api call 22 | return of(null) 23 | .pipe(mergeMap(handleRoute)) 24 | .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648) 25 | .pipe(delay(500)) 26 | .pipe(dematerialize()); 27 | 28 | function handleRoute() { 29 | switch (true) { 30 | case url.endsWith('/users/authenticate') && method === 'POST': 31 | return authenticate(); 32 | case url.endsWith('/users/refresh-token') && method === 'POST': 33 | return refreshToken(); 34 | case url.endsWith('/users/revoke-token') && method === 'POST': 35 | return revokeToken(); 36 | case url.endsWith('/users') && method === 'GET': 37 | return getUsers(); 38 | default: 39 | // pass through any requests not handled above 40 | return next.handle(request); 41 | } 42 | } 43 | 44 | // route functions 45 | 46 | function authenticate() { 47 | const { username, password } = body; 48 | const user = users.find(x => x.username === username && x.password === password); 49 | 50 | if (!user) return error('Username or password is incorrect'); 51 | 52 | // add refresh token to user 53 | user.refreshTokens.push(generateRefreshToken()); 54 | localStorage.setItem(usersKey, JSON.stringify(users)); 55 | 56 | return ok({ 57 | id: user.id, 58 | username: user.username, 59 | firstName: user.firstName, 60 | lastName: user.lastName, 61 | jwtToken: generateJwtToken() 62 | }) 63 | } 64 | 65 | function refreshToken() { 66 | const refreshToken = getRefreshToken(); 67 | 68 | if (!refreshToken) return unauthorized(); 69 | 70 | const user = users.find(x => x.refreshTokens.includes(refreshToken)); 71 | 72 | if (!user) return unauthorized(); 73 | 74 | // replace old refresh token with a new one and save 75 | user.refreshTokens = user.refreshTokens.filter(x => x !== refreshToken); 76 | user.refreshTokens.push(generateRefreshToken()); 77 | localStorage.setItem(usersKey, JSON.stringify(users)); 78 | 79 | return ok({ 80 | id: user.id, 81 | username: user.username, 82 | firstName: user.firstName, 83 | lastName: user.lastName, 84 | jwtToken: generateJwtToken() 85 | }) 86 | } 87 | 88 | function revokeToken() { 89 | if (!isLoggedIn()) return unauthorized(); 90 | 91 | const refreshToken = getRefreshToken(); 92 | const user = users.find(x => x.refreshTokens.includes(refreshToken)); 93 | 94 | // revoke token and save 95 | user.refreshTokens = user.refreshTokens.filter(x => x !== refreshToken); 96 | localStorage.setItem(usersKey, JSON.stringify(users)); 97 | 98 | return ok(); 99 | } 100 | 101 | function getUsers() { 102 | if (!isLoggedIn()) return unauthorized(); 103 | return ok(users); 104 | } 105 | 106 | // helper functions 107 | 108 | function ok(body?) { 109 | return of(new HttpResponse({ status: 200, body })) 110 | } 111 | 112 | function error(message) { 113 | return throwError({ error: { message } }); 114 | } 115 | 116 | function unauthorized() { 117 | return throwError({ status: 401, error: { message: 'Unauthorized' } }); 118 | } 119 | 120 | function isLoggedIn() { 121 | // check if jwt token is in auth header 122 | const authHeader = headers.get('Authorization'); 123 | if (!authHeader.startsWith('Bearer fake-jwt-token')) return false; 124 | 125 | // check if token is expired 126 | const jwtToken = JSON.parse(atob(authHeader.split('.')[1])); 127 | const tokenExpired = Date.now() > (jwtToken.exp * 1000); 128 | if (tokenExpired) return false; 129 | 130 | return true; 131 | } 132 | 133 | function generateJwtToken() { 134 | // create token that expires in 15 minutes 135 | const tokenPayload = { exp: Math.round(new Date(Date.now() + 15*60*1000).getTime() / 1000) } 136 | return `fake-jwt-token.${btoa(JSON.stringify(tokenPayload))}`; 137 | } 138 | 139 | function generateRefreshToken() { 140 | const token = new Date().getTime().toString(); 141 | 142 | // add token cookie that expires in 7 days 143 | const expires = new Date(Date.now() + 7*24*60*60*1000).toUTCString(); 144 | document.cookie = `fakeRefreshToken=${token}; expires=${expires}; path=/`; 145 | 146 | return token; 147 | } 148 | 149 | function getRefreshToken() { 150 | // get refresh token from cookie 151 | return (document.cookie.split(';').find(x => x.includes('fakeRefreshToken')) || '=').split('=')[1]; 152 | } 153 | } 154 | } 155 | 156 | export let fakeBackendProvider = { 157 | // use fake backend in place of Http service for backend-less development 158 | provide: HTTP_INTERCEPTORS, 159 | useClass: FakeBackendInterceptor, 160 | multi: true 161 | }; -------------------------------------------------------------------------------- /src/app/_helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './app.initializer'; 2 | export * from './auth.guard'; 3 | export * from './error.interceptor'; 4 | export * from './fake-backend'; 5 | export * from './jwt.interceptor'; -------------------------------------------------------------------------------- /src/app/_helpers/jwt.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | import { environment } from '@environments/environment'; 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Injectable() 9 | export class JwtInterceptor implements HttpInterceptor { 10 | constructor(private authenticationService: AuthenticationService) { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | // add auth header with jwt if user is logged in and request is to the api url 14 | const user = this.authenticationService.userValue; 15 | const isLoggedIn = user && user.jwtToken; 16 | const isApiUrl = request.url.startsWith(environment.apiUrl); 17 | if (isLoggedIn && isApiUrl) { 18 | request = request.clone({ 19 | setHeaders: { Authorization: `Bearer ${user.jwtToken}` } 20 | }); 21 | } 22 | 23 | return next.handle(request); 24 | } 25 | } -------------------------------------------------------------------------------- /src/app/_models/index.ts: -------------------------------------------------------------------------------- 1 | export * from './user'; -------------------------------------------------------------------------------- /src/app/_models/user.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | id: number; 3 | username: string; 4 | password: string; 5 | firstName: string; 6 | lastName: string; 7 | jwtToken?: string; 8 | } -------------------------------------------------------------------------------- /src/app/_services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { HttpClient } from '@angular/common/http'; 4 | import { BehaviorSubject, Observable } from 'rxjs'; 5 | import { map } from 'rxjs/operators'; 6 | 7 | import { environment } from '@environments/environment'; 8 | import { User } from '@app/_models'; 9 | 10 | @Injectable({ providedIn: 'root' }) 11 | export class AuthenticationService { 12 | private userSubject: BehaviorSubject; 13 | public user: Observable; 14 | 15 | constructor( 16 | private router: Router, 17 | private http: HttpClient 18 | ) { 19 | this.userSubject = new BehaviorSubject(null); 20 | this.user = this.userSubject.asObservable(); 21 | } 22 | 23 | public get userValue(): User { 24 | return this.userSubject.value; 25 | } 26 | 27 | login(username: string, password: string) { 28 | return this.http.post(`${environment.apiUrl}/users/authenticate`, { username, password }, { withCredentials: true }) 29 | .pipe(map(user => { 30 | this.userSubject.next(user); 31 | this.startRefreshTokenTimer(); 32 | return user; 33 | })); 34 | } 35 | 36 | logout() { 37 | this.http.post(`${environment.apiUrl}/users/revoke-token`, {}, { withCredentials: true }).subscribe(); 38 | this.stopRefreshTokenTimer(); 39 | this.userSubject.next(null); 40 | this.router.navigate(['/login']); 41 | } 42 | 43 | refreshToken() { 44 | return this.http.post(`${environment.apiUrl}/users/refresh-token`, {}, { withCredentials: true }) 45 | .pipe(map((user) => { 46 | this.userSubject.next(user); 47 | this.startRefreshTokenTimer(); 48 | return user; 49 | })); 50 | } 51 | 52 | // helper methods 53 | 54 | private refreshTokenTimeout; 55 | 56 | private startRefreshTokenTimer() { 57 | // parse json object from base64 encoded jwt token 58 | const jwtToken = JSON.parse(atob(this.userValue.jwtToken.split('.')[1])); 59 | 60 | // set a timeout to refresh the token a minute before it expires 61 | const expires = new Date(jwtToken.exp * 1000); 62 | const timeout = expires.getTime() - Date.now() - (60 * 1000); 63 | this.refreshTokenTimeout = setTimeout(() => this.refreshToken().subscribe(), timeout); 64 | } 65 | 66 | private stopRefreshTokenTimer() { 67 | clearTimeout(this.refreshTokenTimeout); 68 | } 69 | } -------------------------------------------------------------------------------- /src/app/_services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './authentication.service'; 2 | export * from './user.service'; -------------------------------------------------------------------------------- /src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | import { environment } from '@environments/environment'; 5 | import { User } from '@app/_models'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class UserService { 9 | constructor(private http: HttpClient) { } 10 | 11 | getAll() { 12 | return this.http.get(`${environment.apiUrl}/users`); 13 | } 14 | } -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | import { HomeComponent } from './home'; 5 | import { LoginComponent } from './login'; 6 | import { AuthGuard } from './_helpers'; 7 | 8 | const routes: Routes = [ 9 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 10 | { path: 'login', component: LoginComponent }, 11 | 12 | // otherwise redirect to home 13 | { path: '**', redirectTo: '' } 14 | ]; 15 | 16 | @NgModule({ 17 | imports: [RouterModule.forRoot(routes)], 18 | exports: [RouterModule] 19 | }) 20 | export class AppRoutingModule { } 21 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |  2 | 8 | 9 | 10 |
11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | import { AuthenticationService } from './_services'; 4 | import { User } from './_models'; 5 | 6 | @Component({ selector: 'app', templateUrl: 'app.component.html' }) 7 | export class AppComponent { 8 | user: User; 9 | 10 | constructor(private authenticationService: AuthenticationService) { 11 | this.authenticationService.user.subscribe(x => this.user = x); 12 | } 13 | 14 | logout() { 15 | this.authenticationService.logout(); 16 | } 17 | } -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule, APP_INITIALIZER } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | // used to create fake backend 7 | import { fakeBackendProvider } from './_helpers'; 8 | 9 | import { AppComponent } from './app.component'; 10 | import { AppRoutingModule } from './app-routing.module'; 11 | 12 | import { JwtInterceptor, ErrorInterceptor, appInitializer } from './_helpers'; 13 | import { AuthenticationService } from './_services'; 14 | import { HomeComponent } from './home'; 15 | import { LoginComponent } from './login'; 16 | 17 | @NgModule({ 18 | imports: [ 19 | BrowserModule, 20 | ReactiveFormsModule, 21 | HttpClientModule, 22 | AppRoutingModule 23 | ], 24 | declarations: [ 25 | AppComponent, 26 | HomeComponent, 27 | LoginComponent 28 | ], 29 | providers: [ 30 | { provide: APP_INITIALIZER, useFactory: appInitializer, multi: true, deps: [AuthenticationService] }, 31 | { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 32 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, 33 | 34 | // provider used to create fake backend 35 | fakeBackendProvider 36 | ], 37 | bootstrap: [AppComponent] 38 | }) 39 | export class AppModule { } -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 | 
2 |

You're logged in with Angular 9 + JWT & Refresh Tokens!!

3 |
4 |
Users from secure api end point
5 |
6 |
    7 |
  • {{user.firstName}} {{user.lastName}}
  • 8 |
9 |
10 |
-------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { first } from 'rxjs/operators'; 3 | 4 | import { User } from '@app/_models'; 5 | import { UserService } from '@app/_services'; 6 | 7 | @Component({ templateUrl: 'home.component.html' }) 8 | export class HomeComponent { 9 | loading = false; 10 | users: User[]; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit() { 15 | this.loading = true; 16 | this.userService.getAll().pipe(first()).subscribe(users => { 17 | this.loading = false; 18 | this.users = users; 19 | }); 20 | } 21 | } -------------------------------------------------------------------------------- /src/app/home/index.ts: -------------------------------------------------------------------------------- 1 | export * from './home.component'; -------------------------------------------------------------------------------- /src/app/login/index.ts: -------------------------------------------------------------------------------- 1 | export * from './login.component'; -------------------------------------------------------------------------------- /src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 | 
2 |
3 | Username: test
4 | Password: test 5 |
6 |
7 |

Angular 9 JWT Auth with Refresh Tokens

8 |
9 |
10 |
11 | 12 | 13 |
14 |
Username is required
15 |
16 |
17 |
18 | 19 | 20 |
21 |
Password is required
22 |
23 |
24 | 28 |
{{error}}
29 |
30 |
31 |
32 |
-------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 4 | import { first } from 'rxjs/operators'; 5 | 6 | import { AuthenticationService } from '@app/_services'; 7 | 8 | @Component({ templateUrl: 'login.component.html' }) 9 | export class LoginComponent implements OnInit { 10 | loginForm: FormGroup; 11 | loading = false; 12 | submitted = false; 13 | returnUrl: string; 14 | error = ''; 15 | 16 | constructor( 17 | private formBuilder: FormBuilder, 18 | private route: ActivatedRoute, 19 | private router: Router, 20 | private authenticationService: AuthenticationService 21 | ) { 22 | // redirect to home if already logged in 23 | if (this.authenticationService.userValue) { 24 | this.router.navigate(['/']); 25 | } 26 | } 27 | 28 | ngOnInit() { 29 | this.loginForm = this.formBuilder.group({ 30 | username: ['', Validators.required], 31 | password: ['', Validators.required] 32 | }); 33 | 34 | // get return url from route parameters or default to '/' 35 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 36 | } 37 | 38 | // convenience getter for easy access to form fields 39 | get f() { return this.loginForm.controls; } 40 | 41 | onSubmit() { 42 | this.submitted = true; 43 | 44 | // stop here if form is invalid 45 | if (this.loginForm.invalid) { 46 | return; 47 | } 48 | 49 | this.loading = true; 50 | this.authenticationService.login(this.f.username.value, this.f.password.value) 51 | .pipe(first()) 52 | .subscribe({ 53 | next: () => { 54 | this.router.navigate([this.returnUrl]); 55 | }, 56 | error: error => { 57 | this.error = error; 58 | this.loading = false; 59 | } 60 | }); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cornflourblue/angular-9-jwt-refresh-tokens/6a6e22f76439de7ba220ca6d5355f2a841cde8c4/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | apiUrl: 'http://localhost:4000' 4 | }; 5 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false, 7 | apiUrl: 'http://localhost:4000' 8 | }; 9 | 10 | /* 11 | * For easier debugging in development mode, you can import the following file 12 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 13 | * 14 | * This import should be commented out in production mode because it will have a negative impact 15 | * on performance if an error is thrown. 16 | */ 17 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 18 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cornflourblue/angular-9-jwt-refresh-tokens/6a6e22f76439de7ba220ca6d5355f2a841cde8c4/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular 9 - JWT Authentication with Refresh Tokens 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/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 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /src/styles.less: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | a { cursor: pointer } -------------------------------------------------------------------------------- /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/dist/zone-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 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "lib": [ 15 | "es2018", 16 | "dom" 17 | ], 18 | "paths": { 19 | "@app/*": ["src/app/*"], 20 | "@environments/*": ["src/environments/*"] 21 | } 22 | }, 23 | "angularCompilerOptions": { 24 | "fullTemplateTypeCheck": true, 25 | "strictInjectionParameters": true 26 | } 27 | } -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 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 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": [ 6 | "parameters", 7 | "statements" 8 | ] 9 | }, 10 | "array-type": false, 11 | "arrow-return-shorthand": true, 12 | "curly": true, 13 | "deprecation": { 14 | "severity": "warning" 15 | }, 16 | "component-class-suffix": true, 17 | "contextual-lifecycle": true, 18 | "directive-class-suffix": true, 19 | "directive-selector": [ 20 | true, 21 | "attribute", 22 | "app", 23 | "camelCase" 24 | ], 25 | "component-selector": [ 26 | true, 27 | "element", 28 | "app", 29 | "kebab-case" 30 | ], 31 | "eofline": true, 32 | "import-blacklist": [ 33 | true, 34 | "rxjs/Rx" 35 | ], 36 | "import-spacing": true, 37 | "indent": { 38 | "options": [ 39 | "spaces" 40 | ] 41 | }, 42 | "max-classes-per-file": false, 43 | "max-line-length": [ 44 | true, 45 | 140 46 | ], 47 | "member-ordering": [ 48 | true, 49 | { 50 | "order": [ 51 | "static-field", 52 | "instance-field", 53 | "static-method", 54 | "instance-method" 55 | ] 56 | } 57 | ], 58 | "no-console": [ 59 | true, 60 | "debug", 61 | "info", 62 | "time", 63 | "timeEnd", 64 | "trace" 65 | ], 66 | "no-empty": false, 67 | "no-inferrable-types": [ 68 | true, 69 | "ignore-params" 70 | ], 71 | "no-non-null-assertion": true, 72 | "no-redundant-jsdoc": true, 73 | "no-switch-case-fall-through": true, 74 | "no-var-requires": false, 75 | "object-literal-key-quotes": [ 76 | true, 77 | "as-needed" 78 | ], 79 | "quotemark": [ 80 | true, 81 | "single" 82 | ], 83 | "semicolon": { 84 | "options": [ 85 | "always" 86 | ] 87 | }, 88 | "space-before-function-paren": { 89 | "options": { 90 | "anonymous": "never", 91 | "asyncArrow": "always", 92 | "constructor": "never", 93 | "method": "never", 94 | "named": "never" 95 | } 96 | }, 97 | "typedef-whitespace": { 98 | "options": [ 99 | { 100 | "call-signature": "nospace", 101 | "index-signature": "nospace", 102 | "parameter": "nospace", 103 | "property-declaration": "nospace", 104 | "variable-declaration": "nospace" 105 | }, 106 | { 107 | "call-signature": "onespace", 108 | "index-signature": "onespace", 109 | "parameter": "onespace", 110 | "property-declaration": "onespace", 111 | "variable-declaration": "onespace" 112 | } 113 | ] 114 | }, 115 | "variable-name": { 116 | "options": [ 117 | "ban-keywords", 118 | "check-format", 119 | "allow-pascal-case" 120 | ] 121 | }, 122 | "whitespace": { 123 | "options": [ 124 | "check-branch", 125 | "check-decl", 126 | "check-operator", 127 | "check-separator", 128 | "check-type", 129 | "check-typecast" 130 | ] 131 | }, 132 | "no-conflicting-lifecycle": true, 133 | "no-host-metadata-property": true, 134 | "no-input-rename": true, 135 | "no-inputs-metadata-property": true, 136 | "no-output-native": true, 137 | "no-output-on-prefix": true, 138 | "no-output-rename": true, 139 | "no-outputs-metadata-property": true, 140 | "template-banana-in-box": true, 141 | "template-no-negated-async": true, 142 | "use-lifecycle-interface": true, 143 | "use-pipe-transform-interface": true 144 | }, 145 | "rulesDirectory": [ 146 | "codelyzer" 147 | ] 148 | } --------------------------------------------------------------------------------