Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
maorleger committed May 2, 2024
1 parent a5f0032 commit a127b3a
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 1 deletion.
23 changes: 22 additions & 1 deletion sdk/identity/identity/src/credentials/deviceCodeCredential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@ import { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth"
import {
processMultiTenantRequest,
resolveAdditionallyAllowedTenantIds,
resolveTenantId,
} from "../util/tenantIdUtils";
import { DeviceCodeCredentialOptions, DeviceCodeInfo } from "./deviceCodeCredentialOptions";
import {
DeviceCodeCredentialOptions,
DeviceCodeInfo,
DeviceCodePromptCallback,
} from "./deviceCodeCredentialOptions";
import { AuthenticationRecord } from "../msal/types";
import { MsalDeviceCode } from "../msal/nodeFlows/msalDeviceCode";
import { MsalFlow } from "../msal/flows";
import { credentialLogger } from "../util/logging";
import { ensureScopes } from "../util/scopeUtils";
import { tracingClient } from "../util/tracing";
import { MsalClient, createMsalClient } from "../msal/nodeFlows/msalClient";
import { DeveloperSignOnClientId } from "../constants";

const logger = credentialLogger("DeviceCodeCredential");

Expand All @@ -33,6 +40,8 @@ export class DeviceCodeCredential implements TokenCredential {
private additionallyAllowedTenantIds: string[];
private msalFlow: MsalFlow;
private disableAutomaticAuthentication?: boolean;
private msalClient: MsalClient;
private userPromptCallback: DeviceCodePromptCallback;

/**
* Creates an instance of DeviceCodeCredential with the details needed
Expand All @@ -59,6 +68,13 @@ export class DeviceCodeCredential implements TokenCredential {
this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(
options?.additionallyAllowedTenants,
);
const clientId = options?.clientId ?? DeveloperSignOnClientId;
const tenantId = resolveTenantId(logger, options?.tenantId, clientId);
this.userPromptCallback = options?.userPromptCallback || defaultDeviceCodePromptCallback;
this.msalClient = createMsalClient(clientId, tenantId, {
...options,
tokenCredentialOptions: options || {},
});
this.msalFlow = new MsalDeviceCode({
...options,
logger,
Expand Down Expand Up @@ -93,6 +109,11 @@ export class DeviceCodeCredential implements TokenCredential {
);

const arrayScopes = ensureScopes(scopes);
return this.msalClient.getTokenByDeviceCode(
arrayScopes,
this.userPromptCallback,
newOptions,
);
return this.msalFlow.getToken(arrayScopes, {
...newOptions,
disableAutomaticAuthentication: this.disableAutomaticAuthentication,
Expand Down
63 changes: 63 additions & 0 deletions sdk/identity/identity/src/msal/nodeFlows/msalClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { MsalNodeOptions } from "./msalNodeCommon";
import { calculateRegionalAuthority } from "../../regionalAuthority";
import { getLogLevel } from "@azure/logger";
import { resolveTenantId } from "../../util/tenantIdUtils";
import { DeviceCodePromptCallback } from "../../credentials/deviceCodeCredentialOptions";

/**
* The logger for all MsalClient instances.
Expand All @@ -33,6 +34,11 @@ const msalLogger = credentialLogger("MsalClient");
* Represents a client for interacting with the Microsoft Authentication Library (MSAL).
*/
export interface MsalClient {
getTokenByDeviceCode(
arrayScopes: string[],
userPromptCallback: DeviceCodePromptCallback,
options?: GetTokenOptions,
): Promise<AccessToken>;
/**
* Retrieves an access token by using a client certificate.
*
Expand Down Expand Up @@ -173,6 +179,35 @@ export function createMsalClient(
pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions),
};

const publicApps: Map<string, msal.PublicClientApplication> = new Map();
async function getPublicApp(
options: GetTokenOptions = {},
): Promise<msal.PublicClientApplication> {
const appKey = options.enableCae ? "CAE" : "default";

let publicClientApp = publicApps.get(appKey);
if (publicClientApp) {
return publicClientApp;
}

// Initialize a new app and cache it
const cachePlugin = options.enableCae
? state.pluginConfiguration.cache.cachePluginCae
: state.pluginConfiguration.cache.cachePlugin;

state.msalConfig.auth.clientCapabilities = options.enableCae ? ["cp1"] : undefined;

publicClientApp = new msal.PublicClientApplication({
...state.msalConfig,
broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin },
cache: { cachePlugin: await cachePlugin },
});

publicApps.set(appKey, publicClientApp);

return publicClientApp;
}

const confidentialApps: Map<string, msal.ConfidentialClientApplication> = new Map();
async function getConfidentialApp(
options: GetTokenOptions = {},
Expand Down Expand Up @@ -377,9 +412,37 @@ To work with multiple accounts for the same Client ID and Tenant ID, please prov
);
}

async function getTokenByDeviceCode(
scopes: string[],
deviceCodeCallback: DeviceCodePromptCallback,
options: GetTokenOptions = {},
): Promise<AccessToken> {
msalLogger.getToken.info(`Attempting to acquire token using device code`);

const msalApp = await getPublicApp(options);

return withSilentAuthentication(msalApp, scopes, options, () => {
const requestOptions: msal.DeviceCodeRequest = {
scopes,
cancel: false,
deviceCodeCallback,
authority: state.msalConfig.auth.authority,
claims: options?.claims,
};
const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions);
if (options.abortSignal) {
options.abortSignal.addEventListener("abort", () => {
requestOptions.cancel = true;
});
}
return deviceCodeRequest;
});
}

return {
getTokenByClientSecret,
getTokenByClientAssertion,
getTokenByClientCertificate,
getTokenByDeviceCode,
};
}

0 comments on commit a127b3a

Please sign in to comment.