diff --git a/packages/auth/src/AuthProvider.tsx b/packages/auth/src/AuthProvider.tsx index 2b6447a5af09..00fae09c2efa 100644 --- a/packages/auth/src/AuthProvider.tsx +++ b/packages/auth/src/AuthProvider.tsx @@ -107,6 +107,15 @@ export class AuthProvider extends React.Component< constructor(props: AuthProviderProps) { super(props) this.rwClient = createAuthClient(props.client, props.type) + + // Add observer if the auth client supports it + // @TODO: Do we need to worry about cancelling the event handler? + // I don't think AuthProvider ever unmounts + if (this.rwClient.onTokenChange) { + this.rwClient.onTokenChange(() => { + this.getToken() + }) + } } async componentDidMount() { @@ -115,6 +124,7 @@ export class AuthProvider extends React.Component< } getCurrentUser = async (): Promise> => { + const authToken = await this.getToken() const response = await window.fetch( `${window.__REDWOOD__API_PROXY_PATH}/graphql`, { @@ -122,7 +132,7 @@ export class AuthProvider extends React.Component< headers: { 'content-type': 'application/json', 'auth-provider': this.rwClient.type, - authorization: `Bearer ${this.state.authToken}`, + authorization: `Bearer ${authToken}`, }, body: JSON.stringify({ query: diff --git a/packages/auth/src/authClients/firebase.ts b/packages/auth/src/authClients/firebase.ts index f62468ee4f0b..74eb6eeb649d 100644 --- a/packages/auth/src/authClients/firebase.ts +++ b/packages/auth/src/authClients/firebase.ts @@ -35,5 +35,6 @@ export const firebase = (client: Firebase): AuthClient => { }, getToken: async () => client.auth().currentUser?.getIdToken() ?? null, getUserMetadata: async () => client.auth().currentUser, + onTokenChange: client.auth().onIdTokenChanged, } } diff --git a/packages/auth/src/authClients/index.ts b/packages/auth/src/authClients/index.ts index 47543c4a5abb..4b02389d2545 100644 --- a/packages/auth/src/authClients/index.ts +++ b/packages/auth/src/authClients/index.ts @@ -56,6 +56,7 @@ export interface AuthClient { getUserMetadata(): Promise client: SupportedAuthClients type: SupportedAuthTypes + onTokenChange?(callback: () => void): void } export const createAuthClient = (