├── src ├── assets │ └── .gitkeep ├── favicon.ico ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── silent-refresh.html ├── app │ ├── shared │ │ ├── shared.module.ts │ │ └── api.service.ts │ ├── fallback.component.ts │ ├── feature-basics │ │ ├── public.component.ts │ │ ├── home.component.ts │ │ ├── admin1.component.ts │ │ └── basics.module.ts │ ├── core │ │ ├── auth-module-config.ts │ │ ├── auth-guard.service.ts │ │ ├── auth-config.ts │ │ ├── auth-guard-with-forced-login.service.ts │ │ ├── core.module.ts │ │ └── auth.service.ts │ ├── should-login.component.ts │ ├── feature-extras │ │ ├── admin2.component.ts │ │ └── extras.module.ts │ ├── app.module.ts │ ├── app-menu.component.ts │ └── app.component.ts ├── tsconfig.app.json ├── tsconfig.spec.json ├── tslint.json ├── browserslist ├── main.ts ├── styles.css ├── index.html ├── test.ts ├── karma.conf.js └── polyfills.ts ├── screenshot-001.png ├── e2e ├── src │ ├── app.po.ts │ └── app.e2e-spec.ts ├── tsconfig.e2e.json └── protractor.conf.js ├── .editorconfig ├── tsconfig.json ├── .vscode └── launch.json ├── .gitignore ├── LICENSE ├── package.json ├── README.md ├── tslint.json └── angular.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunobritodev/sample-angular-oauth2-oidc-with-auth-guards/master/src/favicon.ico -------------------------------------------------------------------------------- /screenshot-001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunobritodev/sample-angular-oauth2-oidc-with-auth-guards/master/screenshot-001.png -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | ResourceServer: 'http://api.teste.work' 4 | }; 5 | -------------------------------------------------------------------------------- /src/silent-refresh.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { ApiService } from './api.service'; 4 | 5 | @NgModule({ 6 | providers: [ 7 | ApiService, 8 | ] 9 | }) 10 | export class SharedModule { } 11 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "esnext", 6 | "types": [] 7 | }, 8 | "exclude": [ 9 | "src/test.ts", 10 | "**/*.spec.ts" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/app/fallback.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-fallback', 5 | template: `

This is the 🕳️ FALLBACK component.

`, 6 | }) 7 | export class FallbackComponent { 8 | } 9 | -------------------------------------------------------------------------------- /src/app/feature-basics/public.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-public', 5 | template: `

This is the 🌐 PUBLIC component.

`, 6 | }) 7 | export class PublicComponent { 8 | } 9 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://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 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /src/app/core/auth-module-config.ts: -------------------------------------------------------------------------------- 1 | import { OAuthModuleConfig } from 'angular-oauth2-oidc'; 2 | import { environment } from 'src/environments/environment'; 3 | 4 | export const authModuleConfig: OAuthModuleConfig = { 5 | resourceServer: { 6 | allowedUrls: [environment.ResourceServer], 7 | sendAccessToken: true, 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "types": [ 7 | "jasmine", 8 | "node" 9 | ] 10 | }, 11 | "files": [ 12 | "test.ts", 13 | "polyfills.ts" 14 | ], 15 | "include": [ 16 | "**/*.spec.ts", 17 | "**/*.d.ts" 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('workspace-project App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to sample-auth-guards!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed 5 | > 0.5% 6 | last 2 versions 7 | Firefox ESR 8 | not dead 9 | # IE 9-11 -------------------------------------------------------------------------------- /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.log(err)); 13 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | .authenticating-loader { 2 | display: flex; 3 | align-items: center; 4 | justify-content: center; 5 | position: fixed; 6 | top: 0; 7 | right: 0; 8 | bottom: 0; 9 | left: 0; 10 | font-size: 5rem; 11 | background: #fff; 12 | opacity: 0.8; 13 | } 14 | 15 | .pre { 16 | white-space: pre; 17 | } 18 | 19 | .break-all { 20 | word-break: break-all; 21 | } 22 | 23 | .table-props tr th { 24 | width: 1px; 25 | } 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SampleAuthGuards 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/app/should-login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { OAuthService } from 'angular-oauth2-oidc'; 3 | 4 | @Component({ 5 | selector: 'app-should-login', 6 | template: `

You need to be logged in to view requested page.

7 |

Please log in before continuing.

`, 8 | }) 9 | export class ShouldLoginComponent { 10 | constructor(private authService: OAuthService) { } 11 | 12 | public login($event) { 13 | $event.preventDefault(); 14 | this.authService.initImplicitFlow(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/app/feature-basics/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { ApiService } from '../shared/api.service'; 3 | import { Observable } from 'rxjs'; 4 | 5 | @Component({ 6 | selector: 'app-home', 7 | template: `

8 | This is the 🏠 HOME component. 9 | - {{ apiResponse | async }} 10 |

`, 11 | }) 12 | export class HomeComponent { 13 | apiResponse: Observable; 14 | 15 | constructor(private apiService: ApiService) { } 16 | 17 | ngOnInit() { 18 | this.apiResponse = this.apiService.getProtectedApiResponse(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Launch Program", 11 | "program": "${workspaceFolder}\\serve", 12 | "preLaunchTask": "tsc: build - tsconfig.json", 13 | "outFiles": [ 14 | "${workspaceFolder}/dist/out-tsc/**/*.js" 15 | ] 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /.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 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | yarn-error.log 34 | testem.log 35 | /typings 36 | 37 | # System Files 38 | .DS_Store 39 | Thumbs.db 40 | -------------------------------------------------------------------------------- /src/app/feature-extras/admin2.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | import { ApiService } from '../shared/api.service'; 4 | 5 | @Component({ 6 | selector: 'app-admin', 7 | template: `

8 | This is the 🔧 ADMIN 2 component. 9 | It will redirect you to login if needed. 10 | - {{ apiResponse | async }} 11 |

`, 12 | }) 13 | export class Admin2Component implements OnInit { 14 | apiResponse: Observable; 15 | 16 | constructor(private apiService: ApiService) { } 17 | 18 | ngOnInit() { 19 | this.apiResponse = this.apiService.getProtectedApiResponse(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/feature-basics/admin1.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | 4 | import { ApiService } from '../shared/api.service'; 5 | 6 | @Component({ 7 | selector: 'app-admin', 8 | template: `

9 | This is the ⚙ ADMIN component. 10 | It will not redirect you to the login server. 11 | - {{ apiResponse | async }} 12 |

`, 13 | }) 14 | export class Admin1Component implements OnInit { 15 | apiResponse: Observable; 16 | 17 | constructor(private apiService: ApiService) { } 18 | 19 | ngOnInit() { 20 | this.apiResponse = this.apiService.getProtectedApiResponse(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import { getTestBed } from '@angular/core/testing'; 4 | import { 5 | BrowserDynamicTestingModule, 6 | platformBrowserDynamicTesting 7 | } from '@angular/platform-browser-dynamic/testing'; 8 | import 'zone.js/dist/zone-testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/app/feature-extras/extras.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { RouterModule } from '@angular/router'; 4 | 5 | import { AuthGuardWithForcedLogin } from '../core/auth-guard-with-forced-login.service'; 6 | import { SharedModule } from '../shared/shared.module'; 7 | 8 | import { Admin2Component } from './admin2.component'; 9 | 10 | @NgModule({ 11 | declarations: [ 12 | Admin2Component, 13 | ], 14 | imports: [ 15 | CommonModule, 16 | SharedModule, 17 | RouterModule.forChild([ 18 | { path: 'admin2', component: Admin2Component, canActivate: [AuthGuardWithForcedLogin] }, 19 | ]), 20 | ], 21 | }) 22 | export class ExtrasModule { } 23 | -------------------------------------------------------------------------------- /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 | ResourceServer: 'http://api.teste.work' 8 | }; 9 | 10 | /* 11 | * In development mode, to ignore zone related error stack frames such as 12 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can 13 | * import the following file, but please comment it out in production mode 14 | * because it will have performance impact when throw error 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/app/core/auth-guard.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { tap } from 'rxjs/operators'; 5 | 6 | import { AuthService } from './auth.service'; 7 | 8 | @Injectable() 9 | export class AuthGuard implements CanActivate { 10 | constructor( 11 | private authService: AuthService, 12 | ) { } 13 | 14 | canActivate( 15 | route: ActivatedRouteSnapshot, 16 | state: RouterStateSnapshot, 17 | ): Observable { 18 | return this.authService.canActivateProtectedRoutes$ 19 | .pipe(tap(x => console.log('You tried to go to ' + state.url + ' and this guard said ' + x))); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/core/auth-config.ts: -------------------------------------------------------------------------------- 1 | import { AuthConfig } from 'angular-oauth2-oidc'; 2 | 3 | export const authConfig: AuthConfig = { 4 | issuer: 'https://sso.teste.work', 5 | clientId: 'angular-demo', 6 | redirectUri: window.location.origin + '/index.html', 7 | silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html', 8 | scope: 'openid profile email api_demo.api jp_api.user', 9 | requireHttps: true, 10 | silentRefreshTimeout: 5000, // For faster testing 11 | timeoutFactor: 0.25, // For faster testing 12 | sessionChecksEnabled: true, 13 | showDebugInformation: true, // Also requires enabling "Verbose" level in devtools 14 | clearHashAfterLogin: false, // https://github.com/manfredsteyer/angular-oauth2-oidc/issues/457#issuecomment-431807040 15 | }; 16 | -------------------------------------------------------------------------------- /src/app/shared/api.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, of } from 'rxjs'; 3 | import { HttpClient, HttpErrorResponse } from '@angular/common/http'; 4 | import { map, catchError, tap } from 'rxjs/operators'; 5 | import { environment } from 'src/environments/environment'; 6 | 7 | @Injectable() 8 | export class ApiService { 9 | constructor(private http: HttpClient) { } 10 | 11 | getProtectedApiResponse(): Observable { 12 | return this.http.get(`${environment.ResourceServer}/management/user-data`) 13 | .pipe( 14 | map((response: any) => response.data.userName), 15 | map(iss => '☁ API Success! Username ' + iss), 16 | catchError((e: HttpErrorResponse) => of(`🌩 API Error: ${e.status} ${e.statusText}`)), 17 | ); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /src/app/core/auth-guard-with-forced-login.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { filter, map, tap } from 'rxjs/operators'; 5 | 6 | import { AuthService } from './auth.service'; 7 | 8 | @Injectable() 9 | export class AuthGuardWithForcedLogin implements CanActivate { 10 | private isAuthenticated: boolean; 11 | 12 | constructor( 13 | private authService: AuthService, 14 | ) { 15 | this.authService.isAuthenticated$.subscribe(i => this.isAuthenticated = i); 16 | } 17 | 18 | canActivate( 19 | route: ActivatedRouteSnapshot, 20 | state: RouterStateSnapshot, 21 | ): Observable { 22 | return this.authService.isDoneLoading$ 23 | .pipe(filter(isDone => isDone)) 24 | .pipe(tap(_ => this.isAuthenticated || this.authService.login(state.url))) 25 | .pipe(map(_ => this.isAuthenticated)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2018, Jeroen Heijmans 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /src/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'), 20 | reports: ['html', 'lcovonly'], 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 | }); 31 | }; -------------------------------------------------------------------------------- /src/app/feature-basics/basics.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { RouterModule } from '@angular/router'; 4 | 5 | import { AuthGuard } from '../core/auth-guard.service'; 6 | import { ApiService } from '../shared/api.service'; 7 | import { SharedModule } from '../shared/shared.module'; 8 | 9 | import { Admin1Component } from './admin1.component'; 10 | import { HomeComponent } from './home.component'; 11 | import { PublicComponent } from './public.component'; 12 | 13 | @NgModule({ 14 | declarations: [ 15 | Admin1Component, 16 | HomeComponent, 17 | PublicComponent, 18 | ], 19 | imports: [ 20 | CommonModule, 21 | SharedModule, 22 | RouterModule.forChild([ 23 | { path: '', redirectTo: 'home', pathMatch: 'full' }, 24 | { path: 'home', component: HomeComponent }, 25 | { path: 'admin1', component: Admin1Component, canActivate: [AuthGuard] }, 26 | { path: 'public', component: PublicComponent }, 27 | ]), 28 | ], 29 | providers: [ 30 | ApiService, 31 | ], 32 | }) 33 | export class BasicsModule { } 34 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { RouterModule } from '@angular/router'; 4 | 5 | import { AppMenuComponent } from './app-menu.component'; 6 | import { AppComponent } from './app.component'; 7 | import { CoreModule } from './core/core.module'; 8 | import { FallbackComponent } from './fallback.component'; 9 | import { ShouldLoginComponent } from './should-login.component'; 10 | 11 | @NgModule({ 12 | declarations: [ 13 | AppComponent, 14 | AppMenuComponent, 15 | FallbackComponent, 16 | ShouldLoginComponent, 17 | ], 18 | imports: [ 19 | BrowserModule, 20 | CoreModule.forRoot(), 21 | RouterModule.forRoot([ 22 | { path: '', redirectTo: 'basics/home', pathMatch: 'full' }, 23 | 24 | // Note: this way of module loading requires this in your tsconfig.json: "module": "esnext" 25 | { path: 'basics', loadChildren: () => import('./feature-basics/basics.module').then(m => m.BasicsModule) }, 26 | { path: 'extras', loadChildren: () => import('./feature-extras/extras.module').then(m => m.ExtrasModule) }, 27 | 28 | { path: 'should-login', component: ShouldLoginComponent }, 29 | { path: '**', component: FallbackComponent }, 30 | ]) 31 | ], 32 | bootstrap: [AppComponent] 33 | }) 34 | export class AppModule { } 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sample-auth-guards", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 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": "^8.2.1", 15 | "@angular/common": "^8.2.1", 16 | "@angular/compiler": "^8.2.1", 17 | "@angular/core": "^8.2.1", 18 | "@angular/forms": "^8.2.1", 19 | "@angular/http": "^7.2.15", 20 | "@angular/platform-browser": "^8.2.1", 21 | "@angular/platform-browser-dynamic": "^8.2.1", 22 | "@angular/router": "^8.2.1", 23 | "angular-oauth2-oidc": "^8.0.4", 24 | "core-js": "^2.5.4", 25 | "rxjs": "^6.5.2", 26 | "zone.js": "^0.9.1" 27 | }, 28 | "devDependencies": { 29 | "@angular/compiler-cli": "^8.2.1", 30 | "@angular-devkit/build-angular": "~0.802.1", 31 | "@angular/cli": "~8.2.1", 32 | "@angular/language-service": "^8.2.1", 33 | "@types/jasmine": "~3.3.8", 34 | "@types/jasminewd2": "~2.0.3", 35 | "@types/node": "~8.9.4", 36 | "codelyzer": "~5.1.0", 37 | "jasmine-core": "~3.4.0", 38 | "jasmine-spec-reporter": "~4.2.1", 39 | "karma": "~4.1.0", 40 | "karma-chrome-launcher": "~2.2.0", 41 | "karma-coverage-istanbul-reporter": "~2.0.1", 42 | "karma-jasmine": "~2.0.1", 43 | "karma-jasmine-html-reporter": "^1.4.0", 44 | "protractor": "~5.4.0", 45 | "ts-node": "~7.0.0", 46 | "tslint": "~5.15.0", 47 | "typescript": "~3.5.3" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpClientModule } from '@angular/common/http'; 2 | import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core'; 3 | import { AuthConfig, JwksValidationHandler, OAuthModule, OAuthModuleConfig, OAuthStorage, ValidationHandler } from 'angular-oauth2-oidc'; 4 | 5 | import { authConfig } from './auth-config'; 6 | import { AuthGuardWithForcedLogin } from './auth-guard-with-forced-login.service'; 7 | import { AuthGuard } from './auth-guard.service'; 8 | import { authModuleConfig } from './auth-module-config'; 9 | import { AuthService } from './auth.service'; 10 | 11 | // We need a factory since localStorage is not available at AOT build time 12 | export function storageFactory() : OAuthStorage { 13 | return localStorage 14 | } 15 | 16 | @NgModule({ 17 | imports: [ 18 | HttpClientModule, 19 | OAuthModule.forRoot(), 20 | ], 21 | providers: [ 22 | AuthService, 23 | AuthGuard, 24 | AuthGuardWithForcedLogin, 25 | ], 26 | }) 27 | export class CoreModule { 28 | static forRoot(): ModuleWithProviders { 29 | return { 30 | ngModule: CoreModule, 31 | providers: [ 32 | { provide: AuthConfig, useValue: authConfig }, 33 | { provide: OAuthModuleConfig, useValue: authModuleConfig }, 34 | { provide: ValidationHandler, useClass: JwksValidationHandler }, 35 | { provide: OAuthStorage, useFactory: storageFactory }, 36 | ] 37 | }; 38 | } 39 | 40 | constructor (@Optional() @SkipSelf() parentModule: CoreModule) { 41 | if (parentModule) { 42 | throw new Error('CoreModule is already loaded. Import it in the AppModule only'); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Example angular-oauth2-oidc with AuthGuard 2 | 3 | This repository shows a basic Angular CLI application with [the `angular-oauth2-oidc` library](https://github.com/manfredsteyer/angular-oauth2-oidc) and Angular AuthGuards. 4 | 5 | ## Features 6 | 7 | This demonstrates: 8 | 9 | - Use of **the Implicit Flow** 10 | - Modules (core, shared, and two feature modules) 11 | - An auth guard that forces you to login when navigating to protected routes 12 | - An auth guard that just prevents you from navigating to protected routes 13 | - Asynchronous loading of login information (and thus async auth guards) 14 | - Using `localStorage` for storing tokens (use at your own risk!) 15 | - Loading IDS details from its discovery document 16 | - Trying silent refresh on app startup before potientially starting a login flow 17 | - OpenID's external logout features 18 | 19 | Most interesting features can be found in [the core module](./src/app/core). 20 | 21 | ## Usage 22 | 23 | This repository has been scaffolded with the Angular 5 CLI, then later upgraded to newer versions of the Angular CLI. 24 | To use the repository: 25 | 26 | 1. Clone this repository 27 | 1. Run `npm install` to get the dependencies 28 | 1. Run `ng serve --open` to get it running on [http://localhost:4200](http://localhost:4200) 29 | 30 | This connects to the IdentityServer also used in the library's example. 31 | The **credentials** are user "`max`" and password "`geheim`". 32 | 33 | You could also connect to your own IdentityServer by changing `auth-config.ts`. 34 | Note that your server must whitelist both `http://localhost:4200/index.html` and `http://localhost:4200/silent-refresh.html` for this to work. 35 | 36 | ## Example 37 | 38 | The application is supposed to look somewhat like this: 39 | 40 | ![Application Screenshot](screenshot-001.png) 41 | -------------------------------------------------------------------------------- /src/app/app-menu.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | 4 | import { AuthService } from './core/auth.service'; 5 | 6 | @Component({ 7 | selector: 'app-menu', 8 | template: ``, 33 | }) 34 | export class AppMenuComponent { 35 | isAuthenticated: Observable; 36 | 37 | constructor(private authService: AuthService) { 38 | this.isAuthenticated = authService.isAuthenticated$; 39 | } 40 | 41 | login() { this.authService.login(); } 42 | logout() { this.authService.logout(); } 43 | 44 | get email() { 45 | return this.authService.identityClaims 46 | ? this.authService.identityClaims['email'] 47 | : '-'; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Observable } from 'rxjs'; 3 | 4 | import { AuthService } from './core/auth.service'; 5 | 6 | @Component({ 7 | selector: 'app-root', 8 | template: `
9 | 10 |
11 |

Welcome

12 |

This is part of the app.component. Below is the router outlet.

13 |
14 | 15 |
Authenticating...
16 |
17 |

You can go to a url without a route to see the fallback route.

18 |
19 |

20 | 21 | 22 | 23 |

24 |

25 | 26 | 27 | 28 |

29 |
30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
IsAuthenticated{{isAuthenticated | async}}
HasValidToken{{hasValidToken}}
IsDoneLoading{{isDoneLoading | async}}
CanActivateProtectedRoutes{{canActivateProtectedRoutes | async}}
IdentityClaims{{identityClaims | json}}
AccessToken{{accessToken}}
IdToken{{idToken}}
39 |
40 |
`, 41 | }) 42 | export class AppComponent { 43 | isAuthenticated: Observable; 44 | isDoneLoading: Observable; 45 | canActivateProtectedRoutes: Observable; 46 | 47 | constructor ( 48 | private authService: AuthService, 49 | ) { 50 | this.isAuthenticated = this.authService.isAuthenticated$; 51 | this.isDoneLoading = this.authService.isDoneLoading$; 52 | this.canActivateProtectedRoutes = this.authService.canActivateProtectedRoutes$; 53 | 54 | this.authService.runInitialLoginSequence(); 55 | } 56 | 57 | login() { this.authService.login(); } 58 | logout() { this.authService.logout(); } 59 | refresh() { this.authService.refresh(); } 60 | reload() { window.location.reload(); } 61 | clearStorage() { localStorage.clear(); } 62 | 63 | logoutExternally() { 64 | window.open(this.authService.logoutUrl); 65 | } 66 | 67 | get hasValidToken() { return this.authService.hasValidToken(); } 68 | get accessToken() { return this.authService.accessToken; } 69 | get identityClaims() { return this.authService.identityClaims; } 70 | get idToken() { return this.authService.idToken; } 71 | } 72 | -------------------------------------------------------------------------------- /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/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Web Animations `@angular/platform-browser/animations` 51 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 52 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 53 | **/ 54 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 55 | 56 | /** 57 | * By default, zone.js will patch all possible macroTask and DomEvents 58 | * user can disable parts of macroTask/DomEvents patch by setting following flags 59 | */ 60 | 61 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 62 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 63 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 64 | 65 | /* 66 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 67 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 68 | */ 69 | // (window as any).__Zone_enable_cross_context_check = true; 70 | 71 | /*************************************************************************************************** 72 | * Zone JS is required by default for Angular itself. 73 | */ 74 | import 'zone.js/dist/zone'; // Included with Angular CLI. 75 | 76 | 77 | 78 | /*************************************************************************************************** 79 | * APPLICATION IMPORTS 80 | */ 81 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-shadowed-variable": true, 69 | "no-string-literal": false, 70 | "no-string-throw": true, 71 | "no-switch-case-fall-through": true, 72 | "no-trailing-whitespace": true, 73 | "no-unnecessary-initializer": true, 74 | "no-unused-expression": true, 75 | "no-unused-variable": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "ordered-imports": true, 87 | "prefer-const": true, 88 | "quotemark": [ 89 | true, 90 | "single" 91 | ], 92 | "radix": true, 93 | "semicolon": [ 94 | true, 95 | "always" 96 | ], 97 | "triple-equals": [ 98 | true, 99 | "allow-null-check" 100 | ], 101 | "typedef-whitespace": [ 102 | true, 103 | { 104 | "call-signature": "nospace", 105 | "index-signature": "nospace", 106 | "parameter": "nospace", 107 | "property-declaration": "nospace", 108 | "variable-declaration": "nospace" 109 | } 110 | ], 111 | "unified-signatures": true, 112 | "variable-name": false, 113 | "whitespace": [ 114 | true, 115 | "check-branch", 116 | "check-decl", 117 | "check-operator", 118 | "check-separator", 119 | "check-type" 120 | ], 121 | "no-output-on-prefix": true, 122 | "use-input-property-decorator": true, 123 | "use-output-property-decorator": true, 124 | "use-host-property-decorator": true, 125 | "no-input-rename": true, 126 | "no-output-rename": true, 127 | "use-life-cycle-interface": true, 128 | "use-pipe-transform-interface": true, 129 | "component-class-suffix": true, 130 | "directive-class-suffix": true 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "sample-auth-guards": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": {}, 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/sample-auth-guards", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "src/tsconfig.app.json", 21 | "assets": [ 22 | "src/favicon.ico", 23 | "src/assets", 24 | "src/silent-refresh.html" 25 | ], 26 | "styles": [ 27 | "src/styles.css" 28 | ], 29 | "scripts": [] 30 | }, 31 | "configurations": { 32 | "production": { 33 | "fileReplacements": [ 34 | { 35 | "replace": "src/environments/environment.ts", 36 | "with": "src/environments/environment.prod.ts" 37 | } 38 | ], 39 | "optimization": true, 40 | "outputHashing": "all", 41 | "sourceMap": false, 42 | "extractCss": true, 43 | "namedChunks": false, 44 | "aot": true, 45 | "extractLicenses": true, 46 | "vendorChunk": false, 47 | "buildOptimizer": true 48 | } 49 | } 50 | }, 51 | "serve": { 52 | "builder": "@angular-devkit/build-angular:dev-server", 53 | "options": { 54 | "browserTarget": "sample-auth-guards:build" 55 | }, 56 | "configurations": { 57 | "production": { 58 | "browserTarget": "sample-auth-guards:build:production" 59 | } 60 | } 61 | }, 62 | "extract-i18n": { 63 | "builder": "@angular-devkit/build-angular:extract-i18n", 64 | "options": { 65 | "browserTarget": "sample-auth-guards:build" 66 | } 67 | }, 68 | "test": { 69 | "builder": "@angular-devkit/build-angular:karma", 70 | "options": { 71 | "main": "src/test.ts", 72 | "polyfills": "src/polyfills.ts", 73 | "tsConfig": "src/tsconfig.spec.json", 74 | "karmaConfig": "src/karma.conf.js", 75 | "styles": [ 76 | "src/styles.css" 77 | ], 78 | "scripts": [], 79 | "assets": [ 80 | "src/favicon.ico", 81 | "src/assets", 82 | "src/silent-refresh.html" 83 | ] 84 | } 85 | }, 86 | "lint": { 87 | "builder": "@angular-devkit/build-angular:tslint", 88 | "options": { 89 | "tsConfig": [ 90 | "src/tsconfig.app.json", 91 | "src/tsconfig.spec.json" 92 | ], 93 | "exclude": [ 94 | "**/node_modules/**" 95 | ] 96 | } 97 | } 98 | } 99 | }, 100 | "sample-auth-guards-e2e": { 101 | "root": "e2e/", 102 | "projectType": "application", 103 | "architect": { 104 | "e2e": { 105 | "builder": "@angular-devkit/build-angular:protractor", 106 | "options": { 107 | "protractorConfig": "e2e/protractor.conf.js", 108 | "devServerTarget": "sample-auth-guards:serve" 109 | }, 110 | "configurations": { 111 | "production": { 112 | "devServerTarget": "sample-auth-guards:serve:production" 113 | } 114 | } 115 | }, 116 | "lint": { 117 | "builder": "@angular-devkit/build-angular:tslint", 118 | "options": { 119 | "tsConfig": "e2e/tsconfig.e2e.json", 120 | "exclude": [ 121 | "**/node_modules/**" 122 | ] 123 | } 124 | } 125 | } 126 | } 127 | }, 128 | "defaultProject": "sample-auth-guards" 129 | } 130 | -------------------------------------------------------------------------------- /src/app/core/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { OAuthErrorEvent, OAuthService } from 'angular-oauth2-oidc'; 4 | import { BehaviorSubject, combineLatest, Observable, ReplaySubject } from 'rxjs'; 5 | import { filter, map } from 'rxjs/operators'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class AuthService { 9 | 10 | private isAuthenticatedSubject$ = new BehaviorSubject(false); 11 | public isAuthenticated$ = this.isAuthenticatedSubject$.asObservable(); 12 | 13 | private isDoneLoadingSubject$ = new ReplaySubject(); 14 | public isDoneLoading$ = this.isDoneLoadingSubject$.asObservable(); 15 | 16 | /** 17 | * Publishes `true` if and only if (a) all the asynchronous initial 18 | * login calls have completed or errorred, and (b) the user ended up 19 | * being authenticated. 20 | * 21 | * In essence, it combines: 22 | * 23 | * - the latest known state of whether the user is authorized 24 | * - whether the ajax calls for initial log in have all been done 25 | */ 26 | public canActivateProtectedRoutes$: Observable = combineLatest( 27 | this.isAuthenticated$, 28 | this.isDoneLoading$ 29 | ).pipe(map(values => values.every(b => b))); 30 | 31 | private navigateToLoginPage() { 32 | // TODO: Remember current URL 33 | this.router.navigateByUrl('/should-login'); 34 | } 35 | 36 | constructor ( 37 | private oauthService: OAuthService, 38 | private router: Router, 39 | ) { 40 | // Useful for debugging: 41 | this.oauthService.events.subscribe(event => { 42 | if (event instanceof OAuthErrorEvent) { 43 | console.error(event); 44 | } else { 45 | console.warn(event); 46 | } 47 | }); 48 | 49 | // This is tricky, as it might cause race conditions (where access_token is set in another 50 | // tab before everything is said and done there. 51 | // TODO: Improve this setup. 52 | window.addEventListener('storage', (event) => { 53 | // The `key` is `null` if the event was caused by `.clear()` 54 | if (event.key !== 'access_token' && event.key !== null) { 55 | return; 56 | } 57 | 58 | console.warn('Noticed changes to access_token (most likely from another tab), updating isAuthenticated'); 59 | this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken()); 60 | 61 | if (!this.oauthService.hasValidAccessToken()) { 62 | this.navigateToLoginPage(); 63 | } 64 | }); 65 | 66 | this.oauthService.events 67 | .subscribe(_ => { 68 | this.isAuthenticatedSubject$.next(this.oauthService.hasValidAccessToken()); 69 | }); 70 | 71 | this.oauthService.events 72 | .pipe(filter(e => ['token_received'].includes(e.type))) 73 | .subscribe(e => this.oauthService.loadUserProfile()); 74 | 75 | this.oauthService.events 76 | .pipe(filter(e => ['session_terminated', 'session_error'].includes(e.type))) 77 | .subscribe(e => this.navigateToLoginPage()); 78 | 79 | this.oauthService.setupAutomaticSilentRefresh(); 80 | } 81 | 82 | public runInitialLoginSequence(): Promise { 83 | if (location.hash) { 84 | console.log('Encountered hash fragment, plotting as table...'); 85 | console.table(location.hash.substr(1).split('&').map(kvp => kvp.split('='))); 86 | } 87 | 88 | // 0. LOAD CONFIG: 89 | // First we have to check to see how the IdServer is 90 | // currently configured: 91 | return this.oauthService.loadDiscoveryDocument() 92 | 93 | // For demo purposes, we pretend the previous call was very slow 94 | .then(() => new Promise(resolve => setTimeout(() => resolve(), 1000))) 95 | 96 | // 1. HASH LOGIN: 97 | // Try to log in via hash fragment after redirect back 98 | // from IdServer from initImplicitFlow: 99 | .then(() => this.oauthService.tryLogin()) 100 | 101 | .then(() => { 102 | if (this.oauthService.hasValidAccessToken()) { 103 | return Promise.resolve(); 104 | } 105 | 106 | // 2. SILENT LOGIN: 107 | // Try to log in via silent refresh because the IdServer 108 | // might have a cookie to remember the user, so we can 109 | // prevent doing a redirect: 110 | return this.oauthService.silentRefresh() 111 | .then(() => Promise.resolve()) 112 | .catch(result => { 113 | // Subset of situations from https://openid.net/specs/openid-connect-core-1_0.html#AuthError 114 | // Only the ones where it's reasonably sure that sending the 115 | // user to the IdServer will help. 116 | const errorResponsesRequiringUserInteraction = [ 117 | 'interaction_required', 118 | 'login_required', 119 | 'account_selection_required', 120 | 'consent_required', 121 | ]; 122 | 123 | if (result 124 | && result.reason 125 | && errorResponsesRequiringUserInteraction.indexOf(result.reason.error) >= 0) { 126 | 127 | // 3. ASK FOR LOGIN: 128 | // At this point we know for sure that we have to ask the 129 | // user to log in, so we redirect them to the IdServer to 130 | // enter credentials. 131 | // 132 | // Enable this to ALWAYS force a user to login. 133 | // this.oauthService.initImplicitFlow(); 134 | // 135 | // Instead, we'll now do this: 136 | console.warn('User interaction is needed to log in, we will wait for the user to manually log in.'); 137 | return Promise.resolve(); 138 | } 139 | 140 | // We can't handle the truth, just pass on the problem to the 141 | // next handler. 142 | return Promise.reject(result); 143 | }); 144 | }) 145 | 146 | .then(() => { 147 | this.isDoneLoadingSubject$.next(true); 148 | 149 | // Check for the strings 'undefined' and 'null' just to be sure. Our current 150 | // login(...) should never have this, but in case someone ever calls 151 | // initImplicitFlow(undefined | null) this could happen. 152 | if (this.oauthService.state && this.oauthService.state !== 'undefined' && this.oauthService.state !== 'null') { 153 | console.log('There was state, so we are sending you to: ' + this.oauthService.state); 154 | this.router.navigateByUrl(this.oauthService.state); 155 | } 156 | }) 157 | .catch(() => this.isDoneLoadingSubject$.next(true)); 158 | } 159 | 160 | public login(targetUrl?: string) { 161 | this.oauthService.initImplicitFlow(encodeURIComponent(targetUrl || this.router.url)); 162 | } 163 | 164 | public logout() { this.oauthService.logOut(); } 165 | public refresh() { this.oauthService.silentRefresh(); } 166 | public hasValidToken() { return this.oauthService.hasValidAccessToken(); } 167 | 168 | // These normally won't be exposed from a service like this, but 169 | // for debugging it makes sense. 170 | public get accessToken() { return this.oauthService.getAccessToken(); } 171 | public get identityClaims() { return this.oauthService.getIdentityClaims(); } 172 | public get idToken() { return this.oauthService.getIdToken(); } 173 | public get logoutUrl() { return this.oauthService.logoutUrl; } 174 | } 175 | --------------------------------------------------------------------------------