diff --git a/angular.json b/angular.json index 179fe328..e8d65d7e 100644 --- a/angular.json +++ b/angular.json @@ -151,6 +151,119 @@ } } } + }, + "sample2": { + "projectType": "application", + "schematics": {}, + "root": "projects/sample2", + "sourceRoot": "projects/sample2/src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/sample2", + "index": "projects/sample2/src/index.html", + "main": "projects/sample2/src/main.ts", + "polyfills": "projects/sample2/src/polyfills.ts", + "tsConfig": "projects/sample2/tsconfig.app.json", + "aot": false, + "assets": [ + "projects/sample2/src/favicon.ico", + "projects/sample2/src/assets" + ], + "styles": [ + "projects/sample2/src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "projects/sample2/src/environments/environment.ts", + "with": "projects/sample2/src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "extractCss": true, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true, + "budgets": [ + { + "type": "initial", + "maximumWarning": "2mb", + "maximumError": "5mb" + } + ] + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "sample2:build" + }, + "configurations": { + "production": { + "browserTarget": "sample2:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "sample2:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "projects/sample2/src/test.ts", + "polyfills": "projects/sample2/src/polyfills.ts", + "tsConfig": "projects/sample2/tsconfig.spec.json", + "karmaConfig": "projects/sample2/karma.conf.js", + "assets": [ + "projects/sample2/src/favicon.ico", + "projects/sample2/src/assets" + ], + "styles": [ + "projects/sample2/src/styles.css" + ], + "scripts": [] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "projects/sample2/tsconfig.app.json", + "projects/sample2/tsconfig.spec.json", + "projects/sample2/e2e/tsconfig.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + }, + "e2e": { + "builder": "@angular-devkit/build-angular:protractor", + "options": { + "protractorConfig": "projects/sample2/e2e/protractor.conf.js", + "devServerTarget": "sample2:serve" + }, + "configurations": { + "production": { + "devServerTarget": "sample2:serve:production" + } + } + } + } } }, "schematics": { diff --git a/package-lock.json b/package-lock.json index 48ee0cec..ac659259 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4722,7 +4722,8 @@ "ansi-regex": { "version": "2.1.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -4931,12 +4932,14 @@ "minimist": { "version": "0.0.8", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "minipass": { "version": "2.3.5", "bundled": true, "dev": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -4955,6 +4958,7 @@ "version": "0.5.1", "bundled": true, "dev": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5134,7 +5138,8 @@ "safe-buffer": { "version": "5.1.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -5190,6 +5195,7 @@ "version": "3.0.1", "bundled": true, "dev": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5233,12 +5239,14 @@ "wrappy": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "yallist": { "version": "3.0.3", "bundled": true, - "dev": true + "dev": true, + "optional": true } } }, diff --git a/projects/lib/package.json b/projects/lib/package.json index 0109bb13..6fb3890c 100644 --- a/projects/lib/package.json +++ b/projects/lib/package.json @@ -1,11 +1,11 @@ { - "name": "angular-oauth2-oidc", + "name": "nms-angular-oauth2-oidc", "license": "MIT", "author": { - "name": "Manfred Steyer" + "name": "Meysam Gheysaryan" }, - "version": "8.0.1", - "repository": "manfredsteyer/angular-oauth2-oidc", + "version": "1.1.0", + "repository": "meysam7289/angular-oauth2-oidc", "dependencies": { "jsrsasign": "^8.0.12" }, diff --git a/projects/lib/src/default.datetime.provider.ts b/projects/lib/src/default.datetime.provider.ts new file mode 100644 index 00000000..ae9f04f8 --- /dev/null +++ b/projects/lib/src/default.datetime.provider.ts @@ -0,0 +1,11 @@ +import { DatetimeProvider } from './types'; + +export class DefaultDatetimeProvider extends DatetimeProvider { + get myDate(): Date { + return new Date(); + }; + get myNow(): number { + return Date.now(); + }; + +} \ No newline at end of file diff --git a/projects/lib/src/angular-oauth-oidic.module.ts b/projects/lib/src/nms-angular-oauth-oidic.module.ts similarity index 89% rename from projects/lib/src/angular-oauth-oidic.module.ts rename to projects/lib/src/nms-angular-oauth-oidic.module.ts index e4e9d1de..66b5b0ba 100644 --- a/projects/lib/src/angular-oauth-oidic.module.ts +++ b/projects/lib/src/nms-angular-oauth-oidic.module.ts @@ -1,4 +1,4 @@ -import { OAuthStorage, OAuthLogger } from './types'; +import { OAuthStorage, OAuthLogger, DatetimeProvider } from './types'; import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; @@ -17,6 +17,7 @@ import { NullValidationHandler } from './token-validation/null-validation-handle import { createDefaultLogger, createDefaultStorage } from './factories'; import { CryptoHandler } from './token-validation/crypto-handler'; import { JwksValidationHandler } from './token-validation/jwks-validation-handler'; +import { DefaultDatetimeProvider } from './default.datetime.provider'; @NgModule({ imports: [CommonModule], @@ -35,8 +36,9 @@ export class OAuthModule { UrlHelperService, { provide: OAuthLogger, useFactory: createDefaultLogger }, { provide: OAuthStorage, useFactory: createDefaultStorage }, - { provide: ValidationHandler, useClass: validationHandlerClass}, + { provide: ValidationHandler, useClass: validationHandlerClass }, { provide: CryptoHandler, useClass: JwksValidationHandler }, + { provide: DatetimeProvider, useClass: DefaultDatetimeProvider }, { provide: OAuthResourceServerErrorHandler, useClass: OAuthNoopResourceServerErrorHandler diff --git a/projects/lib/src/oauth-service.ts b/projects/lib/src/oauth-service.ts index 2b9de9dc..4eade846 100644 --- a/projects/lib/src/oauth-service.ts +++ b/projects/lib/src/oauth-service.ts @@ -27,6 +27,7 @@ import { b64DecodeUnicode, base64UrlEncode } from './base64-helper'; import { AuthConfig } from './auth.config'; import { WebHttpUrlEncodingCodec } from './encoder'; import { CryptoHandler } from './token-validation/crypto-handler'; +import { DatetimeProvider } from './types'; /** * Service for logging in and logging out with @@ -80,6 +81,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { protected sessionCheckTimer: any; protected silentRefreshSubject: string; protected inImplicitFlow = false; + private callRefreshTokenSeconds = 0; constructor( protected ngZone: NgZone, @@ -90,6 +92,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { protected urlHelper: UrlHelperService, protected logger: OAuthLogger, @Optional() protected crypto: CryptoHandler, + private datetimeProvider: DatetimeProvider ) { super(); @@ -171,27 +174,33 @@ export class OAuthService extends AuthConfig implements OnDestroy { * @param listenTo Setup automatic refresh of a specific token type */ public setupAutomaticSilentRefresh(params: object = {}, listenTo?: 'access_token' | 'id_token' | 'any', noPrompt = true) { - let shouldRunSilentRefresh = true; - this.events.pipe( - tap((e) => { - if (e.type === 'token_received') { - shouldRunSilentRefresh = true; - } else if (e.type === 'logout') { - shouldRunSilentRefresh = false; - } - }), - filter(e => e.type === 'token_expires') - ).subscribe(e => { - const event = e as OAuthInfoEvent; - if ((listenTo == null || listenTo === 'any' || event.info === listenTo) && shouldRunSilentRefresh) { - // this.silentRefresh(params, noPrompt).catch(_ => { - this.refreshInternal(params, noPrompt).catch(_ => { - this.debug('Automatic silent refresh did not work'); - }); - } - }); - - this.restartRefreshTimerIfStillLoggedIn(); + let shouldRunSilentRefresh = true; + this.events.pipe( + tap((e) => { + if (e.type === 'token_received') { + shouldRunSilentRefresh = true; + } else if (e.type === 'logout') { + shouldRunSilentRefresh = false; + } + }), + filter(e => e.type === 'token_expires') + ).subscribe(e => { + const event = e as OAuthInfoEvent; + if(event.type==='token_expires' && event.info==='access_token'){ + var currentSeconds = new Date().getTime() / 1000; + if(currentSeconds-this.callRefreshTokenSeconds<2) + return; + this.callRefreshTokenSeconds = currentSeconds; + } + if ((listenTo == null || listenTo === 'any' || event.info === listenTo) && shouldRunSilentRefresh) { + // this.silentRefresh(params, noPrompt).catch(_ => { + this.refreshInternal(params, noPrompt).catch(_ => { + this.debug('Automatic silent refresh did not work'); + }); + } + }); + + this.restartRefreshTimerIfStillLoggedIn(); } protected refreshInternal(params, noPrompt) { @@ -329,7 +338,6 @@ export class OAuthService extends AuthConfig implements OnDestroy { const expiration = this.getAccessTokenExpiration(); const storedAt = this.getAccessTokenStoredAt(); const timeout = this.calcTimeout(storedAt, expiration); - this.ngZone.runOutsideAngular(() => { this.accessTokenTimeoutSubscription = of( new OAuthInfoEvent('token_expires', 'access_token') @@ -374,7 +382,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { } protected calcTimeout(storedAt: number, expiration: number): number { - const now = Date.now(); + const now = this.datetimeProvider.myNow; const delta = (expiration - storedAt) * this.timeoutFactor - (now - storedAt); return Math.max(0, delta); } @@ -1264,7 +1272,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { } return url; - + } initImplicitFlowInternal( @@ -1328,7 +1336,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { * @description This method allows resetting the current implict flow in order to be initialized again. */ public resetImplicitFlow(): void { - this.inImplicitFlow = false; + this.inImplicitFlow = false; } protected callOnTokenReceivedIfExists(options: LoginOptions): void { @@ -1354,10 +1362,10 @@ export class OAuthService extends AuthConfig implements OnDestroy { if (grantedScopes) { this._storage.setItem('granted_scopes', JSON.stringify(grantedScopes.split('+'))); } - this._storage.setItem('access_token_stored_at', '' + Date.now()); + this._storage.setItem('access_token_stored_at', '' + this.datetimeProvider.myNow); if (expiresIn) { const expiresInMilliSeconds = expiresIn * 1000; - const now = new Date(); + const now = this.datetimeProvider.myDate; const expiresAt = now.getTime() + expiresInMilliSeconds; this._storage.setItem('expires_at', '' + expiresAt); } @@ -1403,10 +1411,10 @@ export class OAuthService extends AuthConfig implements OnDestroy { const state = parts['state']; const href = location.href - .replace(/[&\?]code=[^&\$]*/, '') - .replace(/[&\?]scope=[^&\$]*/, '') - .replace(/[&\?]state=[^&\$]*/, '') - .replace(/[&\?]session_state=[^&\$]*/, ''); + .replace(/[&\?]code=[^&\$]*/, '') + .replace(/[&\?]scope=[^&\$]*/, '') + .replace(/[&\?]state=[^&\$]*/, '') + .replace(/[&\?]session_state=[^&\$]*/, ''); history.replaceState(null, window.name, href); @@ -1470,7 +1478,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { private fetchAndProcessToken(params: HttpParams): Promise { let headers = new HttpHeaders() - .set('Content-Type', 'application/x-www-form-urlencoded'); + .set('Content-Type', 'application/x-www-form-urlencoded'); if (!this.validateUrlForHttps(this.tokenEndpoint)) { throw new Error('tokenEndpoint must use Http. Also check property requireHttps.'); @@ -1503,32 +1511,32 @@ export class OAuthService extends AuthConfig implements OnDestroy { (tokenResponse) => { this.debug('refresh tokenResponse', tokenResponse); this.storeAccessTokenResponse( - tokenResponse.access_token, - tokenResponse.refresh_token, + tokenResponse.access_token, + tokenResponse.refresh_token, tokenResponse.expires_in, tokenResponse.scope); if (this.oidc && tokenResponse.id_token) { - this.processIdToken(tokenResponse.id_token, tokenResponse.access_token). - then(result => { - this.storeIdToken(result); - - this.eventsSubject.next(new OAuthSuccessEvent('token_received')); - this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed')); - - resolve(tokenResponse); - }) - .catch(reason => { - this.eventsSubject.next(new OAuthErrorEvent('token_validation_error', reason)); - console.error('Error validating tokens'); - console.error(reason); - - reject(reason); - }); + this.processIdToken(tokenResponse.id_token, tokenResponse.access_token). + then(result => { + this.storeIdToken(result); + + this.eventsSubject.next(new OAuthSuccessEvent('token_received')); + this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed')); + + resolve(tokenResponse); + }) + .catch(reason => { + this.eventsSubject.next(new OAuthErrorEvent('token_validation_error', reason)); + console.error('Error validating tokens'); + console.error(reason); + + reject(reason); + }); } else { this.eventsSubject.next(new OAuthSuccessEvent('token_received')); this.eventsSubject.next(new OAuthSuccessEvent('token_refreshed')); - + resolve(tokenResponse); } }, @@ -1688,7 +1696,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { ): boolean { const savedNonce = this._storage.getItem('nonce'); if (savedNonce !== nonceInState) { - + const err = 'Validating access_token failed, wrong state/nonce.'; console.error(err, savedNonce, nonceInState); return false; @@ -1700,7 +1708,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { this._storage.setItem('id_token', idToken.idToken); this._storage.setItem('id_token_claims_obj', idToken.idTokenClaimsJson); this._storage.setItem('id_token_expires_at', '' + idToken.idTokenExpiresAt); - this._storage.setItem('id_token_stored_at', '' + Date.now()); + this._storage.setItem('id_token_stored_at', '' + this.datetimeProvider.myNow); } protected storeSessionState(sessionState: string): void { @@ -1835,30 +1843,30 @@ export class OAuthService extends AuthConfig implements OnDestroy { return this.checkAtHash(validationParams) - .then(atHashValid => { - if ( - !this.disableAtHashCheck && - this.requestAccessToken && - !atHashValid - ) { - const err = 'Wrong at_hash'; - this.logger.warn(err); - return Promise.reject(err); - } - - return this.checkSignature(validationParams).then(_ => { - const result: ParsedIdToken = { - idToken: idToken, - idTokenClaims: claims, - idTokenClaimsJson: claimsJson, - idTokenHeader: header, - idTokenHeaderJson: headerJson, - idTokenExpiresAt: expiresAtMSec - }; - return result; - }); + .then(atHashValid => { + if ( + !this.disableAtHashCheck && + this.requestAccessToken && + !atHashValid + ) { + const err = 'Wrong at_hash'; + this.logger.warn(err); + return Promise.reject(err); + } - }); + return this.checkSignature(validationParams).then(_ => { + const result: ParsedIdToken = { + idToken: idToken, + idTokenClaims: claims, + idTokenClaimsJson: claimsJson, + idTokenHeader: header, + idTokenHeaderJson: headerJson, + idTokenExpiresAt: expiresAtMSec + }; + return result; + }); + + }); } /** @@ -1951,7 +1959,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { public hasValidAccessToken(): boolean { if (this.getAccessToken()) { const expiresAt = this._storage.getItem('expires_at'); - const now = new Date(); + const now = this.datetimeProvider.myDate; if (expiresAt && parseInt(expiresAt, 10) < now.getTime()) { return false; } @@ -1968,7 +1976,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { public hasValidIdToken(): boolean { if (this.getIdToken()) { const expiresAt = this._storage.getItem('id_token_expires_at'); - const now = new Date(); + const now = this.datetimeProvider.myDate; if (expiresAt && parseInt(expiresAt, 10) < now.getTime()) { return false; } @@ -2155,7 +2163,7 @@ export class OAuthService extends AuthConfig implements OnDestroy { this.initCodeFlowInternal(additionalState, params); } else { this.events.pipe(filter(e => e.type === 'discovery_document_loaded')) - .subscribe(_ => this.initCodeFlowInternal(additionalState, params)); + .subscribe(_ => this.initCodeFlowInternal(additionalState, params)); } } @@ -2171,10 +2179,10 @@ export class OAuthService extends AuthConfig implements OnDestroy { this.createLoginUrl(additionalState, '', null, false, params).then(function (url) { location.href = url; }) - .catch(error => { - console.error('Error in initAuthorizationCodeFlow'); - console.error(error); - }); + .catch(error => { + console.error('Error in initAuthorizationCodeFlow'); + console.error(error); + }); } protected async createChallangeVerifierPairForPKCE(): Promise<[string, string]> { diff --git a/projects/lib/src/public_api.ts b/projects/lib/src/public_api.ts index d72ae34f..8d86c72c 100644 --- a/projects/lib/src/public_api.ts +++ b/projects/lib/src/public_api.ts @@ -1,4 +1,4 @@ -export * from './angular-oauth-oidic.module'; +export * from './nms-angular-oauth-oidic.module'; export * from './oauth-service'; export * from './token-validation/jwks-validation-handler'; export * from './token-validation/null-validation-handler'; diff --git a/projects/lib/src/types.ts b/projects/lib/src/types.ts index 802bd649..3dc38a15 100644 --- a/projects/lib/src/types.ts +++ b/projects/lib/src/types.ts @@ -47,7 +47,7 @@ export class LoginOptions { * the lib read the token(s) so that they are not displayed * anymore in the url. If not, set this to true. */ - preventClearHashAfterLogin? = false; + preventClearHashAfterLogin?= false; } /** @@ -76,6 +76,11 @@ export abstract class OAuthStorage { abstract setItem(key: string, data: string): void; } +export abstract class DatetimeProvider { + abstract get myDate(): Date | null; + abstract get myNow(): number | null; +} + /** * Represents the received tokens, the received state * and the parsed claims from the id-token. @@ -105,7 +110,7 @@ export interface ParsedIdToken { */ export interface TokenResponse { access_token: string; - id_token: string; + id_token: string; token_type: string; expires_in: number; refresh_token: string; diff --git a/projects/sample2/browserslist b/projects/sample2/browserslist new file mode 100644 index 00000000..80848532 --- /dev/null +++ b/projects/sample2/browserslist @@ -0,0 +1,12 @@ +# This file is used by the build system to adjust CSS and JS output to support the specified browsers below. +# For additional information regarding the format and rule options, please see: +# https://github.com/browserslist/browserslist#queries + +# You can see what browsers were selected by your queries by running: +# npx browserslist + +> 0.5% +last 2 versions +Firefox ESR +not dead +not IE 9-11 # For IE 9-11 support, remove 'not'. \ No newline at end of file diff --git a/projects/sample2/e2e/protractor.conf.js b/projects/sample2/e2e/protractor.conf.js new file mode 100644 index 00000000..73e4e680 --- /dev/null +++ b/projects/sample2/e2e/protractor.conf.js @@ -0,0 +1,32 @@ +// @ts-check +// Protractor configuration file, see link for more information +// https://github.com/angular/protractor/blob/master/lib/config.ts + +const { SpecReporter } = require('jasmine-spec-reporter'); + +/** + * @type { import("protractor").Config } + */ +exports.config = { + allScriptsTimeout: 11000, + specs: [ + './src/**/*.e2e-spec.ts' + ], + capabilities: { + 'browserName': 'chrome' + }, + directConnect: true, + baseUrl: 'http://localhost:4200/', + framework: 'jasmine', + jasmineNodeOpts: { + showColors: true, + defaultTimeoutInterval: 30000, + print: function() {} + }, + onPrepare() { + require('ts-node').register({ + project: require('path').join(__dirname, './tsconfig.json') + }); + jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); + } +}; \ No newline at end of file diff --git a/projects/sample2/e2e/src/app.e2e-spec.ts b/projects/sample2/e2e/src/app.e2e-spec.ts new file mode 100644 index 00000000..1aad6b76 --- /dev/null +++ b/projects/sample2/e2e/src/app.e2e-spec.ts @@ -0,0 +1,23 @@ +import { AppPage } from './app.po'; +import { browser, logging } from 'protractor'; + +describe('workspace-project App', () => { + let page: AppPage; + + beforeEach(() => { + page = new AppPage(); + }); + + it('should display welcome message', () => { + page.navigateTo(); + expect(page.getTitleText()).toEqual('Welcome to sample2!'); + }); + + afterEach(async () => { + // Assert that there are no errors emitted from the browser + const logs = await browser.manage().logs().get(logging.Type.BROWSER); + expect(logs).not.toContain(jasmine.objectContaining({ + level: logging.Level.SEVERE, + } as logging.Entry)); + }); +}); diff --git a/projects/sample2/e2e/src/app.po.ts b/projects/sample2/e2e/src/app.po.ts new file mode 100644 index 00000000..5776aa9e --- /dev/null +++ b/projects/sample2/e2e/src/app.po.ts @@ -0,0 +1,11 @@ +import { browser, by, element } from 'protractor'; + +export class AppPage { + navigateTo() { + return browser.get(browser.baseUrl) as Promise; + } + + getTitleText() { + return element(by.css('app-root h1')).getText() as Promise; + } +} diff --git a/projects/sample2/e2e/tsconfig.json b/projects/sample2/e2e/tsconfig.json new file mode 100644 index 00000000..bc240fbf --- /dev/null +++ b/projects/sample2/e2e/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "../../../out-tsc/e2e", + "module": "commonjs", + "target": "es5", + "types": [ + "jasmine", + "jasminewd2", + "node" + ] + } +} diff --git a/projects/sample2/src/app/app-routing.module.ts b/projects/sample2/src/app/app-routing.module.ts new file mode 100644 index 00000000..d425c6f5 --- /dev/null +++ b/projects/sample2/src/app/app-routing.module.ts @@ -0,0 +1,10 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; + +const routes: Routes = []; + +@NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] +}) +export class AppRoutingModule { } diff --git a/projects/sample2/src/app/app.component.css b/projects/sample2/src/app/app.component.css new file mode 100644 index 00000000..e69de29b diff --git a/projects/sample2/src/app/app.component.spec.ts b/projects/sample2/src/app/app.component.spec.ts new file mode 100644 index 00000000..6ef2f89d --- /dev/null +++ b/projects/sample2/src/app/app.component.spec.ts @@ -0,0 +1,35 @@ +import { TestBed, async } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; +import { AppComponent } from './app.component'; + +describe('AppComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + RouterTestingModule + ], + declarations: [ + AppComponent + ], + }).compileComponents(); + })); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app).toBeTruthy(); + }); + + it(`should have as title 'sample2'`, () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.debugElement.componentInstance; + expect(app.title).toEqual('sample2'); + }); + + it('should render title in a h1 tag', () => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.debugElement.nativeElement; + expect(compiled.querySelector('h1').textContent).toContain('Welcome to sample2!'); + }); +}); diff --git a/projects/sample2/src/app/app.component.ts b/projects/sample2/src/app/app.component.ts new file mode 100644 index 00000000..2f8b35a8 --- /dev/null +++ b/projects/sample2/src/app/app.component.ts @@ -0,0 +1,47 @@ +import { Component, OnInit } from '@angular/core'; +import { OAuthService, JwksValidationHandler, OAuthErrorEvent } from 'angular-oauth2-oidc'; +import { AuthConfigFactory } from './oidc/auth.config'; +import { filter } from 'rxjs/operators'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'] +}) +export class AppComponent implements OnInit { + title = 'sample2'; + + /** + * + */ + constructor(private oauthService: OAuthService) { + + } + ngOnInit() { + this.configureOAuth(); + this.runTryLogin(); + } + + private configureOAuth() { + this.oauthService.configure(AuthConfigFactory('https://nmsidp.com:44301', 'rahavard_angular')); + this.oauthService.tokenValidationHandler = new JwksValidationHandler(); + this.oauthService.events.pipe(filter((x: any) => x.type === 'token_refresh_error')) + .subscribe((x: OAuthErrorEvent) => { + this.oauthService.initCodeFlow(); + }) + } + + private runTryLogin() { + this.oauthService.loadDiscoveryDocumentAndTryLogin().then(data => { + if (this.oauthService.getRefreshToken()) { + this.oauthService.setupAutomaticSilentRefresh(); + } + }).then(data => { + if (!this.oauthService.getRefreshToken()) { + this.oauthService.initCodeFlow(); + } else if (!this.oauthService.hasValidAccessToken() || !this.oauthService.hasValidIdToken()) { + this.oauthService.refreshToken(); + } + }); + } +} diff --git a/projects/sample2/src/app/oidc/auth.config.ts b/projects/sample2/src/app/oidc/auth.config.ts new file mode 100644 index 00000000..a9f176a9 --- /dev/null +++ b/projects/sample2/src/app/oidc/auth.config.ts @@ -0,0 +1,37 @@ +import { AuthConfig } from 'angular-oauth2-oidc'; + + +export function AuthConfigFactory(idp_url: string, clientId: string): AuthConfig { + return { + // Url of the Identity Provider + issuer: idp_url, + + // URL of the SPA to redirect the user to after login + redirectUri: window.location.origin, + + // The SPA's id. The SPA is registerd with this id at the auth-server + // clientId: 'server.code', + + + clientId: clientId, + + // Just needed if your auth server demands a secret. In general, this + // is a sign that the auth server is not configured with SPAs in mind + // and it might not enforce further best practices vital for security + // such applications. + // dummyClientSecret: 'secret', + + responseType: 'code', + + // set the scope for the permissions the client should request + // The first four are defined by OIDC. + // Important: Request offline_access to get a refresh token + // The api scope is a usecase specific one + scope: 'openid profile offline_access role coreAPI rahavardAPI', + + showDebugInformation: true, + + // Not recommented: + // disablePKCI: true, + } +}; diff --git a/projects/sample2/src/app/oidc/route.guard.ts b/projects/sample2/src/app/oidc/route.guard.ts new file mode 100644 index 00000000..c3adf35e --- /dev/null +++ b/projects/sample2/src/app/oidc/route.guard.ts @@ -0,0 +1,26 @@ +import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; +import { OAuthService } from 'angular-oauth2-oidc'; +import { Injectable } from '@angular/core'; + +@Injectable() +export class RouteGuard implements CanActivate { + + constructor( + private oauthService: OAuthService + ) { } + + canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { + if (this.oauthService.getRefreshToken()) { + if (this.oauthService.hasValidAccessToken() && this.oauthService.hasValidIdToken()) { + return true; + } else { + this.oauthService.refreshToken(); + return false; + } + } else { + this.oauthService.initCodeFlow(); + return false; + } + } + +} diff --git a/projects/sample2/src/assets/.gitkeep b/projects/sample2/src/assets/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/projects/sample2/src/environments/environment.prod.ts b/projects/sample2/src/environments/environment.prod.ts new file mode 100644 index 00000000..3612073b --- /dev/null +++ b/projects/sample2/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true +}; diff --git a/projects/sample2/src/favicon.ico b/projects/sample2/src/favicon.ico new file mode 100644 index 00000000..8081c7ce Binary files /dev/null and b/projects/sample2/src/favicon.ico differ diff --git a/projects/sample2/src/index.html b/projects/sample2/src/index.html new file mode 100644 index 00000000..ca916e9f --- /dev/null +++ b/projects/sample2/src/index.html @@ -0,0 +1,14 @@ + + + + + Sample2 + + + + + + + + + diff --git a/projects/sample2/src/main.ts b/projects/sample2/src/main.ts new file mode 100644 index 00000000..c7b673cf --- /dev/null +++ b/projects/sample2/src/main.ts @@ -0,0 +1,12 @@ +import { enableProdMode } from '@angular/core'; +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +platformBrowserDynamic().bootstrapModule(AppModule) + .catch(err => console.error(err)); diff --git a/projects/sample2/src/polyfills.ts b/projects/sample2/src/polyfills.ts new file mode 100644 index 00000000..aa665d6b --- /dev/null +++ b/projects/sample2/src/polyfills.ts @@ -0,0 +1,63 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/guide/browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + */ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags.ts'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/projects/sample2/src/styles.css b/projects/sample2/src/styles.css new file mode 100644 index 00000000..90d4ee00 --- /dev/null +++ b/projects/sample2/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/projects/sample2/src/test.ts b/projects/sample2/src/test.ts new file mode 100644 index 00000000..16317897 --- /dev/null +++ b/projects/sample2/src/test.ts @@ -0,0 +1,20 @@ +// This file is required by karma.conf.js and loads recursively all the .spec and framework files + +import 'zone.js/dist/zone-testing'; +import { getTestBed } from '@angular/core/testing'; +import { + BrowserDynamicTestingModule, + platformBrowserDynamicTesting +} from '@angular/platform-browser-dynamic/testing'; + +declare const require: any; + +// First, initialize the Angular testing environment. +getTestBed().initTestEnvironment( + BrowserDynamicTestingModule, + platformBrowserDynamicTesting() +); +// Then we find all the tests. +const context = require.context('./', true, /\.spec\.ts$/); +// And load the modules. +context.keys().map(context); diff --git a/projects/sample2/tsconfig.app.json b/projects/sample2/tsconfig.app.json new file mode 100644 index 00000000..57fc3cbc --- /dev/null +++ b/projects/sample2/tsconfig.app.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "../../out-tsc/app", + "types": [] + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "src/test.ts", + "src/**/*.spec.ts" + ] +} diff --git a/projects/sample2/tsconfig.spec.json b/projects/sample2/tsconfig.spec.json new file mode 100644 index 00000000..a8ce1d39 --- /dev/null +++ b/projects/sample2/tsconfig.spec.json @@ -0,0 +1,18 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": [ + "jasmine", + "node" + ] + }, + "files": [ + "src/test.ts", + "src/polyfills.ts" + ], + "include": [ + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/projects/sample2/tslint.json b/projects/sample2/tslint.json new file mode 100644 index 00000000..19e8161a --- /dev/null +++ b/projects/sample2/tslint.json @@ -0,0 +1,17 @@ +{ + "extends": "../../tslint.json", + "rules": { + "directive-selector": [ + true, + "attribute", + "app", + "camelCase" + ], + "component-selector": [ + true, + "element", + "app", + "kebab-case" + ] + } +}