Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorization Code Flow for Single Page Applications: Implementation of the Fetch Client in the Browser #1144

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 9 additions & 25 deletions lib/msal-browser/src/app/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
*/

// import { Logger } from "./Logger";
import { AuthOptions, INetworkModule } from "msal-common";
import { BrowserUtils } from "../utils/BrowserUtils";
import { AuthOptions } from "msal-common";
import { FetchClient } from "../network/FetchClient";
// import { TelemetryEmitter } from "./telemetry/TelemetryTypes";

/**
Expand Down Expand Up @@ -48,25 +49,13 @@ export type TelemetryOptions = {
*/
export type SystemOptions = {
// logger?: Logger;
networkClient?: INetworkModule;
loadFrameTimeout?: number;
tokenRenewalOffsetSeconds?: number;
navigateFrameWait?: number;
telemetry?: TelemetryOptions
};

/**
* App/Framework specific environment support
*
* - isAngular - flag set to determine if it is Angular Framework. MSAL uses this to broadcast tokens. More to come here: detangle this dependency from core.
* - unprotectedResources - Array of URI's which are unprotected resources. MSAL will not attach a token to outgoing requests that have these URI. Defaults to 'null'.
* - protectedResourceMap - This is mapping of resources to scopes used by MSAL for automatically attaching access tokens in web API calls.A single access token is obtained for the resource. So you can map a specific resource path as follows: {"https://graph.microsoft.com/v1.0/me", ["user.read"]}, or the app URL of the resource as: {"https://graph.microsoft.com/", ["user.read", "mail.send"]}. This is required for CORS calls.
*
*/
export type FrameworkOptions = {
unprotectedResources?: Array<string>;
protectedResourceMap?: Map<string, Array<string>>;
};

/**
* Use the configuration object to configure MSAL and initialize the UserAgentApplication.
*
Expand All @@ -79,8 +68,7 @@ export type FrameworkOptions = {
export type Configuration = {
auth: AuthOptions,
cache?: CacheOptions,
system?: SystemOptions,
framework?: FrameworkOptions
system?: SystemOptions
};

const DEFAULT_AUTH_OPTIONS: AuthOptions = {
Expand All @@ -100,14 +88,11 @@ const DEFAULT_CACHE_OPTIONS: CacheOptions = {

const DEFAULT_SYSTEM_OPTIONS: SystemOptions = {
// logger: new Logger(null),
networkClient: BrowserUtils.getBrowserNetworkClient(),
loadFrameTimeout: FRAME_TIMEOUT,
tokenRenewalOffsetSeconds: OFFSET,
navigateFrameWait: NAVIGATE_FRAME_WAIT
};

const DEFAULT_FRAMEWORK_OPTIONS: FrameworkOptions = {
unprotectedResources: new Array<string>(),
protectedResourceMap: new Map<string, Array<string>>()
navigateFrameWait: NAVIGATE_FRAME_WAIT,
telemetry: null
};

/**
Expand All @@ -121,12 +106,11 @@ const DEFAULT_FRAMEWORK_OPTIONS: FrameworkOptions = {
* @returns TConfiguration object
*/

export function buildConfiguration({ auth, cache = {}, system = {}, framework = {}}: Configuration): Configuration {
export function buildConfiguration({ auth, cache = {}, system = {}}: Configuration): Configuration {
const overlayedConfig: Configuration = {
auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },
cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },
system: { ...DEFAULT_SYSTEM_OPTIONS, ...system },
framework: { ...DEFAULT_FRAMEWORK_OPTIONS, ...framework }
system: { ...DEFAULT_SYSTEM_OPTIONS, ...system }
};
return overlayedConfig;
}
17 changes: 15 additions & 2 deletions lib/msal-browser/src/app/PublicClientApplication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import * as msalAuth from "msal-common";
import { BrowserStorage } from "../cache/BrowserStorage";
import { Configuration, buildConfiguration } from "./Configuration";
import { CryptoOps } from "../crypto/CryptoOps";

