Skip to content

Commit

Permalink
Merge pull request #101 from tasoskakour/customise-query-fn
Browse files Browse the repository at this point in the history
Offer more customization over exchangeCodeForToken query
  • Loading branch information
tasoskakour authored Mar 5, 2024
2 parents bf2e133 + e9c55e6 commit 0568dd1
Show file tree
Hide file tree
Showing 17 changed files with 514 additions and 106 deletions.
89 changes: 68 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ const Home = () => {
redirectUri: `${document.location.origin}/callback`,
scope: "YOUR_SCOPES",
responseType: "code",
exchangeCodeForTokenServerURL: "https://your-backend/token",
exchangeCodeForTokenMethod: "POST",
exchangeCodeForTokenQuery: {
url: "https://your-backend/token",
method: "POST",
},
onSuccess: (payload) => console.log("Success", payload),
onError: (error_) => console.log("Error", error_)
});
Expand Down Expand Up @@ -85,17 +87,52 @@ const App = () => {
};
```
### What is the purpose of `exchangeCodeForTokenServerURL` for Authorization Code flows?
##### Example with `exchangeCodeForTokenQueryFn`
You can also use `exchangeCodeForTokenQueryFn` if you want full control over your query to your backend, e.g if you must send your data as form-urlencoded:
```js

