From 9651b096b80d7e437a92266d2f5d16f75c9eb03a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Rodr=C3=ADguez?= Date: Thu, 17 Dec 2020 19:43:11 -0500 Subject: [PATCH] [Identity] More standard samples (#12800) * [Identity] More standard samples * missing files * Feedback and other cleanups * removing device code and interactive samples because of user input * more info on how to set up the keyvault * apiref fix * using-azure-identity.md fix * no more tsconfig.samples.json * fixed version * wip * now it should work * formatting * Skipped the build samples step for now. Will log an issue. Skipped the build samples step for now. Will log an issue. * pnpm-lock after merge master * removing kv keys from package.json --- common/config/rush/pnpm-lock.yaml | 27 ++++-- documentation/using-azure-identity.md | 2 +- sdk/identity/identity/.gitignore | 1 - sdk/identity/identity/package.json | 7 +- sdk/identity/identity/samples/.gitkeep | 0 .../samples/ClientSideUserAuthentication.md | 2 +- .../identity/samples/javascript/README.md | 79 ++++++++++++++++ .../javascript/clientSecretCredential.js | 28 ++++++ .../javascript/defaultAzureCredential.js | 32 +++++++ .../javascript/environmentCredential.js | 28 ++++++ .../identity/samples/javascript/package.json | 35 +++++++ .../identity/samples/javascript/sample.env | 8 ++ .../{ => manual}/authorizationCodeSample.ts | 0 sdk/identity/identity/samples/sample.env | 4 - sdk/identity/identity/samples/tsconfig.json | 4 +- .../identity/samples/typescript/README.md | 92 +++++++++++++++++++ .../identity/samples/typescript/package.json | 41 +++++++++ .../identity/samples/typescript/sample.env | 8 ++ .../typescript/src/clientSecretCredential.ts | 28 ++++++ .../typescript/src/defaultAzureCredential.ts | 32 +++++++ .../typescript/src/environmentCredential.ts | 28 ++++++ .../identity/samples/typescript/tsconfig.json | 15 +++ .../authorizationCodeCredential.ts | 4 +- 23 files changed, 485 insertions(+), 20 deletions(-) delete mode 100644 sdk/identity/identity/samples/.gitkeep create mode 100644 sdk/identity/identity/samples/javascript/README.md create mode 100644 sdk/identity/identity/samples/javascript/clientSecretCredential.js create mode 100644 sdk/identity/identity/samples/javascript/defaultAzureCredential.js create mode 100644 sdk/identity/identity/samples/javascript/environmentCredential.js create mode 100644 sdk/identity/identity/samples/javascript/package.json create mode 100644 sdk/identity/identity/samples/javascript/sample.env rename sdk/identity/identity/samples/{ => manual}/authorizationCodeSample.ts (100%) delete mode 100644 sdk/identity/identity/samples/sample.env create mode 100644 sdk/identity/identity/samples/typescript/README.md create mode 100644 sdk/identity/identity/samples/typescript/package.json create mode 100644 sdk/identity/identity/samples/typescript/sample.env create mode 100644 sdk/identity/identity/samples/typescript/src/clientSecretCredential.ts create mode 100644 sdk/identity/identity/samples/typescript/src/defaultAzureCredential.ts create mode 100644 sdk/identity/identity/samples/typescript/src/environmentCredential.ts create mode 100644 sdk/identity/identity/samples/typescript/tsconfig.json diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 2a7f0bdfa08e..c91460ca1ad2 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -182,6 +182,20 @@ packages: dev: false resolution: integrity: sha512-CxaMaEjwtsmIhWtjHyGimKO7RmES0YxPqGQ9+jKqGygNlhG5NYHktDaiQu6w7k3g+I51VaLXtVSt+BVFd6VWfQ== + /@azure/keyvault-keys/4.1.0: + dependencies: + '@azure/core-http': 1.2.1 + '@azure/core-lro': 1.0.2 + '@azure/core-paging': 1.1.3 + '@azure/core-tracing': 1.0.0-preview.9 + '@azure/logger': 1.0.0 + '@opentelemetry/api': 0.10.2 + tslib: 2.0.3 + dev: false + engines: + node: '>=8.0.0' + resolution: + integrity: sha512-xdz7nkYulWSo2+CsBRxaOe2JrGWQP3WxEjPLdIzZNHyaYBuLlnKHL3XWYH5j0UUVoDcmQClZUlZ2P/kdOiy/aQ== /@azure/logger-js/1.3.2: dependencies: tslib: 1.14.1 @@ -9368,6 +9382,7 @@ packages: 'file:projects/identity.tgz': dependencies: '@azure/core-tracing': 1.0.0-preview.9 + '@azure/keyvault-keys': 4.1.0 '@azure/msal-node': 1.0.0-beta.1 '@microsoft/api-extractor': 7.7.11 '@opentelemetry/api': 0.10.2 @@ -9423,7 +9438,7 @@ packages: optionalDependencies: keytar: 5.6.0 resolution: - integrity: sha512-WJOJ7+HD7LnQmOEszTRNvDTlQq6GfsgMF/5Lga38trgkCYvZziYq3Wpj77zpPXKoijUklAkkPrUQMd6T1OtuwA== + integrity: sha512-ZCzaGxJsU3n67T2O+8DtrTWeuFg6gBOwA64vLE07BgvTuLYeJL2KPawcSq1EUgaVAJz/yfOsOSSy6voyC7ORvw== tarball: 'file:projects/identity.tgz' version: 0.0.0 'file:projects/keyvault-admin.tgz': @@ -9556,7 +9571,7 @@ packages: dev: false name: '@rush-temp/keyvault-common' resolution: - integrity: sha512-wGsIDNLQxOtmtG36q4jZFT5fe+tIn2u1IJ0eKEOdafLAt4ij8y0T61EYKt0Szy2P/5KPUjXf71L+Gn3YKp1ajg== + integrity: sha512-2zFAKDUWUYLbduUtaBOYxIq4aazqkzh3KfJF1MgY6fpYifMMRdaYHqUMng/IGu+MBZfJdzV+Upsi518u4Ldfsg== tarball: 'file:projects/keyvault-common.tgz' version: 0.0.0 'file:projects/keyvault-keys.tgz': @@ -10273,7 +10288,7 @@ packages: dev: false name: '@rush-temp/storage-internal-avro' resolution: - integrity: sha512-K2Ewnm3Ca4h8KMWzAEJGQW3JjbkcfH7+WmHQwWPdlO1Juqqu6oHY2aPt6o+1o37SKg9eNxe9Ov1qvewgOvirRA== + integrity: sha512-dbfd9Yi+PhwWkq+wQglScXEzEwuK57J9ghvGzcLl/YjEb8xiBP9tcCJFuQHiL09kYjjWXo1ovp6YxGDtwTFnmA== tarball: 'file:projects/storage-internal-avro.tgz' version: 0.0.0 'file:projects/storage-queue.tgz': @@ -10495,7 +10510,7 @@ packages: dev: false name: '@rush-temp/test-utils-perfstress' resolution: - integrity: sha512-gMGFoDklp2uuxwqIPE+qmYDHS/rjhhkQA7tsMlLuLAcoCApMXUJa51w8Am+hF8XWgQmPne9RcMghBHGFTnkWHQ== + integrity: sha512-sm36kIhCNYBbbMAWgDDyE0pUlOyFhC3q5fbvFkAVoQVowfZ8IJK//1jQsEI3z0yB5bNHJR+rw+QaWgldrkB46w== tarball: 'file:projects/test-utils-perfstress.tgz' version: 0.0.0 'file:projects/test-utils-recorder.tgz': @@ -10553,7 +10568,7 @@ packages: dev: false name: '@rush-temp/test-utils-recorder' resolution: - integrity: sha512-djCe32KpPT8TTJ7k/W/bdzDJ4UEo0Rz5bJtsNQOlqaD+MVwedY6Bi+HkKcdyCTlUZ5voabCQwixJAuIvsGxOTw== + integrity: sha512-WEfRyUxdNUxn8+8eedpTcgdFv7ARQ2N/Y+ILJQuHjEJY1mY11+CAbTOXMod2r76fmJs6KkeIunHWpU6Y95X8Xg== tarball: 'file:projects/test-utils-recorder.tgz' version: 0.0.0 'file:projects/testhub.tgz': @@ -10576,7 +10591,7 @@ packages: dev: false name: '@rush-temp/testhub' resolution: - integrity: sha512-H+vYaFnYiRChkB0tGH5+DP/KFMLNXsogMJbkDFRbZccdMPKexg+zRX35PWzwNyWiOQ7K4SNXNRzaGJGbOjcRxg== + integrity: sha512-o7zYyw6/QJHBg2/e3mbbeOe+ohKdRse2FU1aX4i7AdO+1337l44mWy1DwVWhcFUy5aSzahd194/6nrgp7Sj6JQ== tarball: 'file:projects/testhub.tgz' version: 0.0.0 registry: '' diff --git a/documentation/using-azure-identity.md b/documentation/using-azure-identity.md index b32edfe0b715..2a48c17804de 100644 --- a/documentation/using-azure-identity.md +++ b/documentation/using-azure-identity.md @@ -310,7 +310,7 @@ locally, you can also add a redirect URI for your development endpoint A complete example of hosting your own authentication response endpoint can be found in the [`authorization code -sample`](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/authorizationCodeSample.ts). +sample`](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/manual/authorizationCodeSample.ts). ### DefaultAzureCredential diff --git a/sdk/identity/identity/.gitignore b/sdk/identity/identity/.gitignore index 7d8f89d82e75..93cf72c40335 100644 --- a/sdk/identity/identity/.gitignore +++ b/sdk/identity/identity/.gitignore @@ -1,2 +1 @@ src/**/*.js -samples/**/*.js \ No newline at end of file diff --git a/sdk/identity/identity/package.json b/sdk/identity/identity/package.json index 3dcd87b74577..14105d78d130 100644 --- a/sdk/identity/identity/package.json +++ b/sdk/identity/identity/package.json @@ -22,16 +22,16 @@ "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", "build:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c 2>&1", "build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1", - "build:samples": "cd samples && tsc -p .", + "build:samples": "echo skipped", "build:test:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c rollup.test.config.js 2>&1", "build:test:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c rollup.test.config.js 2>&1", "build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1", "build": "npm run extract-api && tsc -p . && rollup -c 2>&1", - "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\" \"samples/**/*.{js,json}\"", "clean": "rimraf dist dist-esm dist-browser test-dist test-browser typings *.tgz *.log", "execute:samples": "echo skipped", "extract-api": "tsc -p . && api-extractor run --local", - "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\" \"samples/**/*.{js,json}\"", "integration-test:browser": "echo skipped", "integration-test:node": "echo skipped", "integration-test": "npm run integration-test:node && npm run integration-test:browser", @@ -100,6 +100,7 @@ "devDependencies": { "@azure/eslint-plugin-azure-sdk": "^3.0.0", "@azure/abort-controller": "^1.0.0", + "@azure/dev-tool": "^1.0.0", "@microsoft/api-extractor": "7.7.11", "@rollup/plugin-commonjs": "11.0.2", "@rollup/plugin-json": "^4.0.0", diff --git a/sdk/identity/identity/samples/.gitkeep b/sdk/identity/identity/samples/.gitkeep deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/sdk/identity/identity/samples/ClientSideUserAuthentication.md b/sdk/identity/identity/samples/ClientSideUserAuthentication.md index d0449da895f9..7ea4012df421 100644 --- a/sdk/identity/identity/samples/ClientSideUserAuthentication.md +++ b/sdk/identity/identity/samples/ClientSideUserAuthentication.md @@ -51,7 +51,7 @@ async function main() { ); const client = new BlobServiceClient("https://myaccount.blob.core.windows.net/mycontainer/myblob", credential); - const containerClient = blobServiceClient.getContainerClient(""); + const containerClient = client.getContainerClient(""); const createContainerResponse = await containerClient.create(); console.log(`Successfully created a container`, createContainerResponse.requestId); } diff --git a/sdk/identity/identity/samples/javascript/README.md b/sdk/identity/identity/samples/javascript/README.md new file mode 100644 index 000000000000..4bc829b75cfe --- /dev/null +++ b/sdk/identity/identity/samples/javascript/README.md @@ -0,0 +1,79 @@ +--- +page_type: sample +languages: + - javascript +products: + - azure + - azure-active-directory +urlFragment: identity-javascript +--- + +# Azure Identity library samples for JavaScript + +These sample programs show how to use the JavaScript client libraries for Azure Identity in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------------------------------ | --------------------------------------------------------------- | +| [defaultAzureCredential.js][defaultAzureCredential] | Tries several authentications. The simplest way to use @azure/identity | +| [clientSecretCredential.js][clientSecretCredential] | Authenticates with a client and a client's secret. | +| [environmentCredential.js][environmentCredential] | Authenticates with a client and a client's secret sent through environment variables. | + +## Prerequisites + +The samples are compatible with Node.js >= 8.0.0. + +You need [an Azure subscription][freesub] and [an Azure Key Vault][azkeyvault] to run these sample programs. + +To create an AAD application: + +- Follow [Documentation to register a new application](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) in the Azure Active Directory (in the Azure portal). +- Note down the `CLIENT_ID` and `TENANT_ID`. +- In the "Certificates & Secrets" tab, create a secret and note that down. + +To allow your registered application to access your Key Vault + +- In the Azure portal, go to your Azure Key Vault. +- In the left-side-navbar of your Azure Key Vault in the Azure portal, go to the `Access Policies` section, then click the `+ Add Access Policy` button. +- In the `Add access policy` page, select all the permissions for Keys, Secrets and Certificates. +- For the `Select principal` field, click on the `None selected`. A panel will appear at the right of the window. Search for your Azure Active Directory application, click the application on the search results, then click "Select" at the bottom. +- Once your application is selected, click the "Add" button. +- Click the `Save` button at the top of the Access Policies section of your Key Vault. +- For more information on securing your Key Vault: [Learn more](https://docs.microsoft.com/azure/key-vault/general/secure-your-key-vault) + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +3. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node helloWorld.js +``` + +Alternatively, run a single sample with the correct environment variables set (step 2 is not required if you do this), for example (cross-platform): + +```bash +npx cross-env KEYVAULT_NAME="" AZURE_TENANT_ID="" AZURE_CLIENT_ID="" AZURE_CLIENT_SECRET="" node environmentCredential.js +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[defaultAzureCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/javascript/defaultAzureCredential.js +[clientSecretCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/javascript/clientSecretCredential.js +[environmentCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/javascript/environmentCredential.js +[apiref]: https://docs.microsoft.com/javascript/api/@azure/identity +[azkeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal +[freesub]: https://azure.microsoft.com/free/ +[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity/README.md diff --git a/sdk/identity/identity/samples/javascript/clientSecretCredential.js b/sdk/identity/identity/samples/javascript/clientSecretCredential.js new file mode 100644 index 000000000000..94beda58a8fb --- /dev/null +++ b/sdk/identity/identity/samples/javascript/clientSecretCredential.js @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +const { ClientSecretCredential } = require("@azure/identity"); +const { KeyClient } = require("@azure/keyvault-keys"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + const credential = new ClientSecretCredential( + process.env.AZURE_TENANT_ID, // The tenant ID in Azure Active Directory + process.env.AZURE_CLIENT_ID, // The application (client) ID registered in the AAD tenant + process.env.AZURE_CLIENT_SECRET // The client secret for the registered application + ); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/javascript/defaultAzureCredential.js b/sdk/identity/identity/samples/javascript/defaultAzureCredential.js new file mode 100644 index 000000000000..e67480198464 --- /dev/null +++ b/sdk/identity/identity/samples/javascript/defaultAzureCredential.js @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +const { DefaultAzureCredential } = require("@azure/identity"); +const { KeyClient } = require("@azure/keyvault-keys"); + +// Load the .env file if it exists +require("dotenv").config(); + +/** + * The `DefaultAzureCredential` is appropriate for most scenarios where the application is intended to ultimately be run in the Azure Cloud. + * This is because the `DefaultAzureCredential` combines credentials commonly used to authenticate when deployed, + * with credentials used to authenticate in a development environment. + * + * For more information, you may go to our readme: [link](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#defaultazurecredential) + */ + +async function main() { + const credential = new DefaultAzureCredential(); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/javascript/environmentCredential.js b/sdk/identity/identity/samples/javascript/environmentCredential.js new file mode 100644 index 000000000000..fdfe5370c189 --- /dev/null +++ b/sdk/identity/identity/samples/javascript/environmentCredential.js @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +const { EnvironmentCredential } = require("@azure/identity"); +const { KeyClient } = require("@azure/keyvault-keys"); + +// Load the .env file if it exists +require("dotenv").config(); + +async function main() { + // EnvironmentCredential expects the following three environment variables: + // - AZURE_TENANT_ID: The tenant ID in Azure Active Directory + // - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant + // - AZURE_CLIENT_SECRET: The client secret for the registered application + const credential = new EnvironmentCredential(); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/javascript/package.json b/sdk/identity/identity/samples/javascript/package.json new file mode 100644 index 000000000000..196cf17cca3e --- /dev/null +++ b/sdk/identity/identity/samples/javascript/package.json @@ -0,0 +1,35 @@ +{ + "name": "azure-identity-samples-js", + "private": true, + "version": "0.1.0", + "description": "Azure Identity client library samples for JavaScript", + "engine": { + "node": ">=8.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git" + }, + "keywords": [ + "Azure", + "Identity", + "AAD", + "Node.js", + "JavaScript" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js#readme", + "sideEffects": false, + "dependencies": { + "@azure/identity": "latest", + "@azure/keyvault-keys": "4.1.0", + "dotenv": "^8.2.0" + }, + "devDependencies": { + "rimraf": "^3.0.0" + } +} diff --git a/sdk/identity/identity/samples/javascript/sample.env b/sdk/identity/identity/samples/javascript/sample.env new file mode 100644 index 000000000000..95ba051a2196 --- /dev/null +++ b/sdk/identity/identity/samples/javascript/sample.env @@ -0,0 +1,8 @@ +# The name of the key vault to use in the samples. +# Create a Key Vault in the Azure Portal and enter its URI (e.g. https://mytest.vault.azure.net/) here. +KEYVAULT_URI= + +# Used by some of the credentials to authenticate using Azure AD as a service principal for role-based authentication. +AZURE_TENANT_ID= +AZURE_CLIENT_ID= +AZURE_CLIENT_SECRET= diff --git a/sdk/identity/identity/samples/authorizationCodeSample.ts b/sdk/identity/identity/samples/manual/authorizationCodeSample.ts similarity index 100% rename from sdk/identity/identity/samples/authorizationCodeSample.ts rename to sdk/identity/identity/samples/manual/authorizationCodeSample.ts diff --git a/sdk/identity/identity/samples/sample.env b/sdk/identity/identity/samples/sample.env deleted file mode 100644 index 962180bdf228..000000000000 --- a/sdk/identity/identity/samples/sample.env +++ /dev/null @@ -1,4 +0,0 @@ -PORT="8080" -AZURE_TENANT_ID="" -AZURE_CLIENT_ID="" -AZURE_CLIENT_SECRET="" diff --git a/sdk/identity/identity/samples/tsconfig.json b/sdk/identity/identity/samples/tsconfig.json index 40f5e2f86c4f..8d5707a03e55 100644 --- a/sdk/identity/identity/samples/tsconfig.json +++ b/sdk/identity/identity/samples/tsconfig.json @@ -7,8 +7,8 @@ "declarationDir": null, "sourceMap": false, "inlineSources": false, - "outDir": "../" + "outDir": "samples/typescript/dist" }, - "include": ["**/*.ts"], + "include": ["typescript/**/*.ts"], "exclude": ["src/**/*", "test/**/*"] } diff --git a/sdk/identity/identity/samples/typescript/README.md b/sdk/identity/identity/samples/typescript/README.md new file mode 100644 index 000000000000..eb549b9ebdd4 --- /dev/null +++ b/sdk/identity/identity/samples/typescript/README.md @@ -0,0 +1,92 @@ +--- +page_type: sample +languages: + - typescript +products: + - azure + - azure-active-directory +urlFragment: identity-typescript +--- + +# Azure Identity library samples for TypeScript + +These sample programs show how to use the TypeScript client libraries for Azure Identity in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------- | ---------------------------------------------------------------- | +| [defaultAzureCredential.ts][defaultAzureCredential] | Tries several authentications. The simplest way to use @azure/identity | +| [clientSecretCredential.ts][clientSecretCredential] | Authenticates with a client and a client's secret. | +| [environmentCredential.ts][environmentCredential] | Authenticates with a client and a client's secret sent through environment variables. | + +## Prerequisites + +The samples are compatible with Node.ts >= 8.0.0. + +Before running the samples in Node, they must be compiled to TypeScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using + +```bash +npm install -g typescript +``` + +You need [an Azure subscription][freesub] and [an Azure Key Vault][azkeyvault] to run these sample programs. + +To create an AAD application: + +- Follow [Documentation to register a new application](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) in the Azure Active Directory (in the Azure portal). +- Note down the `CLIENT_ID` and `TENANT_ID`. +- In the "Certificates & Secrets" tab, create a secret and note that down. + +To allow your registered application to access your Key Vault + +- In the Azure portal, go to your Azure Key Vault. +- In the left-side-navbar of your Azure Key Vault in the Azure portal, go to the `Access Policies` section, then click the `+ Add Access Policy` button. +- In the `Add access policy` page, select all the permissions for Keys, Secrets and Certificates. +- For the `Select principal` field, click on the `None selected`. A panel will appear at the right of the window. Search for your Azure Active Directory application, click the application on the search results, then click "Select" at the bottom. +- Once your application is selected, click the "Add" button. +- Click the `Save` button at the top of the Access Policies section of your Key Vault. +- For more information on securing your Key Vault: [Learn more](https://docs.microsoft.com/azure/key-vault/general/secure-your-key-vault) + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Compile the samples + +```bash +npm run build +``` + +3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +4. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node dist/helloWorld.ts +``` + +Alternatively, run a single sample with the correct environment variables set (step 3 is not required if you do this), for example (cross-platform): + +```bash +npx cross-env KEYVAULT_NAME="" AZURE_TENANT_ID="" AZURE_CLIENT_ID="" AZURE_CLIENT_SECRET="" node dist/environmentCredential.ts +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[defaultAzureCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/typescript/src/defaultAzureCredential.ts +[clientSecretCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/typescript/src/clientSecretCredential.ts +[environmentCredential]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/typescript/src/environmentCredential.ts +[apiref]: https://docs.microsoft.com/javascript/api/@azure/identity +[azkeyvault]: https://docs.microsoft.com/azure/key-vault/quick-create-portal +[freesub]: https://azure.microsoft.com/free/ +[package]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/keyvault/keyvault-keys/README.md +[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/identity/identity/samples/typescript/package.json b/sdk/identity/identity/samples/typescript/package.json new file mode 100644 index 000000000000..6aa0b39746fe --- /dev/null +++ b/sdk/identity/identity/samples/typescript/package.json @@ -0,0 +1,41 @@ +{ + "name": "azure-identity-samples-ts", + "private": true, + "version": "0.1.0", + "description": "Azure Identity Keys client library samples for TypeScript", + "engine": { + "node": ">=8.0.0" + }, + "scripts": { + "build": "tsc", + "prebuild": "rimraf dist/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git" + }, + "keywords": [ + "Azure", + "Identity", + "AAD", + "Node.js", + "TypeScript" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js#readme", + "sideEffects": false, + "dependencies": { + "@azure/identity": "latest", + "@azure/keyvault-keys": "4.1.0", + "dotenv": "^8.2.0" + }, + "devDependencies": { + "@types/node": "^8.0.0", + "rimraf": "^3.0.0", + "typescript": "~3.6.4" + } +} diff --git a/sdk/identity/identity/samples/typescript/sample.env b/sdk/identity/identity/samples/typescript/sample.env new file mode 100644 index 000000000000..95ba051a2196 --- /dev/null +++ b/sdk/identity/identity/samples/typescript/sample.env @@ -0,0 +1,8 @@ +# The name of the key vault to use in the samples. +# Create a Key Vault in the Azure Portal and enter its URI (e.g. https://mytest.vault.azure.net/) here. +KEYVAULT_URI= + +# Used by some of the credentials to authenticate using Azure AD as a service principal for role-based authentication. +AZURE_TENANT_ID= +AZURE_CLIENT_ID= +AZURE_CLIENT_SECRET= diff --git a/sdk/identity/identity/samples/typescript/src/clientSecretCredential.ts b/sdk/identity/identity/samples/typescript/src/clientSecretCredential.ts new file mode 100644 index 000000000000..5950679da79d --- /dev/null +++ b/sdk/identity/identity/samples/typescript/src/clientSecretCredential.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientSecretCredential } from "@azure/identity"; +import { KeyClient } from "@azure/keyvault-keys"; + +// Load the .env file if it exists +require("dotenv").config(); + +export async function main(): Promise { + const credential = new ClientSecretCredential( + process.env.AZURE_TENANT_ID!, // The tenant ID in Azure Active Directory + process.env.AZURE_CLIENT_ID!, // The application (client) ID registered in the AAD tenant + process.env.AZURE_CLIENT_SECRET! // The client secret for the registered application + ); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/typescript/src/defaultAzureCredential.ts b/sdk/identity/identity/samples/typescript/src/defaultAzureCredential.ts new file mode 100644 index 000000000000..50f458a766a4 --- /dev/null +++ b/sdk/identity/identity/samples/typescript/src/defaultAzureCredential.ts @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { DefaultAzureCredential } from "@azure/identity"; +import { KeyClient } from "@azure/keyvault-keys"; + +// Load the .env file if it exists +require("dotenv").config(); + +/** + * The `DefaultAzureCredential` is appropriate for most scenarios where the application is intended to ultimately be run in the Azure Cloud. + * This is because the `DefaultAzureCredential` combines credentials commonly used to authenticate when deployed, + * with credentials used to authenticate in a development environment. + * + * For more information, you may go to our readme: [link](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/identity/identity#defaultazurecredential) + */ + +export async function main(): Promise { + const credential = new DefaultAzureCredential(); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/typescript/src/environmentCredential.ts b/sdk/identity/identity/samples/typescript/src/environmentCredential.ts new file mode 100644 index 000000000000..7701e1c8466a --- /dev/null +++ b/sdk/identity/identity/samples/typescript/src/environmentCredential.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { EnvironmentCredential } from "@azure/identity"; +import { KeyClient } from "@azure/keyvault-keys"; + +// Load the .env file if it exists +require("dotenv").config(); + +export async function main(): Promise { + // EnvironmentCredential expects the following three environment variables: + // - AZURE_TENANT_ID: The tenant ID in Azure Active Directory + // - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant + // - AZURE_CLIENT_SECRET: The client secret for the registered application + const credential = new EnvironmentCredential(); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().catch((err) => { + console.log("error code: ", err.code); + console.log("error message: ", err.message); + console.log("error stack: ", err.stack); +}); diff --git a/sdk/identity/identity/samples/typescript/tsconfig.json b/sdk/identity/identity/samples/typescript/tsconfig.json new file mode 100644 index 000000000000..4332663bf7b7 --- /dev/null +++ b/sdk/identity/identity/samples/typescript/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + + "lib": ["dom", "dom.iterable", "esnext.asynciterable"], + + "allowSyntheticDefaultImports": true, + + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**.ts"], + "exclude": ["node_modules"] +} diff --git a/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts b/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts index 865c8134ad81..2aa38086e470 100644 --- a/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts +++ b/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts @@ -38,7 +38,7 @@ export class AuthorizationCodeCredential implements TokenCredential { * the authorization code flow to obtain an authorization code to be used * with this credential. A full example of this flow is provided here: * - * https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/authorizationCodeSample.ts + * https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/manual/authorizationCodeSample.ts * * @param tenantId - The Azure Active Directory tenant (directory) ID or name. * 'common' may be used when dealing with multi-tenant scenarios. @@ -68,7 +68,7 @@ export class AuthorizationCodeCredential implements TokenCredential { * the authorization code flow to obtain an authorization code to be used * with this credential. A full example of this flow is provided here: * - * https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/authorizationCodeSample.ts + * https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/manual/authorizationCodeSample.ts * * @param tenantId - The Azure Active Directory tenant (directory) ID or name. * 'common' may be used when dealing with multi-tenant scenarios.