Expand Down Expand Up @@ -38,6 +39,12 @@ export class PublicClientApplication {
// Crypto interface implementation
private browserCrypto: CryptoOps;

// Storage interface implementation
private browserStorage: BrowserStorage;

// Network interface implementation
private networkClient: msalAuth.INetworkModule;

/**
* @constructor
* Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
Expand Down Expand Up @@ -65,12 +72,18 @@ export class PublicClientApplication {
// Initialize the crypto class
this.browserCrypto = new CryptoOps();

// Initialize the network module class
this.networkClient = this.config.system.networkClient;

// Initialize the browser storage class
this.browserStorage = new BrowserStorage(this.config.auth.clientId, this.config.cache);

// Create auth module
this.authModule = new msalAuth.AuthorizationCodeModule({
auth: this.config.auth,
cryptoInterface: this.browserCrypto,
networkInterface: null,
storageInterface: null
networkInterface: this.networkClient,
storageInterface: this.browserStorage
});
}

Expand Down
1 change: 0 additions & 1 deletion lib/msal-browser/src/cache/BrowserStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/

import { ICacheStorage, Constants, PersistentCacheKeys, TemporaryCacheKeys, ErrorCacheKeys } from "msal-common";
import { CacheOptions } from "../app/Configuration";
import { BrowserAuthError } from "../error/BrowserAuthError";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { ClientConfigurationError, AuthError } from "msal-common";
import { AuthError } from "msal-common";

/**
* BrowserAuthErrorMessage class containing string constants used by error codes and messages.
Expand Down
3 changes: 2 additions & 1 deletion lib/msal-browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export {
AuthResponse,
// Error
AuthError,
AuthErrorMessage
AuthErrorMessage,
INetworkModule
} from "msal-common";
60 changes: 60 additions & 0 deletions lib/msal-browser/src/network/FetchClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { INetworkModule, NetworkRequestOptions } from "msal-common";

enum HTTP_REQUEST_TYPE {
GET = "GET",
POST = "POST"
};

export class FetchClient implements INetworkModule {

/**
* Fetch Client for REST endpoints - Get request
* @param url
* @param headers
* @param body
*/
async sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<T> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 🔥 🔥 🚀

const response = await fetch(url, {
method: HTTP_REQUEST_TYPE.GET,
headers: this.getFetchHeaders(options.headers),
credentials: "include",
body: options.body
});
return await response.json() as T;
}

/**
* Fetch Client for REST endpoints - Post request
* @param url
* @param headers
* @param body
*/
async sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<T> {
const response = await fetch(url, {
method: HTTP_REQUEST_TYPE.POST,
headers: this.getFetchHeaders(options.headers),
credentials: "include",
body: options.body
});
return await response.json() as T;
}

/**
* Get Fetch API Headers object from string map
* @param inputHeaders
*/
private getFetchHeaders(inputHeaders: Map<string, string>): Headers {
if (!inputHeaders) {
return null;
}
const headers = new Headers;
for (const headerName in inputHeaders.keys()) {
headers.append(headerName, inputHeaders.get(headerName));
}
return headers;
}
}
66 changes: 66 additions & 0 deletions lib/msal-browser/src/network/XhrClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { INetworkModule, NetworkRequestOptions } from "msal-common";

export class XhrClient implements INetworkModule {

async sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<T> {
return this.sendRequestAsync(url, "GET", options);
}

async sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): Promise<T> {
return this.sendRequestAsync(url, "POST", options);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use the enum here also?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in PR #1149.

}

private sendRequestAsync<T>(url: string, method: string, options?: NetworkRequestOptions): Promise<T> {
return new Promise<T>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, /* async: */ true);
this.setXhrHeaders(xhr, options.headers);
xhr.onload = (ev) => {
if (xhr.status < 200 || xhr.status >= 300) {
reject(this.handleError(xhr.responseText));
}
try {
let jsonResponse = JSON.parse(xhr.responseText) as T;
resolve(jsonResponse);
} catch (e) {
reject(this.handleError(xhr.responseText));
}
};

xhr.onerror = (ev) => {
reject(xhr.status);
};

if (method === "GET" || method === "POST") {
xhr.send(options.body);
}
else {
throw "not implemented";
}
});
}

private handleError(responseText: string): any {
let jsonResponse;
try {
jsonResponse = JSON.parse(responseText);
if (jsonResponse.error) {
return jsonResponse.error;
} else {
throw responseText;
}
} catch (e) {
return responseText;
}
}

private setXhrHeaders(xhr: XMLHttpRequest, headers: Map<string, string>): void {
for (const headerName in headers.keys()) {
xhr.setRequestHeader(headerName, headers.get(headerName));
}
}
}
14 changes: 14 additions & 0 deletions lib/msal-browser/src/utils/BrowserUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { INetworkModule } from "msal-common";
import { FetchClient } from "../network/FetchClient";
import { XhrClient } from "../network/XhrClient";

/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
Expand Down Expand Up @@ -28,4 +32,14 @@ export class BrowserUtils {
return window.location.href.split("?")[0].split("#")[0];
}

