Skip to content

Commit

Permalink
[Identity] More standard samples (#12800)
Browse files Browse the repository at this point in the history
* [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
  • Loading branch information
sadasant authored Dec 18, 2020
1 parent be0e835 commit 9651b09
Show file tree
Hide file tree
Showing 23 changed files with 485 additions and 20 deletions.
27 changes: 21 additions & 6 deletions common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion documentation/using-azure-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion sdk/identity/identity/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
src/**/*.js
samples/**/*.js
7 changes: 4 additions & 3 deletions sdk/identity/identity/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async function main() {
);
const client = new BlobServiceClient("https://myaccount.blob.core.windows.net/mycontainer/myblob", credential);

const containerClient = blobServiceClient.getContainerClient("<container-name>");
const containerClient = client.getContainerClient("<container-name>");
const createContainerResponse = await containerClient.create();
console.log(`Successfully created a container`, createContainerResponse.requestId);
}
Expand Down
79 changes: 79 additions & 0 deletions sdk/identity/identity/samples/javascript/README.md
Original file line number Diff line number Diff line change
@@ -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="<key vault name>" AZURE_TENANT_ID="<AAD tenant id>" AZURE_CLIENT_ID="<AAD client id>" AZURE_CLIENT_SECRET="<AAD 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
28 changes: 28 additions & 0 deletions sdk/identity/identity/samples/javascript/clientSecretCredential.js
Original file line number Diff line number Diff line change
@@ -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);
});
32 changes: 32 additions & 0 deletions sdk/identity/identity/samples/javascript/defaultAzureCredential.js
Original file line number Diff line number Diff line change
@@ -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);
});
28 changes: 28 additions & 0 deletions sdk/identity/identity/samples/javascript/environmentCredential.js
Original file line number Diff line number Diff line change
@@ -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);
});
35 changes: 35 additions & 0 deletions sdk/identity/identity/samples/javascript/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
8 changes: 8 additions & 0 deletions sdk/identity/identity/samples/javascript/sample.env
Original file line number Diff line number Diff line change
@@ -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=<key-vault-uri>

# Used by some of the credentials to authenticate using Azure AD as a service principal for role-based authentication.
AZURE_TENANT_ID=<AD tenant id or name>
AZURE_CLIENT_ID=<ID of the user/service principal to authenticate as>
AZURE_CLIENT_SECRET=<client secret used to authenticate to Azure AD>
4 changes: 0 additions & 4 deletions sdk/identity/identity/samples/sample.env

This file was deleted.

4 changes: 2 additions & 2 deletions sdk/identity/identity/samples/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
"declarationDir": null,
"sourceMap": false,
"inlineSources": false,
"outDir": "../"
"outDir": "samples/typescript/dist"
},
"include": ["**/*.ts"],
"include": ["typescript/**/*.ts"],
"exclude": ["src/**/*", "test/**/*"]
}
Loading

0 comments on commit 9651b09

Please sign in to comment.