Skip to content

@azure/identity-TokenCredential #371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
999b114
Adding token credential auth provider
nikithauc Sep 25, 2020
9e4db10
testing with samplenpm
nikithauc Sep 29, 2020
0dab297
Adding client secret cred flow
nikithauc Nov 13, 2020
6e74cda
Adding unit tests
nikithauc Nov 28, 2020
a56a103
package json change
nikithauc Nov 29, 2020
7f12ab6
Adding readme docs
nikithauc Nov 29, 2020
d70b08a
Adding project references from spec and aut
nikithauc Dec 16, 2020
ba0947d
temporarily resetting package json
nikithauc Dec 23, 2020
40e1a43
Merge with dev
nikithauc Dec 23, 2020
862081c
Updating to isomorphic-fetch 3.00, commenting some tests
nikithauc Dec 23, 2020
d89f994
Exporting authProviders from lib folder
nikithauc Dec 23, 2020
8c57c0a
Exporting authProviders from lib folder
nikithauc Dec 23, 2020
2cfaf69
Keywords, msal files path change
nikithauc Jan 3, 2021
0bcb659
Resetting file, removing empty references
nikithauc Jan 3, 2021
6f6c690
Merge branch 'dev' into Authentication
nikithauc Jan 4, 2021
39d242e
Create versionTest.yml
nikithauc Jan 5, 2021
1967788
Delete versionTest.yml
nikithauc Jan 5, 2021
e169e3c
Merging with 3.0.0
nikithauc Jan 7, 2021
48d5a01
Merge branch 'Authentication' of https://github.com/microsoftgraph/ms…
nikithauc Jan 7, 2021
a7e1a62
merge with 3.0.0
nikithauc Jan 7, 2021
7da0d9f
refactoring with error conditions and test merge
nikithauc Jan 12, 2021
c61af2e
Adding note and karma file path
nikithauc Jan 12, 2021
571bdaf
adding js sample
nikithauc Jan 13, 2021
dfce4fd
Correcting doc language errors
nikithauc Jan 13, 2021
7e39e1b
Update docs/TokenCredentialAuthenticationProvider.md
nikithauc Jan 13, 2021
fee04ec
Update docs/TokenCredentialAuthenticationProvider.md
nikithauc Jan 20, 2021
3a2fe1b
Update samples/tokenCredentialSamples/ClientCredentialFlow/README.md
nikithauc Jan 20, 2021
6c296a0
Re-adding peerdependency meta in package.json
nikithauc Jan 21, 2021
c9aff66
Merge branch 'Authentication' of https://github.com/microsoftgraph/ms…
nikithauc Jan 21, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ npm-debug.log
/lib/*
!/lib/.npmignore

/authProviders/*

src/**/*.js
src/**/*.js.map
src/**/*.d.ts

samples/**/secrets.ts
samples/**/secrets.js
samples/node/secrets.json
samples/browser/src/secrets.js
samples/browser/src/graph-js-sdk.js
Expand Down
59 changes: 5 additions & 54 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,64 +55,15 @@ Register your application to use Microsoft Graph API using one of the following

### 2. Authenticate for the Microsoft Graph service