/**
* Returns best compatible network client object.
*/
static getBrowserNetworkClient(): INetworkModule {
if (window.fetch) {
return new FetchClient();
} else {
return new XhrClient();
}
}
}
11 changes: 8 additions & 3 deletions lib/msal-common/src/app/config/MsalModuleConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License.
*/
import { ICacheStorage } from "../../cache/ICacheStorage";
import { INetworkModule } from "../../network/INetworkModule";
import { INetworkModule, NetworkRequestOptions } from "../../network/INetworkModule";
import { ICrypto, PkceCodes } from "../../utils/crypto/ICrypto";
import { AuthError } from "../../error/AuthError";

Expand Down Expand Up @@ -55,8 +55,13 @@ const DEFAULT_STORAGE_OPTIONS: ICacheStorage = {
};

const DEFAULT_NETWORK_OPTIONS: INetworkModule = {
async sendRequestAsync(url: string, method: RequestInit, enableCaching?: boolean): Promise<any> {
const notImplErr = "Network interface - sendRequestAsync() has not been implemented";
async sendGetRequestAsync(url: string, options?: NetworkRequestOptions): Promise<any> {
const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
console.warn(notImplErr);
throw AuthError.createUnexpectedError(notImplErr);
},
async sendPostRequestAsync(url: string, options?: NetworkRequestOptions): Promise<any> {
const notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
console.warn(notImplErr);
throw AuthError.createUnexpectedError(notImplErr);
}
Expand Down
3 changes: 2 additions & 1 deletion lib/msal-common/src/auth/authority/AadAuthority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { Authority, AuthorityType } from "./Authority";
import { AADTrustedHostList } from "../../utils/Constants";
import { INetworkModule } from "../../network/INetworkModule";
import { ITenantDiscoveryResponse } from "./ITenantDiscoveryResponse";

/**
* @hidden
Expand Down Expand Up @@ -41,7 +42,7 @@ export class AadAuthority extends Authority {
}

// for custom domains in AAD where we query the service for the Instance discovery
const response = await this.networkInterface.sendRequestAsync(this.aadInstanceDiscoveryEndpointUrl, { method: "GET" }, true);
const response = await this.networkInterface.sendGetRequestAsync<any>(this.aadInstanceDiscoveryEndpointUrl);
return response.tenant_discovery_endpoint;
}

Expand Down
16 changes: 5 additions & 11 deletions lib/msal-common/src/auth/authority/Authority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,31 +57,31 @@ export abstract class Authority {

public get authorizationEndpoint(): string {
if(this.discoveryComplete) {
return this.tenantDiscoveryResponse.AuthorizationEndpoint.replace("{tenant}", this.tenant);
return this.tenantDiscoveryResponse.authorization_endpoint.replace("{tenant}", this.tenant);
} else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError();
}
}

public get tokenEndpoint(): string {
if(this.discoveryComplete) {
return this.tenantDiscoveryResponse.TokenEndpoint.replace("{tenant}", this.tenant);
return this.tenantDiscoveryResponse.token_endpoint.replace("{tenant}", this.tenant);
} else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError();
}
}

public get endSessionEndpoint(): string {
if(this.discoveryComplete) {
return this.tenantDiscoveryResponse.EndSessionEndpoint.replace("{tenant}", this.tenant);
return this.tenantDiscoveryResponse.end_session_endpoint.replace("{tenant}", this.tenant);
} else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError();
}
}

public get selfSignedJwtAudience(): string {
if(this.discoveryComplete) {
return this.tenantDiscoveryResponse.Issuer.replace("{tenant}", this.tenant);
return this.tenantDiscoveryResponse.issuer.replace("{tenant}", this.tenant);
} else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError();
}
Expand All @@ -103,13 +103,7 @@ export abstract class Authority {
}

private async discoverEndpoints(openIdConfigurationEndpoint: string): Promise<ITenantDiscoveryResponse> {
const response = await this.networkInterface.sendRequestAsync(openIdConfigurationEndpoint, { method: "GET" }, true);
return {
AuthorizationEndpoint: response.authorization_endpoint,
TokenEndpoint: response.token_endpoint,
EndSessionEndpoint: response.end_session_endpoint,
Issuer: response.issuer
} as ITenantDiscoveryResponse;
return this.networkInterface.sendGetRequestAsync<ITenantDiscoveryResponse>(openIdConfigurationEndpoint);
}

public abstract async getOpenIdConfigurationAsync(): Promise<string>;
Expand Down