Skip to main content

Migration from @okta/okta-auth-js

Cheat Sheet

okta-authjsEquivalentLibraryExample
signInWithRedirect()AuthorizationCodeFlowspa-oauth2-flowsExample
token.getWithoutPrompt()AuthorizationCodeFlowspa-oauth2-flowsExample
signOutSessionLogoutFlowspa-oauth2-flowsExample
handleLoginRedirect()AuthorizationCodeFlow.remove()spa-oauth2-flowsExample
isAuthenticated()Credential.refreshIfNeeded()spa-platformExample

signInWithRedirect()

Note: signInWithRedirect() and token.getWithRedirect are essentially the same method

Note: Tokens will be stored via the LoginCallback

export const signInFlow = new AuthorizationCodeFlow({
...oauthConfig,
redirectUri: `${window.location.origin}/login/callback`,
});

export async function signIn (originalUri = window.location.href) {
const url = new URL(originalUri);
await signInFlow.start({ originalUri: url.pathname });
return AuthorizationCodeFlow.PerformRedirect(signInFlow);
}

token.getWithoutPrompt()

export const signInFlow = new AuthorizationCodeFlow({
...oauthConfig,
redirectUri: `${window.location.origin}/login/callback`,
});

export async function signIn () {
const { token } = await AuthorizationCodeFlow.PerformSilently(signInFlow);
Credential.store(token);
}

signOut

Note: Signing out a user is not "one-size fits all" in a multi-token architecture. The following example assumes a single (default) token

export const signOutFlow = new SessionLogoutFlow({
...oauthConfig,
logoutRedirectUri: `${window.location.origin}`
});

export async function signOut () {
const idToken = Credential.default?.token?.idToken?.rawValue;
if (idToken) {
const logoutUrl = await signOutFlow.start(idToken);
Credential.default.remove(); // will be revoked via logout call, but needs to be removed from storage
window.location.assign(logoutUrl);
}
}

handleLoginRedirect()

async function handleAuthorizationCodeFlowResponse () {
const { token, context } = await signInFlow.resume(window.location.href);

const { tags, originalUri } = context;
const cred = Credential.store(token, tags);

window.location.replace(originalUri);
}

isAuthenticated()

Note: this example is for illustration purposes. It's recommended to use FetchClient for requesting protected resources

export async function fetchData () {
// fetches token from storage
const credential = Credential.default;

if (!credential) {
// trigger sign in if no token exists
return signIn();
}

try {
// attempt to refresh token, if expired
await credential.refreshIfNeeded();
}
catch (err) {
// trigger sign in if expired token cannot be refresh
return signIn();
}

// happy path: fetch protected resource
return fetch('/api/resource/', {
headers: { Authorization: `Bearer ${credential.token.accessToken}`}
});
}