-
Notifications
You must be signed in to change notification settings - Fork 232
@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
Changes from 22 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
999b114
Adding token credential auth provider
nikithauc 9e4db10
testing with samplenpm
nikithauc 0dab297
Adding client secret cred flow
nikithauc 6e74cda
Adding unit tests
nikithauc a56a103
package json change
nikithauc 7f12ab6
Adding readme docs
nikithauc d70b08a
Adding project references from spec and aut
nikithauc ba0947d
temporarily resetting package json
nikithauc 40e1a43
Merge with dev
nikithauc 862081c
Updating to isomorphic-fetch 3.00, commenting some tests
nikithauc d89f994
Exporting authProviders from lib folder
nikithauc 8c57c0a
Exporting authProviders from lib folder
nikithauc 2cfaf69
Keywords, msal files path change
nikithauc 0bcb659
Resetting file, removing empty references
nikithauc 6f6c690
Merge branch 'dev' into Authentication
nikithauc 39d242e
Create versionTest.yml
nikithauc 1967788
Delete versionTest.yml
nikithauc e169e3c
Merging with 3.0.0
nikithauc 48d5a01
Merge branch 'Authentication' of https://github.com/microsoftgraph/ms…
nikithauc a7e1a62
merge with 3.0.0
nikithauc 7da0d9f
refactoring with error conditions and test merge
nikithauc c61af2e
Adding note and karma file path
nikithauc 571bdaf
adding js sample
nikithauc dfce4fd
Correcting doc language errors
nikithauc 7e39e1b
Update docs/TokenCredentialAuthenticationProvider.md
nikithauc fee04ec
Update docs/TokenCredentialAuthenticationProvider.md
nikithauc 3a2fe1b
Update samples/tokenCredentialSamples/ClientCredentialFlow/README.md
nikithauc 6c296a0
Re-adding peerdependency meta in package.json
nikithauc c9aff66
Merge branch 'Authentication' of https://github.com/microsoftgraph/ms…
nikithauc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 have to can use [TokenCredentialAuthenticationProvider](./TokenCredentialAuthenticationProvider.md) or implement your own AuthenticationProvider. Learn how you can create a [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md). | ||
nikithauc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```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); | ||
ddyett marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
#### 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> | ||
nikithauc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``` | ||
|
||
```typescript | ||
import { UserAgentApplication } from "msal"; | ||
|
||
import { ImplicitMSALAuthenticationProvider } from "@microsoft/microsoft-graph-client/lib/src/authentication/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); | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
#### 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 authentication browser and node applications. | ||
nikithauc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
###### Example of how to create and pass a token credential sample - | ||
nikithauc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```typescript | ||
// Import the TokenCredential class that you wish to use. This examples uses a Client SecretCredential | ||
import { ClientSecretCredential } from "@azure/identity"; | ||
import { TokenCredentialAuthenticationProvider, TokenCredentialAuthenticationProviderOptions } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials"; | ||
nikithauc marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// 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(); | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,13 @@ | ||
module.exports = function(config) { | ||
config.set({ | ||
frameworks: ["mocha", "chai", "karma-typescript"], | ||
files: ["test/common/**/*.ts", "src/**/*.ts", "test/browser/**/*.ts", "test/*.ts"], | ||
preprocessors: { | ||
"**/*.ts": ["karma-typescript"], | ||
}, | ||
karmaTypescriptConfig: { | ||
tsconfig: "./tsconfig-cjs.json", | ||
}, | ||
browsers: ["ChromeHeadless"], | ||
}); | ||
}; | ||
config.set({ | ||
frameworks: ["mocha", "chai", "karma-typescript"], | ||
files: ["test/common/**/*.ts", "src/**/!(azureTokenCredentials)/*.ts", "src/*.ts", "test/browser/**/*.ts", "test/*.ts"], | ||
preprocessors: { | ||
"**/*.ts": ["karma-typescript"], | ||
}, | ||
karmaTypescriptConfig: { | ||
tsconfig: "./tsconfig-cjs.json", | ||
}, | ||
browsers: ["ChromeHeadless"], | ||
}); | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.