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 6 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
33 changes: 9 additions & 24 deletions lib/msal-browser/src/app/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// import { Logger } from "./Logger";
import { BrowserUtils } from "../utils/BrowserUtils";
import { AuthOptions } from "msal-common";
import { INetworkClient } from "../network/INetworkClient";
import { FetchClient } from "../network/FetchClient";
// import { TelemetryEmitter } from "./telemetry/TelemetryTypes";

/**
Expand Down Expand Up @@ -48,25 +50,13 @@ export type TelemetryOptions = {
*/
export type SystemOptions = {
// logger?: Logger;
networkClient?: INetworkClient;
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 +69,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 +89,11 @@ const DEFAULT_CACHE_OPTIONS: CacheOptions = {

const DEFAULT_SYSTEM_OPTIONS: SystemOptions = {
// logger: new Logger(null),
networkClient: new FetchClient(),
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 +107,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;
}
21 changes: 18 additions & 3 deletions lib/msal-browser/src/app/PublicClientApplication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
*/

import * as msalAuth from "msal-common";
import { Configuration, buildConfiguration } from "./Configuration";
import { Configuration, buildConfiguration, SystemOptions } from "./Configuration";
import { BrowserCrypto } from "../utils/crypto/BrowserCrypto";
import { FetchClient } from "../network/FetchClient";
import { BrowserStorage } from "../cache/BrowserStorage";
import { INetworkClient } from "../network/INetworkClient";

/**
* A type alias for an authResponseCallback function.
Expand Down Expand Up @@ -38,6 +41,12 @@ export class PublicClientApplication {
// Crypto interface implementation
private browserCrypto: BrowserCrypto;

// Storage interface implementation
private browserStorage: BrowserStorage;

// Network interface implementation
private networkClient: INetworkClient;

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

// 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
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
20 changes: 20 additions & 0 deletions lib/msal-browser/src/network/FetchClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { INetworkClient } from "./INetworkClient";

export class FetchClient implements INetworkClient {

/**
* XHR client for JSON endpoints
* https://www.npmjs.com/package/async-promise
* @param url
* @param requestParams
* @param enableCaching
*/
async sendRequestAsync(url: string, requestParams: RequestInit): Promise<any> {
pkanher617 marked this conversation as resolved.
Show resolved Hide resolved
const response = await fetch(url, requestParams);
return response.json();
}
}
16 changes: 16 additions & 0 deletions lib/msal-browser/src/network/INetworkClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/

import { INetworkModule } from "msal-common";

export interface INetworkClient extends INetworkModule {
/**
* Interface function for async network requests. Based on the Fetch standard: https://fetch.spec.whatwg.org/
* @param url
* @param requestParams
* @param enableCaching
*/
sendRequestAsync(url: string, requestParams: RequestInit): Promise<any>;
}
2 changes: 1 addition & 1 deletion lib/msal-common/src/app/config/MsalModuleConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const DEFAULT_STORAGE_OPTIONS: ICacheStorage = {
};

const DEFAULT_NETWORK_OPTIONS: INetworkModule = {
async sendRequestAsync(url: string, method: RequestInit, enableCaching?: boolean): Promise<any> {
async sendRequestAsync(url: string, method: RequestInit): Promise<any> {
const notImplErr = "Network interface - sendRequestAsync() has not been implemented";
console.warn(notImplErr);
throw AuthError.createUnexpectedError(notImplErr);
Expand Down
2 changes: 1 addition & 1 deletion lib/msal-common/src/auth/authority/AadAuthority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,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.sendRequestAsync(this.aadInstanceDiscoveryEndpointUrl, { method: "GET" });
return response.tenant_discovery_endpoint;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/msal-common/src/auth/authority/Authority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export abstract class Authority {
}

private async discoverEndpoints(openIdConfigurationEndpoint: string): Promise<ITenantDiscoveryResponse> {
const response = await this.networkInterface.sendRequestAsync(openIdConfigurationEndpoint, { method: "GET" }, true);
const response = await this.networkInterface.sendRequestAsync(openIdConfigurationEndpoint, { method: "GET" });
return {
AuthorizationEndpoint: response.authorization_endpoint,
TokenEndpoint: response.token_endpoint,
Expand Down
2 changes: 1 addition & 1 deletion lib/msal-common/src/network/INetworkModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ export interface INetworkModule {
* @param requestParams
* @param enableCaching
*/
sendRequestAsync(url: string, requestParams: RequestInit, enableCaching?:boolean): Promise<any>
sendRequestAsync(url: string, requestParams: RequestInit): Promise<any>;
pkanher617 marked this conversation as resolved.
Show resolved Hide resolved
}