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

Add support for resource owner password flow #1039

Merged
merged 2 commits into from
Jan 27, 2025
Merged
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
6 changes: 1 addition & 5 deletions example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,4 @@ The application will be built and launched on the specified platform, allowing y
### To run on different Auth0 Application

1. Change the `clientId` and `domain` value in `example/src/auth0-configuration.js`
2. For Android, Change the `auth0Domain` value in `example/android/app/build.gradle`

```
manifestPlaceholders = [auth0Domain: "YOUR_DOMAIN_HERE", auth0Scheme: "${applicationId}"]
```
2. For Android, Change the `android:host` values in `example/android/app/src/main/AndroidManifest.xml`
4 changes: 2 additions & 2 deletions example/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@
<category android:name="android.intent.category.BROWSABLE" />

<data
android:host="venkat-desu.us.auth0.com"
android:host="auth0-domain"
android:pathPrefix="/android/${applicationId}/callback"
android:scheme="${applicationId}.auth0" />
<data
android:host="brucke.auth0.com"
android:host="auth0-domain"
android:pathPrefix="/android/${applicationId}/callback"
android:scheme="${applicationId}.auth0" />
</intent-filter>
Expand Down
4 changes: 2 additions & 2 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ const SecondScreen = () => {
const SecondScreenProvider = () => {
return (
<Auth0Provider
domain="venkat-desu.us.auth0.com"
clientId="Wy9qORYVTokJFuJsvbXa2JJ6dDQhBGzI"
domain={config.domainSecondScreen}
clientId={config.clientIdSecondScreen}
>
<SecondScreen />
</Auth0Provider>
Expand Down
6 changes: 4 additions & 2 deletions example/src/auth0-configuration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const config = {
clientId: 'u7KBoASmHOpIFqwp77tmGRHnUVaMupBj',
domain: 'brucke.auth0.com',
clientId: 'your-client-id',
domain: 'your-domain',
clientIdSecondScreen: 'your-client-id',
domainSecondScreen: 'your-domain',
};

export default config;
59 changes: 59 additions & 0 deletions src/hooks/__tests__/use-auth0.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const mockAuth0 = {
loginWithOTP: jest.fn().mockResolvedValue(mockCredentials),
loginWithRecoveryCode: jest.fn().mockResolvedValue(mockCredentials),
hasValidCredentials: jest.fn().mockResolvedValue(),
passwordRealm: jest.fn().mockResolvedValue(mockCredentials),
},
credentialsManager: {
getCredentials: jest.fn().mockResolvedValue(mockCredentials),
Expand Down Expand Up @@ -781,6 +782,64 @@ describe('The useAuth0 hook', () => {
expect(result.current.error).toBe(mockAuthError);
});

it('can authorize with password realm, passing through all parameters', async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
});

let promise = result.current.authorizeWithPasswordRealm({
username: '[email protected]',
password: 'random-password',
realm: 'react-native-sample-app',
});

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

expect(mockAuth0.auth.passwordRealm).toHaveBeenCalledWith({
username: '[email protected]',
password: 'random-password',
realm: 'react-native-sample-app',
});

let credentials;
await act(async () => {
credentials = await promise;
});
expect(credentials).toEqual({
idToken:
'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5jb20iLCJhdWQiOiJjbGllbnQxMjMiLCJuYW1lIjoiVGVzdCBVc2VyIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwicGljdHVyZSI6Imh0dHBzOi8vaW1hZ2VzL3BpYy5wbmcifQ==.c2lnbmF0dXJl',
accessToken: 'ACCESS TOKEN',
});
});

it('sets the user prop after successful authentication', async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
});

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

expect(result.current.user).toMatchObject({
name: 'Test User',
familyName: 'User',
picture: 'https://images/pic.png',
});
});

it('does not set user prop when authentication fails', async () => {
mockAuth0.auth.passwordRealm.mockRejectedValue(mockAuthError);
const { result } = renderHook(() => useAuth0(), {
wrapper,
});

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

expect(result.current.user).toBeNull();
expect(result.current.error).toBe(mockAuthError);
});

it('can clear the session', async () => {
const { result } = renderHook(() => useAuth0(), {
wrapper,
Expand Down
8 changes: 8 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,
PasswordRealmOptions,
} from '../types';

export interface Auth0ContextInterface<TUser extends User = User>
Expand Down Expand Up @@ -105,6 +106,12 @@ export interface Auth0ContextInterface<TUser extends User = User>
* Clears the user's credentials without clearing their web session and logs them out.
*/
clearCredentials: () => Promise<void>;
/**
* Authorize user with credentials using the Password Realm Grant. See {@link Auth#passwordRealm}
*/
authorizeWithPasswordRealm: (
parameters: PasswordRealmOptions
) => Promise<Credentials | undefined>;
}

export interface AuthState<TUser extends User = User> {
Expand Down Expand Up @@ -143,6 +150,7 @@ const initialContext = {
clearSession: stub,
getCredentials: stub,
clearCredentials: stub,
authorizeWithPasswordRealm: stub,
};

const Auth0Context = createContext<Auth0ContextInterface>(initialContext);
Expand Down
19 changes: 19 additions & 0 deletions src/hooks/auth0-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
User,
WebAuthorizeOptions,
WebAuthorizeParameters,
PasswordRealmOptions,
} from '../types';
import { CustomJwtPayload } from '../internal-types';
import { convertUser } from '../utils/userConversion';
Expand Down Expand Up @@ -301,6 +302,22 @@ const Auth0Provider = ({
[client]
);

const authorizeWithPasswordRealm = useCallback(
async (parameters: PasswordRealmOptions) => {
try {
const credentials = await client.auth.passwordRealm(parameters);
const user = getIdTokenProfileClaims(credentials.idToken);
await client.credentialsManager.saveCredentials(credentials);
dispatch({ type: 'LOGIN_COMPLETE', user });
return credentials;
} catch (error) {
dispatch({ type: 'ERROR', error });
return;
}
},
[client]
);

const hasValidCredentials = useCallback(
async (minTtl: number = 0) => {
return await client.credentialsManager.hasValidCredentials(minTtl);
Expand Down Expand Up @@ -334,6 +351,7 @@ const Auth0Provider = ({
clearSession,
getCredentials,
clearCredentials,
authorizeWithPasswordRealm,
}),
[
state,
Expand All @@ -350,6 +368,7 @@ const Auth0Provider = ({
clearSession,
getCredentials,
clearCredentials,
authorizeWithPasswordRealm,
]
);

Expand Down
5 changes: 3 additions & 2 deletions src/hooks/use-auth0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ import Auth0Context, { Auth0ContextInterface } from './auth0-context';
* clearSession,
* getCredentials,
* clearCredentials,
* requireLocalAuthentication
* requireLocalAuthentication,
* authorizeWithPasswordRealm,
* } = useAuth0();
* ```
*
*
* Refer to {@link Auth0ContextInterface} on how to use the above methods.
*/
const useAuth0 = () => useContext(Auth0Context);
Expand Down
Loading