Compare commits
4 Commits
a8725a7c22
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9137688a55 | |||
| a805ed415f | |||
| 1a70f7efcf | |||
| 2645d6c1f4 |
60
bin/create-app-and-sp.mjs
Normal file
60
bin/create-app-and-sp.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { config } from "../public-config.js";
|
||||
import {
|
||||
createApp,
|
||||
createSp,
|
||||
getApp,
|
||||
getGraphClient,
|
||||
getServicePrincipal,
|
||||
} from "../src/graph.js";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
async function usage() {
|
||||
console.log("Usage: create-app-and-sp.mjs --app-name <name>");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { client } = await getGraphClient({
|
||||
tenantId: config.tenantId,
|
||||
clientId: config.clientId,
|
||||
});
|
||||
|
||||
const args = parseArgs({
|
||||
options: {
|
||||
"app-name": {
|
||||
type: "string",
|
||||
short: "n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!args.values["app-name"]) {
|
||||
await usage();
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Will create app with name:", args.values["app-name"]);
|
||||
|
||||
let app = await getApp(client, args.values["app-name"]);
|
||||
if (!app) {
|
||||
app = await createApp(client, args.values["app-name"]);
|
||||
console.log("Created app:", app.appId);
|
||||
}
|
||||
|
||||
let sp = await getServicePrincipal(client, app.appId);
|
||||
if (!sp) {
|
||||
sp = await createSp(client, app.appId);
|
||||
console.log("Created service principal:", sp.id);
|
||||
}
|
||||
|
||||
console.log(`The application and associated service principal are ready.
|
||||
App ID: ${app.appId}
|
||||
Service Principal ID: ${sp.id}`);
|
||||
}
|
||||
|
||||
await main().catch((e) => {
|
||||
console.error("Error in main:", e);
|
||||
console.error(e.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
65
bin/delete-app-and-sp.mjs
Normal file
65
bin/delete-app-and-sp.mjs
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { config } from "../public-config.js";
|
||||
import {
|
||||
deleteApp,
|
||||
deleteSp,
|
||||
getApp,
|
||||
getGraphClient,
|
||||
getServicePrincipal,
|
||||
} from "../src/graph.js";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
async function usage() {
|
||||
console.log("Usage: delete-app-and-sp.mjs --app-name <name>");
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { client } = await getGraphClient({
|
||||
tenantId: config.tenantId,
|
||||
clientId: config.clientId,
|
||||
});
|
||||
|
||||
const args = parseArgs({
|
||||
options: {
|
||||
"app-name": {
|
||||
type: "string",
|
||||
short: "n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!args.values["app-name"]) {
|
||||
await usage();
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Will delete app with name:", args.values["app-name"]);
|
||||
|
||||
const app = await getApp(client, args.values["app-name"]);
|
||||
if (!app) {
|
||||
console.log("No app found with name:", args.values["app-name"]);
|
||||
return;
|
||||
}
|
||||
|
||||
const sp = await getServicePrincipal(client, app.appId);
|
||||
if (sp && sp.id) {
|
||||
await deleteSp(client, sp.id);
|
||||
console.log("Deleted service principal:", sp.id);
|
||||
} else {
|
||||
console.log("No service principal found for appId:", app.appId);
|
||||
}
|
||||
|
||||
if (app && app.id) {
|
||||
await deleteApp(client, app.id);
|
||||
console.log("Deleted app:", app.appId);
|
||||
} else {
|
||||
console.log("App object id missing; cannot delete application");
|
||||
}
|
||||
}
|
||||
|
||||
await main().catch((e) => {
|
||||
console.error("Error in main:", e);
|
||||
console.error(e.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -3,8 +3,10 @@
|
||||
import { loginInteractive } from "../src/azure.js";
|
||||
import { config } from "../public-config.js";
|
||||
import { createHash } from "crypto";
|
||||
import { Client } from "@microsoft/microsoft-graph-client";
|
||||
|
||||
const scopes = ["https://management.azure.com/.default"];
|
||||
// const scopes = ["https://management.azure.com/.default"];
|
||||
const scopes = ["https://graph.microsoft.com/.default"];
|
||||
|
||||
let token;
|
||||
|
||||
@@ -26,3 +28,30 @@ console.log("Access token acquired.");
|
||||
const hash = createHash("sha256").update(token.accessToken).digest("hex");
|
||||
console.log("SHA-256 hash of access token:", hash);
|
||||
console.log("Token expires on:", token.expiresOn);
|
||||
|
||||
const client = Client.init({
|
||||
authProvider: (done) => {
|
||||
done(null, token.accessToken);
|
||||
},
|
||||
});
|
||||
|
||||
let result;
|
||||
|
||||
result = await client
|
||||
.api("/applications")
|
||||
.filter("displayName eq 'Azure Node Playground Public'")
|
||||
.get();
|
||||
|
||||
const apps = result.value ?? [];
|
||||
console.log(
|
||||
`Registered applications with the name 'Azure Node Playground' (${apps.length}):`,
|
||||
);
|
||||
|
||||
if (apps.length !== 1) {
|
||||
console.error(
|
||||
"Expected exactly one application with the name 'Azure Node Playground'. Please ensure it is registered in your Azure AD tenant.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("Application details:", apps[0]);
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import open from "open";
|
||||
import open, { apps } from "open";
|
||||
|
||||
async function openBrowser(url) {
|
||||
try {
|
||||
await open(url);
|
||||
await open(url, {
|
||||
wait: false,
|
||||
app: {
|
||||
name: apps.edge
|
||||
}
|
||||
});
|
||||
console.log(`Browser opened to ${url}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to open browser: ${error}`);
|
||||
|
||||
63
src/azure.js
63
src/azure.js
@@ -1,13 +1,20 @@
|
||||
// azure.js
|
||||
import http from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import open from "open";
|
||||
import open, { apps } from "open";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { PublicClientApplication, ConfidentialClientApplication } from "@azure/msal-node";
|
||||
import { DefaultAzureCredential, ClientSecretCredential, DeviceCodeCredential } from "@azure/identity";
|
||||
import {
|
||||
PublicClientApplication,
|
||||
ConfidentialClientApplication,
|
||||
} from "@azure/msal-node";
|
||||
import {
|
||||
DefaultAzureCredential,
|
||||
ClientSecretCredential,
|
||||
DeviceCodeCredential,
|
||||
} from "@azure/identity";
|
||||
|
||||
export async function getCredential(credentialType, options) {
|
||||
switch (credentialType) {
|
||||
@@ -17,17 +24,21 @@ export async function getCredential(credentialType, options) {
|
||||
case "cs":
|
||||
case "clientSecret":
|
||||
if (!options.tenantId || !options.clientId || !options.clientSecret) {
|
||||
throw new Error("tenantId, clientId, and clientSecret are required for ClientSecretCredential");
|
||||
throw new Error(
|
||||
"tenantId, clientId, and clientSecret are required for ClientSecretCredential",
|
||||
);
|
||||
}
|
||||
return new ClientSecretCredential(
|
||||
options.tenantId,
|
||||
options.clientId,
|
||||
options.clientSecret
|
||||
options.clientSecret,
|
||||
);
|
||||
case "dc":
|
||||
case "deviceCode":
|
||||
if (!options.tenantId || !options.clientId) {
|
||||
throw new Error("tenantId and clientId are required for DeviceCodeCredential");
|
||||
throw new Error(
|
||||
"tenantId and clientId are required for DeviceCodeCredential",
|
||||
);
|
||||
}
|
||||
return new DeviceCodeCredential({
|
||||
tenantId: options.tenantId,
|
||||
@@ -45,18 +56,13 @@ function fileCachePlugin(cachePath) {
|
||||
return {
|
||||
beforeCacheAccess: async (ctx) => {
|
||||
if (fs.existsSync(cachePath)) {
|
||||
ctx.tokenCache.deserialize(
|
||||
fs.readFileSync(cachePath, "utf8")
|
||||
);
|
||||
ctx.tokenCache.deserialize(fs.readFileSync(cachePath, "utf8"));
|
||||
}
|
||||
},
|
||||
afterCacheAccess: async (ctx) => {
|
||||
if (ctx.cacheHasChanged) {
|
||||
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
cachePath,
|
||||
ctx.tokenCache.serialize()
|
||||
);
|
||||
fs.writeFileSync(cachePath, ctx.tokenCache.serialize());
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -72,16 +78,22 @@ function generatePkce() {
|
||||
return { verifier, challenge, challengeMethod: "S256" };
|
||||
}
|
||||
|
||||
export async function loginInteractive({ tenantId, clientId, scopes }) {
|
||||
export async function loginInteractive({ appName, tenantId, clientId, scopes }) {
|
||||
if (!tenantId) throw new Error("tenantId is required");
|
||||
if (!clientId) throw new Error("clientId is required");
|
||||
if (!Array.isArray(scopes) || scopes.length === 0)
|
||||
throw new Error("scopes[] is required");
|
||||
|
||||
// Make app name lowercase with all non-alphanumeric characters removed
|
||||
// spaces replaced with dashes and all letters converted to lowercase
|
||||
const sanitizedAppName = (appName || "Azure Node Login")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-");
|
||||
|
||||
const cachePath = path.join(
|
||||
os.homedir(),
|
||||
".config/azure-node-playground",
|
||||
`${clientId}-token-cache.json`
|
||||
`.config/${sanitizedAppName}`,
|
||||
`${clientId}-token-cache.json`,
|
||||
);
|
||||
|
||||
const pca = new PublicClientApplication({
|
||||
@@ -142,7 +154,9 @@ export async function loginInteractive({ tenantId, clientId, scopes }) {
|
||||
|
||||
resolve(token);
|
||||
} catch (e) {
|
||||
try { server.close(); } catch {}
|
||||
try {
|
||||
server.close();
|
||||
} catch {}
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
@@ -160,10 +174,19 @@ export async function loginInteractive({ tenantId, clientId, scopes }) {
|
||||
codeChallengeMethod: pkce.challengeMethod,
|
||||
});
|
||||
|
||||
try { await open(authUrl, { wait: false }); } catch {}
|
||||
console.log("If the browser didn't open, visit:\n" + authUrl);
|
||||
try {
|
||||
await open(authUrl, {
|
||||
wait: false,
|
||||
app: {
|
||||
name: apps.edge, // Enforce using Microsoft Edge browser
|
||||
},
|
||||
});
|
||||
} catch {}
|
||||
console.log("Visit:\n" + authUrl);
|
||||
} catch (e) {
|
||||
try { server.close(); } catch {}
|
||||
try {
|
||||
server.close();
|
||||
} catch {}
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
|
||||
70
src/graph.js
Normal file
70
src/graph.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Client } from "@microsoft/microsoft-graph-client";
|
||||
import { loginInteractive } from "./azure.js";
|
||||
|
||||
export async function getGraphClient({ tenantId, clientId }) {
|
||||
const graphApiToken = await loginInteractive({
|
||||
tenantId,
|
||||
clientId,
|
||||
scopes: ["https://graph.microsoft.com/.default"],
|
||||
});
|
||||
|
||||
const client = Client.init({
|
||||
authProvider: (done) => {
|
||||
done(null, graphApiToken.accessToken);
|
||||
},
|
||||
});
|
||||
|
||||
return { graphApiToken, client };
|
||||
}
|
||||
|
||||
export async function getApp(client, appName) {
|
||||
const result = await client
|
||||
.api("/applications")
|
||||
.filter(`displayName eq '${appName}'`)
|
||||
.get();
|
||||
|
||||
// Return the first application found or null if none exists
|
||||
return result.value.length > 0 ? result.value[0] : null;
|
||||
}
|
||||
|
||||
export async function getServicePrincipal(client, appId) {
|
||||
const result = await client
|
||||
.api("/servicePrincipals")
|
||||
.filter(`appId eq '${appId}'`)
|
||||
.get();
|
||||
|
||||
// Return the first service principal found or null if none exists
|
||||
return result.value.length > 0 ? result.value[0] : null;
|
||||
}
|
||||
|
||||
export async function createApp(client, appName) {
|
||||
const app = await client.api("/applications").post({
|
||||
displayName: appName,
|
||||
});
|
||||
|
||||
if (!app || !app.appId) {
|
||||
throw new Error("Failed to create application");
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function createSp(client, appId) {
|
||||
const sp = await client.api("/servicePrincipals").post({
|
||||
appId,
|
||||
});
|
||||
|
||||
if (!sp || !sp.id) {
|
||||
throw new Error("Failed to create service principal");
|
||||
}
|
||||
|
||||
return sp;
|
||||
}
|
||||
|
||||
export async function deleteSp(client, spId) {
|
||||
await client.api(`/servicePrincipals/${spId}`).delete();
|
||||
}
|
||||
|
||||
export async function deleteApp(client, appObjectId) {
|
||||
await client.api(`/applications/${appObjectId}`).delete();
|
||||
}
|
||||
Reference in New Issue
Block a user