The Microsoft Graph JavaScript Client Library has an adapter implementation ([ImplicitMSALAuthenticationProvider](src/ImplicitMSALAuthenticationProvider.ts)) for [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core) (Microsoft Authentication Library) which takes care of getting the `accessToken`. MSAL library does not ship with this library, user has to include it externally (For including MSAL, refer [this](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core#installation)).
The Microsoft Graph JavaScript Client Library has an adapter implementation for the following -

> **Important Note:** MSAL is supported only for frontend applications, for server-side authentication you have to implement your own AuthenticationProvider. Learn how you can create a [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md).
- ([TokenCredentialAuthenticationProvider](src/authentication/TokenCredentialAuthenticationProvider.ts)) to support [Azure Identity TokenCredential](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md) (Azure Identity client library for JavaScript) which takes care of getting the `accessToken`. @azure/identity library does not ship with this library, user has to include it externally (For including @azure/identity, refer [this](https://www.npmjs.com/package/@azure/identity)).

#### Creating an instance of ImplicitMSALAuthenticationProvider in browser environment
> Learn how to [create an instance of TokenCredentialAuthenticationProvider](./docs/TokenCredentialAuthenticationProvider.md).

Refer devDependencies in [package.json](./package.json) for the compatible msal version and update that version in below.
- ([ImplicitMSALAuthenticationProvider](src/ImplicitMSALAuthenticationProvider.ts)) for [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core) (Microsoft Authentication Library) which takes care of getting the `accessToken`. MSAL library does not ship with this library, user has to include it externally (For including MSAL, refer [this](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core#installation)).

```html
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>
```

```typescript
// Configuration options for MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes

// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new Msal.UserAgentApplication(msalConfig);
const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, options);
```

#### Creating an instance of ImplicitMSALAuthenticationProvider in node environment

Refer devDependencies in [package.json](./package.json) for the compatible msal version and update that version in below.

```cmd
npm install msal@<version>
```

```typescript
import { UserAgentApplication } from "msal";

import { ImplicitMSALAuthenticationProvider } from "@microsoft/microsoft-graph-client/lib/src/ImplicitMSALAuthenticationProvider";
import { MSALAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProviderOptions";

// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes

// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new UserAgentApplication(msalConfig);
const options = new MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication, options);
```
> Learn how to [create an instance of ImplicitMSALAuthenticationProvider](./docs/ImplicitMSALAuthenticationProvider.md).

User can integrate own preferred authentication library by implementing `IAuthenticationProvider` interface. Refer implementing [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md).

Expand Down
5 changes: 5 additions & 0 deletions authProviderOptions/ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
The authProviderOptions/ folders contains barrels for exporting Authentication Provider options such as MSAL and Azure Identity Token Credentials.

[tsconfig-sub-cjs.json](../tsconfig-sub-es.json) and [tsconfig-sub-cjs.json](../tsconfig-sub-es.json) contains the config for transpiling the files to authProviders/ output folder.

This approach is used because of the limitations of creating a submodule structure - References - https://github.com/microsoft/TypeScript/issues/8305 https://github.com/microsoft/TypeScript/issues/33079
8 changes: 8 additions & 0 deletions authProviderOptions/azureTokenCredentials/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../lib/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
8 changes: 8 additions & 0 deletions authProviderOptions/es/azureTokenCredentials/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../../lib/es/src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider";
export * from "../../../lib/es/src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions";
9 changes: 9 additions & 0 deletions authProviderOptions/es/msal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/

export * from "../../../lib/es/src/authentication/msal/ImplicitMSALAuthenticationProvider";
export * from "../../../lib/es/src/authentication/msal/MSALAuthenticationProviderOptions";
8 changes: 8 additions & 0 deletions authProviderOptions/msal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "../../lib/src/authentication/msal/MSALAuthenticationProviderOptions";
export * from "../../lib/src/authentication/msal/ImplicitMSALAuthenticationProvider";
56 changes: 56 additions & 0 deletions docs/ImplicitMSALAuthenticationProvider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#### Creating an instance of ImplicitMSALAuthenticationProvider in browser environment

Refer devDependencies in [package.json](../package.json) for the compatible msal version and update that version in below.

**Important Note:** MSAL is supported only for frontend applications, for server-side authentication you either can use [TokenCredentialAuthenticationProvider](./TokenCredentialAuthenticationProvider.md) or implement your own AuthenticationProvider. Learn how you can create a [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md).

```html
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>
```

```typescript
// Configuration options for MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes

// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new Msal.UserAgentApplication(msalConfig);
const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, options);
```

#### Creating an instance of ImplicitMSALAuthenticationProvider in node environment

Refer devDependencies in [package.json](./package.json) for the compatible msal version and update that version in below.

```cmd
npm install msal@<version>
```

```typescript
import { UserAgentApplication } from "msal";

import { ImplicitMSALAuthenticationProvider, MSALAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/msal";

// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes

// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal

// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new UserAgentApplication(msalConfig);
const options = new MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication, options);
```
56 changes: 56 additions & 0 deletions docs/TokenCredentialAuthenticationProvider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#### Creating an instance of TokenCredentialAuthentication

###### Links for more information -

- [GitHub - Azure Identity client library for JavaScript ](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md)

- [npm - Azure Identity client library for JavaScript](https://www.npmjs.com/package/@azure/identity)

- Check the [tokenCredentialSamples folder][../samples/tokencredentialsamples]. The ClientSecretCredentialFlow is an example of using TokenCredential to authenticate a node application. The AuthenticationCodeFlow is an example of using TokenCredential to authenticate a browser application.

**Important Note:** TokenCredentials can be used to authenticate browser and node applications.

###### Example of how to create and pass a token credential -

```typescript
// Import the TokenCredential class that you wish to use. This example uses a Client SecretCredential

import { ClientSecretCredential } from "@azure/identity";
import { TokenCredentialAuthenticationProvider, TokenCredentialAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials";

// Create an instance of the TokenCredential class that is imported
const tokenCredential = new ClientSecretCredential("your_tenantId", "your_clientId", "your_clientSecret");

// Set your scopes and options for TokenCredential.getToken (Check the ` interface GetTokenOptions` in (TokenCredential Implementation)[https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/core/core-auth/src/tokenCredential.ts])

const options: TokenCredentialAuthenticationProviderOptions = { scopes: [scopes], getTokenOptions };

// Create an instance of the TokenCredentialAuthenticationProvider by passing the tokenCredential instance and options to the constructor
const authProvider = new TokenCredentialAuthenticationProvider(tokenCredential, options);
const client = Client.initWithMiddleware({
debugLogging: true,
authProvider: authProvider,
});
const res = await client.api("/users/").get();
```

```javascript
// Import the TokenCredential class that you wish to use. This examples uses a ClientSecretCredential

const { ClientSecretCredential } = require("@azure/identity");
const { Client } = require("@microsoft/microsoft-graph-client");
const { TokenCredentialAuthenticationProvider } = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials");

// Create an instance of the TokenCredential class that is imported
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// Set your scopes and options for TokenCredential.getToken (Check the ` interface GetTokenOptions` in (TokenCredential Implementation)[https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/core/core-auth/src/tokenCredential.ts])

const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: [scopes] });

const client = Client.initWithMiddleware({
debugLogging: true,
authProvider,
});
const res = await client.api("/users/").get();
```
138 changes: 69 additions & 69 deletions docs/content/Batching.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,79 +66,79 @@ const serialBatching = async function(elem) {
};
```

### Download multiple profile photos with batching and preprocess these for rendering in a browser
### Download multiple profile photos with batching and preprocess these for rendering in a browser

You should convert the downloaded photos through batching to a Base64 representation if you want to render these in a browser.

```typescript
b64toBlob = async (b64Data:any, contentType:string, sliceSize?:number):Promise<Blob> => {
contentType = contentType || 'image/png';
sliceSize = sliceSize || 512;
let byteCharacters:string = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
let blob = new Blob(byteArrays, {type: contentType});
return blob;
};
blobToBase64 = (blob: Blob): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = _ => {
resolve(reader.result as string);
};
reader.readAsDataURL(blob);
});
};

downloadPhotosBatching = async (client: Client) => {
try {
let users = ["[email protected]", "[email protected]"]
// create batch request steps for the users specified above
const batchRequestSteps : BatchRequestStep[] = users.map((userId) => {
const request : BatchRequestStep = {
id: userId,
request: new Request(`/users/${userId}/photo/$value`, {
method: "GET",
})
};
return request;
})
// initiate the batchrequest and execute the operation
const batchRequestContent = new BatchRequestContent(batchRequestSteps);
const content = await batchRequestContent.getContent();
const batchResponse = new BatchResponseContent(await client.api("/$batch").post(content));
// example on how to retrieve the base64 representation of the downloaded image for the first user
const response = batchResponse.getResponseById(users[0]);
if (response.ok) {
var data = await response.text();
const binToBlob = await this.b64toBlob((data),'img/jpg');
// you can associate the base64 output to an src attribute of an <img> HTML tag
const base64Result = await this.blobToBase64(binToBlob);
console.log(base64Result);
}
} catch (error) {
console.error(error);
}
};
b64toBlob = async (b64Data: any, contentType: string, sliceSize?: number): Promise<Blob> => {
contentType = contentType || "image/png";
sliceSize = sliceSize || 512;

let byteCharacters: string = atob(b64Data);
let byteArrays = [];

for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);

let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}

let blob = new Blob(byteArrays, { type: contentType });
return blob;
};

blobToBase64 = (blob: Blob): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = (_) => {
resolve(reader.result as string);
};
reader.readAsDataURL(blob);
});
};

downloadPhotosBatching = async (client: Client) => {
try {
let users = ["[email protected]", "[email protected]"];

// create batch request steps for the users specified above
const batchRequestSteps: BatchRequestStep[] = users.map((userId) => {
const request: BatchRequestStep = {
id: userId,
request: new Request(`/users/${userId}/photo/$value`, {
method: "GET",
}),
};
return request;
});

// initiate the batchrequest and execute the operation
const batchRequestContent = new BatchRequestContent(batchRequestSteps);
const content = await batchRequestContent.getContent();
const batchResponse = new BatchResponseContent(await client.api("/$batch").post(content));

// example on how to retrieve the base64 representation of the downloaded image for the first user
const response = batchResponse.getResponseById(users[0]);
if (response.ok) {
var data = await response.text();
const binToBlob = await this.b64toBlob(data, "img/jpg");

// you can associate the base64 output to an src attribute of an <img> HTML tag
const base64Result = await this.blobToBase64(binToBlob);
console.log(base64Result);
}
} catch (error) {
console.error(error);
}
};
```

### GET and POST contents from and to different workloads - Making parallel requests
Expand Down
Loading