Skip to content

[msal-node] documentation #1902

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 9 commits into from
Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ The Microsoft Authentication Library for JavaScript enables client-side JavaScri

The [`lib`](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib) folder contains the source code for all of our libraries. You will also find all the details about **installing the libraries**, in their respective README.md.

- [Microsoft Authentication Library for Node.js v1.x (Alpha)](lib/msal-node/): A [Node.js](https://nodejs.org/en/) library that enables authentication and token acquisition with the Microsoft Identity platform in JavaScript applications. Implements the following OAuth 2.0 protocols and is [OpenID-compliant](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc):
- [Authorization Code Grant](https://oauth.net/2/grant-types/authorization-code/) with [PKCE](https://oauth.net/2/pkce/)
- [Device Code Grant](https://oauth.net/2/grant-types/device-code/)
- [Refresh Token Grant](https://oauth.net/2/grant-types/refresh-token/)
- [Client Credential Grant](https://oauth.net/2/grant-types/client-credentials/) (Coming soon)

- [Microsoft Authentication Library for JavaScript v2.x (Preview)](lib/msal-browser/): A browser-based, framework-agnostic browser library that enables authentication and token acquisition with the Microsoft Identity platform in JavaScript applications. Implements the OAuth 2.0 [Authorization Code Flow with PKCE](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow), and is [OpenID-compliant](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc).

- [Microsoft Authentication Library for JavaScript v1.x](lib/msal-core/): A browser-based, framework-agnostic core library that enables authentication and token acquisition with the Microsoft Identity platform in JavaScript applications. Implements the OAuth 2.0 [Implicit Grant Flow](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow), and is [OpenID-compliant](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc).
Expand Down
9 changes: 9 additions & 0 deletions lib/msal-common/docs/Response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MSAL will return an `AuthenticationResult.ts` object as a response to all acquire token APIs:

#### `msal-browser` public APIs for token acquisition:
`loginPopup`, `acquireTokenPopup`, `acquireTokenSilent` or `handleRedirectPromise`

#### `msal-node` public APIs for token acquisition:
`acquireTokenByCode`, `acquireTokenSilent`, `acquireTokenByRefreshToken`, `acquireTokenByDeviceCode`

Reference docs for `AuthenticationResult` expanding on each parameter can be found [here](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/classes/_src_response_authenticationresult_.authenticationresult.html).
3 changes: 0 additions & 3 deletions lib/msal-common/docs/initialization.md

This file was deleted.

191 changes: 191 additions & 0 deletions lib/msal-common/docs/request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# Request

Since MSAL Node supports various authorization code grants, there is support for different public APIs per grant and the corresponding request.

## Authorization Code Flow

### Public APIs
- [getAuthCodeUrl()](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-node/classes/_src_client_publicclientapplication_.publicclientapplication.html#getauthcodeurl): This API is the first leg of the `authorization code grant` for MSAL Node. The request is of the type [AuthorizationUrlRequest](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/modules/_src_request_authorizationurlrequest_.html).
The application is sent a URL that can be used to generate an `authorization code`. This `URL` can be opened in a browser of choice, where the user can input their credential, and will be redirected back to the `redirectUri` (registered during the [app registration](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-app-registration)) with an `authorization code`. The `authorization code` can now be redeemed for a `token` with the following step.

- [acquireTokenByCode()](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-node/classes/_src_client_publicclientapplication_.publicclientapplication.html#acquiretokenbycode): This API is the second leg of the `authorization code grant` for MSAL Node. The request constructed here should be of the type [AuthorizationCodeRequest](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/modules/_src_request_authorizationcoderequest_.html). The application passed the `authorization code` received as a part of the above step and exchanges it for a `token`.

``` javascript

const authCodeUrlParameters = {
scopes: ["sample_scope"],
redirectUri: "your_redirect_uri",
};

// get url to sign user in and consent to scopes needed for application
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
console.log(response);
}).catch((error) => console.log(JSON.stringify(error)));

const tokenRequest = {
code: "authorization_code",
redirectUri: "your_redirect_uri",
scopes: ["sample_scope"],
};

// acquire a token by exchanging the code
pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
}).catch((error) => {
console.log(error);
});
```

## Device Code Flow

### Public APIs
- [acquireTokenByDeviceCode()](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-node/classes/_src_client_publicclientapplication_.publicclientapplication.html#acquiretokenbydevicecode): This API lets the application acquire a token with Device Code grant. The request is of the type [DeviceCodeRequest](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/modules/_src_request_devicecoderequest_.html). This API acquires a `token` from the authority using OAuth2.0 device code flow. This flow is designed for devices that do not have access to a browser or have input constraints. The authorization server issues a DeviceCode object with a verification code, an end-user code, and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be instructed to use another device to navigate to the verification URI to input credentials. Since the client cannot receive incoming requests, it polls the authorization server repeatedly until the end-user completes input of credentials.

``` javascript
const msalConfig = {
auth: {
clientId: "your_client_id_here",
authority: "your_authority_here",
}
};

const pca = new msal.PublicClientApplication(msalConfig);

const deviceCodeRequest = {
deviceCodeCallback: (response) => (console.log(response.message)),
scopes: ["user.read"],
};

pca.acquireTokenByDeviceCode(deviceCodeRequest).then((response) => {
console.log(JSON.stringify(response));
}).catch((error) => {
console.log(JSON.stringify(error));
});

```

## Refresh Token Flow

### Public APIs
- [acquireTokenByRefreshToken](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-node/classes/_src_client_publicclientapplication_.publicclientapplication.html#acquiretokenbyrefreshtoken): This API acquires a token by exchanging the refresh token provided for a new set of tokens. The request is of the type [RefreshTokenRequest](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/modules/_src_request_refreshtokenrequest_.html). The `refresh token` is never returned to the user in a response, but can be accessed from the user cache. It is recommended that you use acquireTokenSilent() for silent scenarios. When using acquireTokenSilent(), MSAL will handle the caching and refreshing of tokens automatically.

``` javascript
const config = {
auth: {
clientId: "your_client_id_here",
authority: "your_authority_here",
}
};

const pca = new msal.PublicClientApplication(config);

const refreshTokenRequest = {
refreshToken: "",
scopes: ["user.read"],
};

pca.acquireTokenByRefreshToken(refreshTokenRequest).then((response) => {
console.log(JSON.stringify(response));
}).catch((error) => {
console.log(JSON.stringify(error));
});
```

## Silent Flow

### Public APIs
- [acquireTokenSilent](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-node/classes/_src_client_publicclientapplication_.publicclientapplication.html#acquiretokensilent): This API acquires a token silently, in case cache is provided by the user, or when cache is created by preceding this call with any other interactive flow (eg: authorization code flow). The request is of the type [SilentFlowRequest](https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-common/modules/_src_request_silentflowrequest_.html). The `token` is acquired silently when a user specifies the account the token is requested for.

``` javascript
/**
* Cache Plugin configuration
*/
const cachePath = "./data/example.cache.json"; // Replace this string with the path to your valid cache file.

const readFromStorage = () => {
return fs.readFile(cachePath, "utf-8");
};

const writeToStorage = (getMergedState) => {
return readFromStorage().then(oldFile =>{
const mergedState = getMergedState(oldFile);
return fs.writeFile(cachePath, mergedState);
})
};

const cachePlugin = {
readFromStorage,
writeToStorage
};

/**
* Public Client Application Configuration
*/
const publicClientConfig = {
auth: {
clientId: "your_client_id_here",
authority: "your_authority_here",
redirectUri: "your_redirectUri_here",
},
cache: {
cachePlugin
},
};

/** Request Configuration */

const scopes = ["your_scopes"];

const authCodeUrlParameters = {
scopes: scopes,
redirectUri: "your_redirectUri_here",
};

const pca = new msal.PublicClientApplication(publicClientConfig);
const msalCacheManager = pca.getCacheManager();
let accounts;

pca.getAuthCodeUrl(authCodeUrlParameters)
.then((response) => {
console.log(response);
}).catch((error) => console.log(JSON.stringify(error)));

const tokenRequest = {
code: req.query.code,
redirectUri: "http://localhost:3000/redirect",
scopes: scopes,
};

pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
return msalCacheManager.writeToPersistence();
}).catch((error) => {
console.log(error);
});

// get Accounts
accounts = msalCacheManager.getAllAccounts();
console.log("Accounts: ", accounts);

// Build silent request
const silentRequest = {
account: accounts[1], // Index must match the account that is trying to acquire token silently
scopes: scopes,
};

// Acquire Token Silently to be used in MS Graph call
pca.acquireTokenSilent(silentRequest).then((response) => {
console.log("\nSuccessful silent token acquisition:\nResponse: \n:", response);
return msalCacheManager.writeToPersistence();
}).catch((error) => {
console.log(error);
});
```
## Next Steps
Proceed to understand the public APIs provided by `msal-node` for acquiring tokens [here](./response.md)






Loading