Skip to content

Commit 2d38a48

Browse files
Merge pull request #151 from fmalcher/httpclient
Update to new HttpClient
2 parents 0bf1686 + 56daeb5 commit 2d38a48

File tree

7 files changed

+115
-57
lines changed

7 files changed

+115
-57
lines changed

angular-oauth2-oidc/gulpfile.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ gulp.task('rollup:fesm', function () {
7272

7373
// Bundle's entry point
7474
// See https://github.com/rollup/rollup/wiki/JavaScript-API#entry
75-
entry: `${buildFolder}/index.js`,
75+
input: `${buildFolder}/index.js`,
7676

7777
// Allow mixing of hypothetical and actual files. "Actual" files can be files
7878
// accessed by Rollup or produced by plugins further down the chain.
@@ -105,7 +105,7 @@ gulp.task('rollup:umd', function () {
105105

106106
// Bundle's entry point
107107
// See https://github.com/rollup/rollup/wiki/JavaScript-API#entry
108-
entry: `${buildFolder}/index.js`,
108+
input: `${buildFolder}/index.js`,
109109

110110
// Allow mixing of hypothetical and actual files. "Actual" files can be files
111111
// accessed by Rollup or produced by plugins further down the chain.
@@ -131,7 +131,7 @@ gulp.task('rollup:umd', function () {
131131
// The name to use for the module for UMD/IIFE bundles
132132
// (required for bundles with exports)
133133
// See https://github.com/rollup/rollup/wiki/JavaScript-API#modulename
134-
moduleName: 'angular-oauth2-oidc',
134+
name: 'angular-oauth2-oidc',
135135

136136
// See https://github.com/rollup/rollup/wiki/JavaScript-API#globals
137137
globals: {

angular-oauth2-oidc/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
"del": "^2.2.2",
4343
"gulp": "^3.9.1",
4444
"gulp-rename": "^1.2.2",
45-
"gulp-rollup": "^2.11.0",
45+
"gulp-rollup": "^2.15.0",
4646
"jasmine-core": "~2.5.2",
4747
"jasmine-spec-reporter": "~3.2.0",
4848
"karma": "~1.4.1",
@@ -55,7 +55,7 @@
5555
"node-sass-tilde-importer": "^1.0.0",
5656
"node-watch": "^0.5.2",
5757
"protractor": "~5.1.0",
58-
"rollup": "^0.41.6",
58+
"rollup": "^0.50.0",
5959
"run-sequence": "^1.2.2",
6060
"rxjs": "^5.1.0",
6161
"ts-node": "~2.0.0",

angular-oauth2-oidc/src/index.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { NgModule, ModuleWithProviders } from '@angular/core';
22
import { CommonModule } from '@angular/common';
3+
import { HttpClientModule } from '@angular/common/http';
4+
35
import { OAuthService } from './oauth-service';
46
import { UrlHelperService } from './url-helper.service';
57

@@ -26,7 +28,7 @@ export * from './tokens';
2628
@NgModule({
2729
imports: [
2830
CommonModule,
29-
//HttpModule
31+
HttpClientModule
3032
],
3133
declarations: [
3234
],

angular-oauth2-oidc/src/oauth-service.ts

+44-46
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
import { Http, URLSearchParams, Headers } from '@angular/http';
21
import { Injectable, Optional } from '@angular/core';
2+
import { HttpClient, HttpHeaders } from '@angular/common/http';
33
import { Observable } from 'rxjs/Observable';
44
import { Subject } from 'rxjs/Subject';
5+
import { Subscription } from 'rxjs/Subscription';
6+
57
import { ValidationHandler, ValidationParams } from './token-validation/validation-handler';
68
import { UrlHelperService } from './url-helper.service';
7-
import { Subscription } from 'rxjs/Subscription';
89
import { OAuthEvent, OAuthInfoEvent, OAuthErrorEvent, OAuthSuccessEvent } from './events';
9-
import { OAuthStorage, LoginOptions, ParsedIdToken } from './types';
10+
import { OAuthStorage, LoginOptions, ParsedIdToken, OidcDiscoveryDoc, TokenResponse, UserInfo } from './types';
1011
import { b64DecodeUnicode } from './base64-helper';
1112
import { AuthConfig } from './auth.config';
1213

@@ -65,7 +66,7 @@ export class OAuthService
6566
private silentRefreshSubject: string;
6667

6768
constructor(
68-
private http: Http,
69+
private http: HttpClient,
6970
@Optional() storage: OAuthStorage,
7071
@Optional() tokenValidationHandler: ValidationHandler,
7172
@Optional() private config: AuthConfig,
@@ -92,7 +93,6 @@ export class OAuthService
9293

9394
this.setupRefreshTimer();
9495

95-
9696
}
9797

9898
/**
@@ -140,14 +140,13 @@ export class OAuthService
140140
* @param params Additional parameter to pass
141141
*/
142142
public setupAutomaticSilentRefresh(params: object = {}) {
143-
this
144-
.events
145-
.filter(e => e.type === 'token_expires')
146-
.subscribe(e => {
147-
this.silentRefresh(params).catch(_ => {
148-
this.debug('automatic silent refresh did not work');
149-
})
150-
});
143+
this.events
144+
.filter(e => e.type === 'token_expires')
145+
.subscribe(e => {
146+
this.silentRefresh(params).catch(_ => {
147+
this.debug('automatic silent refresh did not work');
148+
});
149+
});
151150

152151
this.restartRefreshTimerIfStillLoggedIn();
153152
}
@@ -306,7 +305,7 @@ export class OAuthService
306305
fullUrl = this.issuer || '';
307306
if (!fullUrl.endsWith('/')) {
308307
fullUrl += '/';
309-
}
308+
}
310309
fullUrl += '.well-known/openid-configuration';
311310
}
312311

@@ -315,7 +314,7 @@ export class OAuthService
315314
return;
316315
}
317316

318-
this.http.get(fullUrl).map(r => r.json()).subscribe(
317+
this.http.get<OidcDiscoveryDoc>(fullUrl).subscribe(
319318
(doc) => {
320319

321320
if (!this.validateDiscoveryDocument(doc)) {
@@ -368,7 +367,7 @@ export class OAuthService
368367
private loadJwks(): Promise<object> {
369368
return new Promise<object>((resolve, reject) => {
370369
if (this.jwksUri) {
371-
this.http.get(this.jwksUri).map(r => r.json()).subscribe(
370+
this.http.get(this.jwksUri).subscribe(
372371
jwks => {
373372
this.jwks = jwks;
374373
this.eventsSubject.next(new OAuthSuccessEvent('discovery_document_loaded'));
@@ -388,55 +387,55 @@ export class OAuthService
388387

389388
}
390389

391-
private validateDiscoveryDocument(doc: object): boolean {
390+
private validateDiscoveryDocument(doc: OidcDiscoveryDoc): boolean {
392391

393392
let errors: string[];
394393

395-
if (doc['issuer'] !== this.issuer) {
394+
if (doc.issuer !== this.issuer) {
396395
console.error(
397396
'invalid issuer in discovery document',
398397
'expected: ' + this.issuer,
399-
'current: ' + doc['issuer']
398+
'current: ' + doc.issuer
400399
);
401400
return false;
402401
}
403402

404-
errors = this.validateUrlFromDiscoveryDocument(doc['authorization_endpoint']);
403+
errors = this.validateUrlFromDiscoveryDocument(doc.authorization_endpoint);
405404
if (errors.length > 0) {
406405
console.error('error validating authorization_endpoint in discovery document', errors);
407406
return false;
408407
}
409408

410-
errors = this.validateUrlFromDiscoveryDocument(doc['end_session_endpoint']);
409+
errors = this.validateUrlFromDiscoveryDocument(doc.end_session_endpoint);
411410
if (errors.length > 0) {
412411
console.error('error validating end_session_endpoint in discovery document', errors);
413412
return false;
414413
}
415414

416-
errors = this.validateUrlFromDiscoveryDocument(doc['token_endpoint']);
415+
errors = this.validateUrlFromDiscoveryDocument(doc.token_endpoint);
417416
if (errors.length > 0) {
418417
console.error('error validating token_endpoint in discovery document', errors);
419418
}
420419

421-
errors = this.validateUrlFromDiscoveryDocument(doc['userinfo_endpoint']);
420+
errors = this.validateUrlFromDiscoveryDocument(doc.userinfo_endpoint);
422421
if (errors.length > 0) {
423422
console.error('error validating userinfo_endpoint in discovery document', errors);
424423
return false;
425424
}
426425

427-
errors = this.validateUrlFromDiscoveryDocument(doc['jwks_uri']);
426+
errors = this.validateUrlFromDiscoveryDocument(doc.jwks_uri);
428427
if (errors.length > 0) {
429428
console.error('error validating jwks_uri in discovery document', errors);
430429
return false;
431430
}
432431

433-
if (this.sessionChecksEnabled && !doc['check_session_iframe']) {
432+
if (this.sessionChecksEnabled && !doc.check_session_iframe) {
434433
console.warn(
435434
'sessionChecksEnabled is activated but discovery document'
436435
+ ' does not contain a check_session_iframe field');
437436
}
438437

439-
this.sessionChecksEnabled = doc['check_session_iframe'];
438+
this.sessionChecksEnabled = !!doc.check_session_iframe;
440439

441440
return true;
442441
}
@@ -458,7 +457,7 @@ export class OAuthService
458457
public fetchTokenUsingPasswordFlowAndLoadUserProfile(
459458
userName: string,
460459
password: string,
461-
headers: Headers = new Headers()): Promise<object> {
460+
headers: HttpHeaders = new HttpHeaders()): Promise<object> {
462461
return this
463462
.fetchTokenUsingPasswordFlow(userName, password, headers)
464463
.then(() => this.loadUserProfile());
@@ -481,17 +480,17 @@ export class OAuthService
481480

482481
return new Promise((resolve, reject) => {
483482

484-
let headers = new Headers();
485-
headers.set('Authorization', 'Bearer ' + this.getAccessToken());
483+
const headers = new HttpHeaders()
484+
.set('Authorization', 'Bearer ' + this.getAccessToken());
486485

487-
this.http.get(this.userinfoEndpoint, { headers }).map(r => r.json()).subscribe(
488-
(doc) => {
489-
this.debug('userinfo received', doc);
486+
this.http.get<UserInfo>(this.userinfoEndpoint, { headers }).subscribe(
487+
(info) => {
488+
this.debug('userinfo received', info);
490489

491490
let existingClaims = this.getIdentityClaims() || {};
492-
491+
493492
if (!this.skipSubjectCheck) {
494-
if (this.oidc && (!existingClaims['sub'] || doc.sub !== existingClaims['sub'])) {
493+
if (this.oidc && (!existingClaims['sub'] || info.sub !== existingClaims['sub'])) {
495494
let err = 'if property oidc is true, the received user-id (sub) has to be the user-id '
496495
+ 'of the user that has logged in with oidc.\n'
497496
+ 'if you are not using oidc but just oauth2 password flow set oidc to false';
@@ -501,11 +500,11 @@ export class OAuthService
501500
}
502501
}
503502

504-
doc = Object.assign({}, existingClaims, doc);
503+
info = Object.assign({}, existingClaims, info);
505504

506-
this._storage.setItem('id_token_claims_obj', JSON.stringify(doc));
505+
this._storage.setItem('id_token_claims_obj', JSON.stringify(info));
507506
this.eventsSubject.next(new OAuthSuccessEvent('user_profile_loaded'));
508-
resolve(doc);
507+
resolve(info);
509508
},
510509
(err) => {
511510
console.error('error loading user info', err);
@@ -522,7 +521,7 @@ export class OAuthService
522521
* @param password
523522
* @param headers Optional additional http-headers.
524523
*/
525-
public fetchTokenUsingPasswordFlow(userName: string, password: string, headers: Headers = new Headers()): Promise<object> {
524+
public fetchTokenUsingPasswordFlow(userName: string, password: string, headers: HttpHeaders = new HttpHeaders()): Promise<object> {
526525

527526
if (!this.validateUrlForHttps(this.tokenEndpoint)) {
528527
throw new Error('tokenEndpoint must use Http. Also check property requireHttps.');
@@ -544,7 +543,7 @@ export class OAuthService
544543

545544
let params = search.toString();
546545

547-
this.http.post(this.tokenEndpoint, params, { headers }).map(r => r.json()).subscribe(
546+
this.http.post<TokenResponse>(this.tokenEndpoint, params, { headers }).subscribe(
548547
(tokenResponse) => {
549548
this.debug('tokenResponse', tokenResponse);
550549
this.storeAccessTokenResponse(tokenResponse.access_token, tokenResponse.refresh_token, tokenResponse.expires_in);
@@ -586,12 +585,12 @@ export class OAuthService
586585
search.set('client_secret', this.dummyClientSecret);
587586
}
588587

589-
let headers = new Headers();
590-
headers.set('Content-Type', 'application/x-www-form-urlencoded');
588+
const headers = new HttpHeaders()
589+
.set('Content-Type', 'application/x-www-form-urlencoded');
591590

592591
let params = search.toString();
593592

594-
this.http.post(this.tokenEndpoint, params, { headers }).map(r => r.json()).subscribe(
593+
this.http.post<TokenResponse>(this.tokenEndpoint, params, { headers }).subscribe(
595594
(tokenResponse) => {
596595
this.debug('refresh tokenResponse', tokenResponse);
597596
this.storeAccessTokenResponse(tokenResponse.access_token, tokenResponse.refresh_token, tokenResponse.expires_in);
@@ -785,8 +784,7 @@ export class OAuthService
785784
}
786785

787786
private waitForSilentRefreshAfterSessionChange() {
788-
this
789-
.events
787+
this.events
790788
.filter((e: OAuthEvent) =>
791789
e.type === 'silently_refreshed'
792790
|| e.type === 'silent_refresh_timeout'
@@ -1396,7 +1394,7 @@ export class OAuthService
13961394
this._storage.removeItem('id_token_expires_at');
13971395
this._storage.removeItem('id_token_stored_at');
13981396
this._storage.removeItem('access_token_stored_at');
1399-
1397+
14001398
this.silentRefreshSubject = null;
14011399

14021400
this.eventsSubject.next(new OAuthInfoEvent('logout'));
@@ -1408,7 +1406,7 @@ export class OAuthService
14081406
let logoutUrl: string;
14091407

14101408
if (!this.validateUrlForHttps(this.logoutUrl)) throw new Error('logoutUrl must use Http. Also check property requireHttps.');
1411-
1409+
14121410
// For backward compatibility
14131411
if (this.logoutUrl.indexOf('{{') > -1) {
14141412
logoutUrl = this.logoutUrl.replace(/\{\{id_token\}\}/, id_token);

angular-oauth2-oidc/src/types.ts

+58
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,61 @@ export interface ParsedIdToken {
7777
idTokenHeaderJson: string;
7878
idTokenExpiresAt: number;
7979
}
80+
81+
/**
82+
* Represents the response from the token endpoint
83+
* http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
84+
*/
85+
export interface TokenResponse {
86+
access_token: string;
87+
token_type: string;
88+
expires_in: number;
89+
refresh_token: string;
90+
scope: string;
91+
state?: string;
92+
}
93+
94+
/**
95+
* Represents the response from the user info endpoint
96+
* http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
97+
*/
98+
export interface UserInfo {
99+
sub: string;
100+
[key: string]: any;
101+
}
102+
103+
/**
104+
* Represents an OpenID Connect discovery document
105+
*/
106+
export interface OidcDiscoveryDoc {
107+
issuer: string;
108+
authorization_endpoint: string;
109+
token_endpoint: string;
110+
token_endpoint_auth_methods_supported: string[];
111+
token_endpoint_auth_signing_alg_values_supported: string[];
112+
userinfo_endpoint: string;
113+
check_session_iframe: string;
114+
end_session_endpoint: string;
115+
jwks_uri: string;
116+
registration_endpoint: string;
117+
scopes_supported: string[];
118+
response_types_supported: string[];
119+
acr_values_supported: string[];
120+
response_modes_supported: string[];
121+
grant_types_supported: string[];
122+
subject_types_supported: string[];
123+
userinfo_signing_alg_values_supported: string[];
124+
userinfo_encryption_alg_values_supported: string[];
125+
userinfo_encryption_enc_values_supported: string[];
126+
id_token_signing_alg_values_supported: string[];
127+
id_token_encryption_alg_values_supported: string[];
128+
id_token_encryption_enc_values_supported: string[];
129+
request_object_signing_alg_values_supported: string[];
130+
display_values_supported: string[];
131+
claim_types_supported: string[];
132+
claims_supported: string[];
133+
claims_parameter_supported: boolean;
134+
service_documentation: string;
135+
ui_locales_supported: string[];
136+
}
137+

0 commit comments

Comments
 (0)