____ _ _ ___
/ __ \ /\ | | | | |__ \
| | | | / \ _ _| |_| |__ ) |
| | | |/ /\ \| | | | __| '_ \ / /
| |__| / ____ \ |_| | |_| | | |/ /_
\____/_/ \_\__,_|\__|_| |_|____|
/$$$$$$$
| $$__ $$
| $$ \ $$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$
| $$$$$$$//$$__ $$ /$$__ $$| $$ | $$ /$$__ $$
| $$____/| $$ \ $$| $$ \ $$| $$ | $$| $$ \ $$
| $$ | $$ | $$| $$ | $$| $$ | $$| $$ | $$
| $$ | $$$$$$/| $$$$$$$/| $$$$$$/| $$$$$$$/
|__/ \______/ | $$____/ \______/ | $$____/
| $$ | $$
| $$ | $$ ______ _
|__/ |__/ | ____| |
| |__ | | _____ __
| __| | |/ _ \ \ /\ / /
| | | | (_) \ V V /
|_| |_|\___/ \_/\_/
A very simple oauth2 implicit grant flow library
with no dependencies that uses window.open
.
- Simplicity as a feature—only 187 SLOC.
- No dependencies.
- Easily integrates with React, Angular, Vue etc.
- Never interrupt or reload the state of your client to login.
- To get a token, call
oauth2PopupFlow.token()
which returns a Promise<string>
of the token. - To get the payload, call
oauth2PopupFlow.tokenPayload()
which returns a Promise<TokenPayload>
. - Statically typed API via Typescript for use within Javascript or Typescript.
If the user isn't logged in, the typical OAuth2 implicit grant flow forwards the user to the authorization server's login page (separate from your app) and then redirects them back. The issue with this is that it requires the app to be reloaded in order to grab a token. This reload complicates your application and may result in lost work due to the app reloading.
The popup is a simple solution that allows the 9e load the hosted login page that keep the state of your application.
This library is great if:
- You already use the implicit grant
- Your authorization server typically doesn't prompt the user to login
- You want the user to automatically be logged in and authenticated in your application
Usage
import { OAuth2PopupFlow } from 'oauth2-popup-flow';
interface TokenPayload {
exp: number,
other: string,
stuff: string,
username: string,
}
export const auth = new OAuth2PopupFlow<TokenPayload>({
authorizationUri: 'https://example.com/oauth/authorize',
clientId: 'YOUR_CLIENT_ID',
redirectUri: 'http://localhost:8080/redirect',
scope: 'openid profile',
});
auth.tryLoginPopup().then(result => {
if (result === 'ALREADY_LOGGED_IN') {
} else if (result === 'POPUP_FAILED') {
} else if (result === 'SUCCESS') {
}
});
const loggedIn = auth.loggedIn();
async function someAsyncFunction() {
auth.tryLoginPopup();
const token = await auth.token();
const response = await fetch('https://example.com', {
method: 'POST',
headers: new Headers({
Authorization: `Bearer ${token}`,
}),
});
}
async function getInfoFromToken() {
auth.tryLoginPopup();
const payload = await auth.tokenPayload();
return payload.username;
}
someAsyncFunction();
getInfoFromToken().then(username => console.log({ username }));
Check out the API docs for more info
Examples (WIP)
Requirements