Skip to content

Commit

Permalink
Merge pull request #1264 from tulios/document-oauthbearer
Browse files Browse the repository at this point in the history
Add example for oauthbearer implementation
  • Loading branch information
Nevon authored Jan 7, 2022
2 parents 2b5f96f + 3fe9b36 commit db0b826
Showing 1 changed file with 75 additions and 1 deletion.
76 changes: 75 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,81 @@ The OAuth bearer token must be an object with properties value and
request.

The implementation of the oauthBearerProvider must take care that tokens are
reused and refreshed when appropriate.
reused and refreshed when appropriate. An example implementation using
[`simple-oauth2`](https://github.com/lelylan/simple-oauth2) would look something
like the following:

```ts
import { AccessToken, ClientCredentials } from 'simple-oauth2'
interface OauthBearerProviderOptions {
clientId: string;
clientSecret: string;
host: string;
path: string;
refreshThresholdMs: number;
}

const oauthBearerProvider = (options: OauthBearerProviderOptions) => {
const client = new ClientCredentials({
client: {
id: options.clientId,
secret: options.clientSecret
},
auth: {
tokenHost: options.host,
tokenPath: options.path
}
});

let tokenPromise: Promise<string>;
let accessToken: AccessToken;

async function refreshToken() {
try {
if (accessToken == null) {
accessToken = await client.getToken({})
}

if (accessToken.expired(options.refreshThresholdMs / 1000)) {
accessToken = await accessToken.refresh()
}

const nextRefresh = accessToken.token.expires_in * 1000 - options.refreshThresholdMs;
setTimeout(() => {
tokenPromise = refreshToken()
}, nextRefresh);

return accessToken.token.access_token;
} catch (error) {
accessToken = null;
throw error;
}
}

tokenPromise = refreshToken();

return async function () {
return {
value: await tokenPromise
}
}
};

const kafka = new Kafka({
// ... other required options
sasl: {
mechanism: 'oauthbearer',
oauthBearerProvider: oauthBearerProvider({
clientId: 'oauth-client-id',
clientSecret: 'oauth-client-secret',
host: 'https://my-oauth-server.com',
path: '/oauth/token',
// Refresh the token 15 seconds before it expires
refreshThreshold: 15000,
}),
},
})
```

### AWS IAM Example

Expand Down

0 comments on commit db0b826

Please sign in to comment.