Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Added refreshToken and saveCredentials to auth0 hook #883

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/hooks/__tests__/use-auth0.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,20 @@ const mockIdToken = makeJwt();
const mockCredentials = {
idToken: mockIdToken,
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
};

const mockAuthError = new Auth0Error({ json: { error: 'mock error' } });

const updatedMockCredentialsWithIdToken = {
idToken: makeJwt({ name: 'Different User' }),
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
};

const updatedMockCredentialsWithoutIdToken = {
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
};

const wrapper = ({ children }) => (
Expand All @@ -65,6 +68,9 @@ const mockAuth0 = {
loginWithOTP: jest.fn().mockResolvedValue(mockCredentials),
loginWithRecoveryCode: jest.fn().mockResolvedValue(mockCredentials),
hasValidCredentials: jest.fn().mockResolvedValue(),
refreshToken: jest
.fn()
.mockResolvedValue(updatedMockCredentialsWithIdToken),
},
credentialsManager: {
getCredentials: jest.fn().mockResolvedValue(mockCredentials),
Expand Down Expand Up @@ -212,6 +218,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -251,6 +258,63 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

it("can refresh the user's credentials using refreshToken method", async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
});
let credentials;
let newCredentials;
await act(async () => {
credentials = await result.current.getCredentials();
await result.current.refreshToken({
refreshToken: credentials.refreshToken,
scope: 'openid profile email offline_access',
});
newCredentials = await result.current.getCredentials();
});

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(mockAuth0.auth.refreshToken).toHaveBeenCalledWith({
refreshToken: credentials.refreshToken,
scope: 'openid profile email offline_access',
});
expect(newCredentials).toEqual({
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

it("can save the user's credentials using saveCredentials method", async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
});
let credentials;
let newCredentials;

await act(async () => {
const { refreshToken } = await result.current.getCredentials();
newCredentials = await result.current.refreshToken({
refreshToken,
scope: 'openid profile email offline_access',
});
result.current.saveCredentials(newCredentials);
credentials = await result.current.getCredentials();
});

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(newCredentials).toEqual({
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -407,6 +471,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -524,6 +589,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -639,6 +705,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -695,6 +762,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down Expand Up @@ -751,6 +819,7 @@ describe('The useAuth0 hook', () => {
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
refreshToken: 'REFRESH TOKEN',
});
});

Expand Down
20 changes: 20 additions & 0 deletions src/hooks/auth0-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
WebAuthorizeParameters,
PasswordlessWithSMSOptions,
ClearSessionOptions,
RefreshTokenOptions,
} from '../types';
import LocalAuthenticationStrategy from '../credentials-manager/localAuthenticationStrategy';

Expand Down Expand Up @@ -102,6 +103,23 @@ export interface Auth0ContextInterface<TUser extends User = User>
parameters?: Record<string, unknown>,
forceRefresh?: boolean
) => Promise<Credentials | undefined>;
/**
* Manually saves the user's credentials to the native credential store.
* by default. See {@link CredentialsManager#getCredentials}
* @returns
*/
saveCredentials: (
credentials: Credentials
) => Promise<Credentials | undefined>;
/**
* Obtain new tokens using the Refresh Token obtained during Auth (requesting `offline_access` scope)
*
* @returns A populated instance of {@link Credentials}.
* @see https://auth0.com/docs/tokens/refresh-token/current#use-a-refresh-token
*/
refreshToken: (
refreshTokenOptions: RefreshTokenOptions
) => Promise<Credentials | undefined>;
/**
* Clears the user's credentials without clearing their web session and logs them out.
*/
Expand Down Expand Up @@ -160,6 +178,8 @@ const initialContext = {
getCredentials: stub,
clearCredentials: stub,
requireLocalAuthentication: stub,
saveCredentials: stub,
refreshToken: stub,
};

const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
Expand Down
39 changes: 39 additions & 0 deletions src/hooks/auth0-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
MultifactorChallengeOptions,
PasswordlessWithEmailOptions,
PasswordlessWithSMSOptions,
RefreshTokenOptions,
User,
WebAuthorizeOptions,
WebAuthorizeParameters,
Expand Down Expand Up @@ -163,6 +164,40 @@ const Auth0Provider = ({
[client]
);

const saveCredentials = useCallback(
async (
credentials: Credentials
): Promise<Credentials | undefined> => {
try {
await client.credentialsManager.saveCredentials(
credentials
);
const newCredentials = await getCredentials()
return newCredentials;
} catch (error) {
dispatch({ type: 'ERROR', error });
return;
}
},
[client]
);

const refreshToken = useCallback(
async (
refreshTokenOptions: RefreshTokenOptions
): Promise<Credentials | undefined> => {
try {
const credentials = await client.auth.refreshToken(refreshTokenOptions);
const newCredentials = saveCredentials(credentials)
return newCredentials;
} catch (error) {
dispatch({ type: 'ERROR', error });
return;
}
},
[client]
);

const sendSMSCode = useCallback(
async (parameters: PasswordlessWithSMSOptions) => {
try {
Expand Down Expand Up @@ -351,6 +386,8 @@ const Auth0Provider = ({
getCredentials,
clearCredentials,
requireLocalAuthentication,
refreshToken,
saveCredentials
}),
[
state,
Expand All @@ -368,6 +405,8 @@ const Auth0Provider = ({
getCredentials,
clearCredentials,
requireLocalAuthentication,
refreshToken,
saveCredentials
]
);

Expand Down
4 changes: 3 additions & 1 deletion src/hooks/use-auth0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ import Auth0Context, { Auth0ContextInterface } from './auth0-context';
* clearSession,
* getCredentials,
* clearCredentials,
* requireLocalAuthentication
* requireLocalAuthentication,
* refreshToken,
* saveCredentials
* } = useAuth0();
* ```
*
Expand Down