const { ... } = useOAuth2({
// ...
// Instead of exchangeCodeForTokenQuery (e.g sending form-urlencoded or similar)...
exchangeCodeForTokenQueryFn: async (callbackParameters) => {
const formBody = [];
for (const key in callbackParameters) {
formBody.push(
`${encodeURIComponent(key)}=${encodeURIComponent(callbackParameters[key])}`
);
}
const response = await fetch(`YOUR_BACKEND_URL`, {
method: 'POST',
body: formBody.join('&'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
});
if (!response.ok) throw new Error('Failed');
const tokenData = await response.json();
return tokenData;
},.
// ...
})

```
### What is the purpose of `exchangeCodeForTokenQuery` for Authorization Code flows?
Generally when we're working with authorization code flows, we need to *immediately* **exchange** the retrieved *code* with an actual *access token*, after a successful authorization. Most of the times this is needed for back-end apps, but there are many use cases this is useful for front-end apps as well.
In order for the flow to be accomplished, the 3rd party provider we're authorizing against (e.g Google, Facebook etc), will provide an API call (e.g for Google is `https://oauth2.googleapis.com/token`) that we need to hit in order to exchange the code for an access token. However, this call requires the `client_secret` of your 3rd party app as a parameter to work - a secret that you cannot expose to your front-end app.

That's why you need to proxy this call to your back-end and `exchangeCodeForTokenServerURL` is the API URL of your back-end route that will take care of this. The request parameters that will get passed along as **query parameters** are `{ code, client_id, grant_type, redirect_uri, state }`. By default this will be a **POST** request but you can change it with the `exchangeCodeForTokenMethod` property.
That's why you need to proxy this call to your back-end and with `exchangeCodeForTokenQuery` object you can provide the schematics of your call e.g `url`, `method` etc. The request parameters that will get passed along as **query parameters** are `{ code, client_id, grant_type, redirect_uri, state }`. By default this will be a **POST** request but you can change it with the `method` property.
You can read more about "Exchanging authorization code for refresh and access tokens" in [Google OAuth2 documentation](https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code).
### What's the alternative option `exchangeCodeForTokenQueryFn`?

There could be certain cases where `exchangeCodeForTokenQuery` is not enough and you want full control over how you send the request to your backend. For example you may want to send it as a urlencoded form. With this property you can define your callback function which takes `callbackParameters: object` as a parameter (which includes whatever returned from OAuth2 callback e.g `code, scope, state` etc) and must return a promise with a valid object which will contain all the token data state e.g `access_token, expires_in` etc.

### What's the case with Implicit Grant flows?

With an implicit grant flow things are much simpler as the 3rd-party provider immediately returns the `access_token` to the callback request so there's no need to make any action after that. Just set `responseType=token` to use this flow.
Expand All @@ -106,34 +143,36 @@ After a successful authorization, data will get persisted to **localStorage** an
If you want to re-trigger the authorization flow just call `getAuth()` function again.
**Note**: In case localStorage is throwing an error (e.g user has disabled it) then you can use the `isPersistent` property which - for this case -will be false. Useful if you want to notify the user that the data is only stored in-memory.
**Note**: In case localStorage is throwing an error (e.g user has disabled it) then you can use the `isPersistent` property which - for this case - will be false. Useful if you want to notify the user that the data is only stored in-memory.
## API
- `function useOAuth2(options): {data, loading, error, getAuth}`
This is the hook that makes this package to work. `Options` is an object that contains the properties below
- **authorizeUrl** (string): The 3rd party authorization URL (e.g https://accounts.google.com/o/oauth2/v2/auth).
- **clientId** (string): The OAuth2 client id of your application.
- **redirectUri** (string): Determines where the 3rd party API server redirects the user after the user completes the authorization flow. In our [example](#usage-example) the Popup is rendered on that redirectUri.
- **scope** (string - _optional_): A list of scopes depending on your application needs.
- **responseType** (string): Can be either **code** for _code authorization grant_ or **token** for _implicit grant_.
- **extraQueryParameters** (object - _optional_): An object of extra parameters that you'd like to pass to the query part of the authorizeUrl, e.g {audience: "xyz"}.
- **exchangeCodeForTokenServerURL** (string): This property is only used when using _code authorization grant_ flow (responseType = code). It specifies the API URL of your server that will get called immediately after the user completes the authorization flow. Read more [here](#what-is-the-purpose-of-exchangecodefortokenserverurl-for-authorization-code-flows).
- **exchangeCodeForTokenMethod** (string - _optional_): Specifies the HTTP method that will be used for the code-for-token exchange to your server. Defaults to **POST**.
- **exchangeCodeForTokenHeaders** (object - _optional_): An object of extra parameters that will be used for the code-for-token exchange to your server.
- `authorizeUrl` (string): The 3rd party authorization URL (e.g https://accounts.google.com/o/oauth2/v2/auth).
- `clientId` (string): The OAuth2 client id of your application.
- `redirectUri` (string): Determines where the 3rd party API server redirects the user after the user completes the authorization flow. In our [example](#usage-example) the Popup is rendered on that redirectUri.
- `scope` (string - _optional_): A list of scopes depending on your application needs.
- `responseType` (string): Can be either **code** for _code authorization grant_ or **token** for _implicit grant_.
- `extraQueryParameters` (object - _optional_): An object of extra parameters that you'd like to pass to the query part of the authorizeUrl, e.g {audience: "xyz"}.
- `exchangeCodeForTokenQuery` (object): This property is only required when using _code authorization grant_ flow (responseType = code). It's properties are:
- `url` (string - _required_) It specifies the API URL of your server that will get called immediately after the user completes the authorization flow. Read more [here](#what-is-the-purpose-of-exchangecodefortokenserverurl-for-authorization-code-flows).
- `method` (string - _required_): Specifies the HTTP method that will be used for the code-for-token exchange to your server. Defaults to **POST**
- `headers` (object - _optional_): An object of extra parameters that will be used for the code-for-token exchange to your server.
- `exchangeCodeForTokenQueryFn` function(callbackParameters) => Promise\<Object\>: **Instead of using** `exchangeCodeForTokenQuery` to describe the query, you can take full control and provide query function yourself. `callbackParameters` will contain everything returned from the OAUth2 callback e.g `code, state` etc. You must return a promise with a valid object that will represent your final state - data of the auth procedure.
- **onSuccess** (function): Called after a complete successful authorization flow.
- **onError** (function): Called when an error occurs.
**Returns**:
- **data** (object): Consists of the retrieved auth data and generally will have the shape of `{access_token, token_type, expires_in}` (check [Typescript](#typescript) usage for providing custom shape).
- **loading** (boolean): Is set to true while the authorization is taking place.
- **error** (string): Is set when an error occurs.
- **getAuth** (function): Call this function to trigger the authorization flow.
- **logout** (function): Call this function to logout and clear all authorization data.
- **isPersistent** (boolean): Property that returns false if localStorage is throwing an error and the data is stored only in-memory. Useful if you want to notify the user.
- `data` (object): Consists of the retrieved auth data and generally will have the shape of `{access_token, token_type, expires_in}` (check [Typescript](#typescript) usage for providing custom shape). If you're using `responseType: code` and `exchangeCodeForTokenQueryFn` this object will contain whatever you returnn from your query function.
- `loading` (boolean): Is set to true while the authorization is taking place.
- `error` (string): Is set when an error occurs.
- `getAuth` (function): Call this function to trigger the authorization flow.
- `logout` (function): Call this function to logout and clear all authorization data.
- `isPersistent` (boolean): Property that returns false if localStorage is throwing an error and the data is stored only in-memory. Useful if you want to notify the user.
---
Expand All @@ -143,7 +182,7 @@ This is the component that will be rendered as a window Popup for as long as the

Props consists of:

- **Component** (ReactElement - _optional_): You can optionally set a custom component to be rendered inside the Popup. By default it just displays a "Loading..." message.
- `Component` (ReactElement - _optional_): You can optionally set a custom component to be rendered inside the Popup. By default it just displays a "Loading..." message.

### Typescript

Expand Down Expand Up @@ -178,6 +217,14 @@ type MyCustomShapeData = {
const {data, ...} = useOAuth2<MyCustomShapeData>({...});
```
### Migrating to v2.0.0 (2024-03-05)
Please follow the steps below to migrate to `v2.0.0`:
- **DEPRECATED properties**: `exchangeCodeForTokenServerURL`, `exchangeCodeForTokenMethod`, `exchangeCodeForTokenHeaders`
- **INTRODUCED NEW PROPERTY**: `exchangeCodeForTokenQuery`
- `exchangeCodeForTokenQuery` just combines all the above deprecated properties, e.g you can use it like: `exchangeCodeForTokenQuery: { url:"...", method:"POST", headers:{} }`
### Tests
You can run tests by calling
Expand Down
91 changes: 91 additions & 0 deletions e2e/login-authorization-code-flow-with-queryfn.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import puppeteer, { Browser } from 'puppeteer';
import { getTextContent } from './test-utils';

const URL = 'http://localhost:3000';

let browser: Browser;
afterAll((done) => {
browser.close();

done();
});

test('Login with authorization code flow and exchangeCodeForQueryFn works as expected', async () => {
browser = await puppeteer.launch({ headless: 'new' });
const page = await browser.newPage();

await page.goto(URL);

const nav = new Promise((response) => {
browser.on('targetcreated', response);
});

await page.click('#authorization-code-queryfn-login');

// Assess loading
await page.waitForSelector('#authorization-code-queryfn-loading');

// Assess popup redirection
await nav;
const pages = await browser.pages();
expect(pages[2].url()).toMatch(
/http:\/\/localhost:3000\/callback\?code=SOME_CODE&state=.*\S.*/ // any non-empty state
);

// Assess network call to exchange code for token
await page.waitForResponse(async (response) => {
if (response.request().method().toUpperCase() === 'OPTIONS') return false;

const url = decodeURIComponent(response.url());
const json = await response.json();
const urlPath = url.split('?')[0];

return (
urlPath === 'http://localhost:3001/mock-token-form-data' &&
response.request().method().toUpperCase() === 'POST' &&
response.request().postData() === 'code=SOME_CODE&someOtherData=someOtherData' &&
json.code === 'SOME_CODE' &&
json.access_token === 'SOME_ACCESS_TOKEN' &&
json.expires_in === 3600 &&
json.refresh_token === 'SOME_REFRESH_TOKEN' &&
json.scope === 'SOME_SCOPE' &&
json.token_type === 'Bearer'
);
});

// Assess UI
await page.waitForSelector('#authorization-code-queryfn-data');
expect(await getTextContent(page, '#authorization-code-queryfn-data')).toBe(
'{"code":"SOME_CODE","access_token":"SOME_ACCESS_TOKEN","expires_in":3600,"refresh_token":"SOME_REFRESH_TOKEN","scope":"SOME_SCOPE","token_type":"Bearer"}'
);

// Assess localStorage
expect(
await page.evaluate(() =>
JSON.parse(
window.localStorage.getItem(
'code-http://localhost:3001/mock-authorize-SOME_CLIENT_ID_2-SOME_SCOPE'
) || ''
)
)
).toEqual({
code: 'SOME_CODE',
access_token: 'SOME_ACCESS_TOKEN',
expires_in: 3600,
refresh_token: 'SOME_REFRESH_TOKEN',
scope: 'SOME_SCOPE',
token_type: 'Bearer',
});

// Logout
await page.click('#authorization-code-queryfn-logout');
expect(await page.$('#authorization-code-queryfn-data')).toBe(null);
expect(await page.$('#authorization-code-queryfn-login')).not.toBe(null);
expect(
await page.evaluate(() =>
window.localStorage.getItem(
'code-http://localhost:3001/mock-authorize-SOME_CLIENT_ID_2-SOME_SCOPE'
)
)
).toEqual('null');
});
6 changes: 5 additions & 1 deletion e2e/login-authorization-code-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ test('Login with authorization code flow works as expected', async () => {

// Assess network call to exchange code for token
await page.waitForResponse(async (response) => {
if (response.request().method().toUpperCase() === 'OPTIONS') return false;

const url = decodeURIComponent(response.url());
const json = await response.json();
const urlPath = url.split('?')[0];
Expand All @@ -46,6 +48,7 @@ test('Login with authorization code flow works as expected', async () => {
urlQuery.get('code') === 'SOME_CODE' &&
urlQuery.get('redirect_uri') === 'http://localhost:3000/callback' &&
Boolean(urlQuery.get('state')?.match(/.*\S.*/)) &&
json.code === 'SOME_CODE' &&
json.access_token === 'SOME_ACCESS_TOKEN' &&
json.expires_in === 3600 &&
json.refresh_token === 'SOME_REFRESH_TOKEN' &&
Expand All @@ -57,7 +60,7 @@ test('Login with authorization code flow works as expected', async () => {
// Assess UI
await page.waitForSelector('#authorization-code-data');
expect(await getTextContent(page, '#authorization-code-data')).toBe(
'{"access_token":"SOME_ACCESS_TOKEN","expires_in":3600,"refresh_token":"SOME_REFRESH_TOKEN","scope":"SOME_SCOPE","token_type":"Bearer"}'
'{"code":"SOME_CODE","access_token":"SOME_ACCESS_TOKEN","expires_in":3600,"refresh_token":"SOME_REFRESH_TOKEN","scope":"SOME_SCOPE","token_type":"Bearer"}'
);

// Assess localStorage
Expand All @@ -70,6 +73,7 @@ test('Login with authorization code flow works as expected', async () => {
)
)
).toEqual({
code: 'SOME_CODE',
access_token: 'SOME_ACCESS_TOKEN',
expires_in: 3600,
refresh_token: 'SOME_REFRESH_TOKEN',
Expand Down
5 changes: 4 additions & 1 deletion example/client/Example.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import { BrowserRouter, Route, Routes } from 'react-router-dom';

import { OAuthPopup } from '../../src/components';
import LoginAuthorizationCode from './LoginAuthorizationCode';
import LoginAuthorizationCodeWithQueryFn from './LoginAuthorizationCodeWithQueryFn';
import LoginImplicitGrant from './LoginImplicitGrant';

const Home = () => {
return (
<div style={{ margin: '24px' }}>
<LoginImplicitGrant />
<hr />
<LoginAuthorizationCode />
<hr />
<LoginImplicitGrant />
<LoginAuthorizationCodeWithQueryFn />
</div>
);
};
Expand Down
9 changes: 7 additions & 2 deletions example/client/LoginAuthorizationCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ const LoginCode = () => {
redirectUri: `${document.location.origin}/callback`,
scope: 'SOME_SCOPE',
responseType: 'code',
exchangeCodeForTokenServerURL: 'http://localhost:3001/mock-token',
exchangeCodeForTokenMethod: 'POST',
exchangeCodeForTokenQuery: {
method: 'GET',
url: 'http://localhost:3001/mock-token',
headers: {
someHeader: 'someHeader',
},
},
onSuccess: (payload) => console.log('Success', payload),
onError: (error_) => console.log('Error', error_),
});
Expand Down
81 changes: 81 additions & 0 deletions example/client/LoginAuthorizationCodeWithQueryFn.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/* eslint-disable no-console */
import { useOAuth2 } from '../../src/components';

type TMyAuthData = {
access_token: string;
};

const LoginCode = () => {
const { data, loading, error, getAuth, logout } = useOAuth2<TMyAuthData>({
authorizeUrl: 'http://localhost:3001/mock-authorize',
clientId: 'SOME_CLIENT_ID_2',
redirectUri: `${document.location.origin}/callback`,
scope: 'SOME_SCOPE',
responseType: 'code',
exchangeCodeForTokenQueryFn: async (callbackParameters: { code: string }) => {
const jsonObject = {
code: callbackParameters.code,
someOtherData: 'someOtherData',
};
const formBody = [];
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const key in jsonObject) {
formBody.push(
`${encodeURIComponent(key)}=${encodeURIComponent(jsonObject[key as keyof typeof jsonObject])}`
);
}
const response = await fetch(`http://localhost:3001/mock-token-form-data`, {
method: 'POST',
body: formBody.join('&'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
});
if (!response.ok) throw new Error('exchangeCodeForTokenQueryFn fail at example');
const tokenData = await response.json();
return tokenData;
},
onSuccess: (payload) => console.log('Success', payload),
onError: (error_) => console.log('Error', error_),
});

const isLoggedIn = Boolean(data?.access_token); // or whatever...

let ui = (
<button type="button" id="authorization-code-queryfn-login" onClick={() => getAuth()}>
Login with Authorization Code with QueryFn
</button>
);

if (error) {
ui = <div>Error</div>;
}

if (loading) {
ui = <div id="authorization-code-queryfn-loading">Loading...</div>;
}

if (isLoggedIn) {
ui = (
<div>
<pre id="authorization-code-queryfn-data">{JSON.stringify(data)}</pre>
<button
id="authorization-code-queryfn-logout"
type="button"
onClick={() => logout()}
>
Logout
</button>
</div>
);
}

return (
<div style={{ margin: '24px' }}>
<h2> Login with Authorization Code with QueryFn</h2>
{ui}
</div>
);
};

export default LoginCode;
Loading

0 comments on commit 0568dd1

Please sign in to comment.