Skip to content

Commit

Permalink
[SDK-4026] Add some examples (#909)
Browse files Browse the repository at this point in the history
Co-authored-by: Frederik Prijck <[email protected]>
  • Loading branch information
adamjmcgrath and frederikprijck authored Aug 16, 2023
1 parent 9ea0a0c commit 35638e1
Show file tree
Hide file tree
Showing 2 changed files with 242 additions and 7 deletions.
232 changes: 232 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# Examples

- [Authentication Client](#authentication-client)
- [Signup a user](#signup-a-user)
- [Use a client assertion](#use-a-client-assertion)
- [Use Refresh Tokens](#use-refresh-tokens)
- [Complete the Authorization Code flow with PKCE](#complete-the-authorization-code-flow-with-pkce)
- [Login with Passwordless](#login-with-passwordless)
- [Management Client](#management-client)
- [Paginate through a list of users](#paginate-through-a-list-of-users)
- [Paginate through a list of logs using checkpoint pagination](#paginate-through-a-list-of-logs-using-checkpoint-pagination)
- [Import users from a JSON file](#import-users-from-a-json-file)
- [Update a user's user_metadata](#update-a-users-user_metadata)

## Authentication Client

### Signup a user

```js
import { AuthenticationClient } from 'auth0';

const auth = new AuthenticationClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});
const { data: user } = await auth.database.signUp({
user: '{USER_EMAIL}',
password: '{USER_PASSWORD}',
connection: 'Username-Password-Authentication',
});
```

### Use a client assertion

```js
import { AuthenticationClient } from 'auth0';

const clientAssertionSigningKey = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----`;

const auth = new AuthenticationClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientAssertionSigningKey,
});

const { data: tokens } = await auth.oauth.clientCredentialsGrant({
audience: 'you-api',
});
```

### Use Refresh Tokens

```js
import { AuthenticationClient } from 'auth0';

const auth = new AuthenticationClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

// Get a new access token
const {
data: { access_token },
} = await auth.oauth.refreshTokenGrant({
refresh_token: refreshToken,
});

// Revoke a refresh token
await auth.oauth.revokeRefreshToken({
token: refreshToken,
});
```

### Complete the Authorization Code flow with PKCE

```js
import { AuthenticationClient } from 'auth0';

const auth = new AuthenticationClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});
const { data: tokens } = await auth.oauth.authorizationCodeGrantWithPKCE(
{
code_verifier: '{key used to generate the code_challenge passed to /authorize}',
code: '{code from authorization response}',
redirect_uri: '{application redirect uri}',
},
{
idTokenValidateOptions: {
nonce: '{random string passed to /authorize to check against the nonce claim}',
maxAge: '{number of seconds to check against the auth_time claim}',
organization: '{organization name or ID to check against the org_id or org_name claim}',
},
}
);
```

> Note: We recommend one of our [Regular Web Application SDK Libraries](https://auth0.com/docs/libraries#webapp) for this.
### Login with Passwordless

```js
import { AuthenticationClient } from 'auth0';

const auth = new AuthenticationClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

// Or you can `sendSMS`
await auth.passwordless.sendEmail({
email: '{user email}',
send: 'code',
});

const { data: tokens } = await auth.passwordless.loginWithEmail({
email: '{user email}',
code: '{code from email}',
});
```

## Management Client

### Paginate through a list of users

```js
import { ManagementClient } from 'auth0';

const management = new ManagementClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

const allUsers = [];
let page = 0;
while (true) {
const {
data: { users, total },
} = await management.users.getAll({
include_totals: true,
page: page++,
});
allUsers.push(...users);
if (allUsers.length === total) {
break;
}
}
```

> Note: The maximum number of users you can get with this endpoint is 1000. For more use `users.exportUsers`.
### Paginate through a list of logs using checkpoint pagination

```js
import { ManagementClient } from 'auth0';

const management = new ManagementClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

const allLogs = [];
let from = '';
while (true) {
const { data: logs } = await mgmntClient.logs.getAll({ from });
if (!logs.length) {
break;
}
allLogs.push(...logs);
({ log_id: from } = logs[logs.length - 1]);
}
```

### Import users from a JSON file

```js
import { ManagementClient } from 'auth0';
import { fileFrom } from 'fetch-blob/from.js';

const management = new ManagementClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

const {
data: { job: id },
} = await management.jobs.importUsers({
users: await fileFrom('./users.json', 'application/json'),
connection_id: 'con_{your connection id}',
});

let done = false;
while (!done) {
const {
data: {
job: { status },
},
} = await management.jobs.get({ id });
if (status === 'completed') {
done = true;
} else if (status === 'failed') {
const { data: errors } = await management.jobs.getErrors({ id });
throw new Error(errors);
} else {
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
```

### Update a user's user_metadata

```js
import { ManagementClient } from 'auth0';

const management = new ManagementClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});

await management.users.update({ id: '{user id}' }, { user_metadata: { foo: 'bar' } });
```
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ npm install auth0@beta

This client can be used to access Auth0's [Authentication API](https://auth0.com/docs/api/authentication).

The **AuthenticationClient** constructor takes an _optional_ client ID, if specified it will be used as default value for all endpoints that accept a client ID.

```js
import { AuthenticationClient } from 'auth0';

Expand All @@ -48,32 +46,37 @@ const auth0 = new AuthenticationClient({
});
```

See [more examples](./EXAMPLES.md#authentication-client).

#### Management API Client

The Auth0 Management API is meant to be used by back-end servers or trusted parties performing administrative tasks. Generally speaking, anything that can be done through the Auth0 dashboard (and more) can also be done through this API.

Initialize your client class with an API v2 token and a domain.
Initialize your client class with a client ID, client secret and a domain.

```js
import { ManagementClient } from 'auth0';

var management = new ManagementClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
token: '{YOUR_API_V2_TOKEN}',
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
clientId: '{YOUR_CLIENT_ID}',
clientSecret: '{YOUR_CLIENT_SECRET}',
});
```

Or, initialize your client class with a client secret and a domain.
Or, initialize your client class with an API v2 token and a domain.

```js
import { ManagementClient } from 'auth0';

var management = new ManagementClient({
domain: '{YOUR_TENANT_AND REGION}.auth0.com',
token: '{YOUR_API_V2_TOKEN}',
domain: '{YOUR_ACCOUNT}.auth0.com',
});
```

See [more examples](./EXAMPLES.md#management-client).

## API Reference

- [AuthenticationClient](https://auth0.github.io/node-auth0/beta/classes/auth.AuthenticationClient.html)
Expand Down

0 comments on commit 35638e1

Please sign in to comment.