Migration from @okta/okta-auth-js
Cheat Sheet
okta-authjs | Equivalent | Library | Example |
|---|---|---|---|
| signInWithRedirect() | AuthorizationCodeFlow | spa-oauth2-flows | Example |
| token.getWithoutPrompt() | AuthorizationCodeFlow | spa-oauth2-flows | Example |
| signOut | SessionLogoutFlow | spa-oauth2-flows | Example |
| handleLoginRedirect() | AuthorizationCodeFlow.remove() | spa-oauth2-flows | Example |
| isAuthenticated() | Credential.refreshIfNeeded() | spa-platform | Example |
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
FetchClientfor 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}`}
});
}