82 lines
2.4 KiB
TypeScript
82 lines
2.4 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
|
|
/**
|
|
* @module azure
|
|
*
|
|
* This module provides authentication functionalities for Azure services.
|
|
*/
|
|
|
|
import { getTokenUsingMsal } from "./pca-auth.ts";
|
|
import { getTokenUsingAzureIdentity } from "./client-auth.ts";
|
|
import { loadAuthConfig, loadConfig } from "../index.ts";
|
|
import { SkAzureCredential } from "./sk-credential.ts";
|
|
import { DefaultAzureCredential } from "@azure/identity";
|
|
import type { TokenCredential } from "@azure/core-auth";
|
|
|
|
// Reexporting functions and types from submodules
|
|
export {
|
|
loginInteractive,
|
|
loginDeviceCode,
|
|
login,
|
|
logout,
|
|
parseResources,
|
|
} from "./pca-auth.ts";
|
|
|
|
export { getCredential } from "./client-auth.ts";
|
|
|
|
export const RESOURCE_SCOPE_BY_NAME = {
|
|
graph: "https://graph.microsoft.com/.default",
|
|
devops: "499b84ac-1321-427f-aa17-267ca6975798/.default",
|
|
azurerm: "https://management.azure.com/.default",
|
|
openai: "https://cognitiveservices.azure.com/.default",
|
|
} as const;
|
|
|
|
export type ResourceName = keyof typeof RESOURCE_SCOPE_BY_NAME;
|
|
export const DEFAULT_RESOURCES: ResourceName[] = ["graph", "devops", "azurerm"];
|
|
|
|
// A helper function to translate short resource names to their corresponding scopes
|
|
export function translateResourceNamesToScopes(resourceNames: string[]): string[] {
|
|
return resourceNames.map((name) => RESOURCE_SCOPE_BY_NAME[name as ResourceName]);
|
|
}
|
|
|
|
export function supportedResourceNames(): ResourceName[] {
|
|
return Object.keys(RESOURCE_SCOPE_BY_NAME) as ResourceName[];
|
|
}
|
|
|
|
// Generic utility functions
|
|
export type AuthMode = "azure-identity" | "msal";
|
|
|
|
export async function getTokenCredential(
|
|
tenantId?: string,
|
|
clientId?: string,
|
|
): Promise<TokenCredential> {
|
|
const config = await loadConfig();
|
|
|
|
if (config.authMode === "azure-identity") {
|
|
return new DefaultAzureCredential();
|
|
}
|
|
|
|
const authConfig = await loadAuthConfig("public-config");
|
|
return new SkAzureCredential(
|
|
tenantId || authConfig.tenantId,
|
|
clientId || authConfig.clientId,
|
|
);
|
|
}
|
|
|
|
export async function getAccessToken(
|
|
tenantId: string,
|
|
clientId: string,
|
|
resources: string[]
|
|
): Promise<string> {
|
|
const config = await loadConfig();
|
|
if (config.authMode === "msal") {
|
|
const result = await getTokenUsingMsal(tenantId, clientId, resources);
|
|
if (!result?.accessToken) {
|
|
throw new Error("Failed to acquire access token with MSAL.");
|
|
}
|
|
return result.accessToken;
|
|
} else {
|
|
return getTokenUsingAzureIdentity(tenantId, clientId, resources);
|
|
}
|
|
}
|