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

Configure ApolloProvider to always use fresh tokens #1609

Merged
merged 6 commits into from
Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 18 additions & 6 deletions packages/auth/src/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export interface AuthContextInterface {
/* Determining your current authentication state */
loading: boolean
isAuthenticated: boolean
authToken: string | null
authToken: string | null // @WARN! to be depracated
dac09 marked this conversation as resolved.
Show resolved Hide resolved
dac09 marked this conversation as resolved.
Show resolved Hide resolved
/* The current user's data from the `getCurrentUser` function on the api side */
currentUser: null | CurrentUser
/* The user's metadata from the auth provider */
Expand All @@ -25,6 +25,8 @@ export interface AuthContextInterface {
logOut(options?: unknown): Promise<void>
signUp(options?: unknown): Promise<void>
getToken(): Promise<null | string>
// To be removed once authToken is removed
getFreshToken(): Promise<null | string>
/**
* Fetches the "currentUser" from the api side,
* but does not update the current user state.
Expand Down Expand Up @@ -55,7 +57,7 @@ export interface AuthContextInterface {
export const AuthContext = React.createContext<AuthContextInterface>({
loading: true,
isAuthenticated: false,
authToken: null,
authToken: null, // @WARN! to be depracated
userMetadata: null,
currentUser: null,
})
Expand All @@ -69,7 +71,7 @@ type AuthProviderProps = {
type AuthProviderState = {
loading: boolean
isAuthenticated: boolean
authToken: string | null
authToken: string | null // @WARN! to be depracated
userMetadata: null | Record<string, any>
currentUser: null | CurrentUser
hasError: boolean
Expand All @@ -96,7 +98,7 @@ export class AuthProvider extends React.Component<
state: AuthProviderState = {
loading: true,
isAuthenticated: false,
authToken: null,
authToken: null, // @WARN! to be depracated
userMetadata: null,
currentUser: null,
hasError: false,
Expand All @@ -115,14 +117,16 @@ export class AuthProvider extends React.Component<
}

getCurrentUser = async (): Promise<Record<string, unknown>> => {
// Always get a fresh token, rather than use the one in state
const token = await this.getToken()
const response = await window.fetch(
`${window.__REDWOOD__API_PROXY_PATH}/graphql`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'auth-provider': this.rwClient.type,
authorization: `Bearer ${this.state.authToken}`,
authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query:
Expand Down Expand Up @@ -178,10 +182,17 @@ export class AuthProvider extends React.Component<
return authToken
}

// Note: Used by apollo middleware to get a fresh token
// State isn't changed, to prevent infinite loops
// Remove this, and call getToken when AuthProviderState.authToken is removed
getFreshToken = async () => {
return this.rwClient.getToken()
}
dac09 marked this conversation as resolved.
Show resolved Hide resolved

reauthenticate = async () => {
const notAuthenticatedState: AuthProviderState = {
isAuthenticated: false,
authToken: null,
authToken: null, // @WARN! to be depracated
currentUser: null,
userMetadata: null,
loading: false,
Expand Down Expand Up @@ -253,6 +264,7 @@ export class AuthProvider extends React.Component<
getCurrentUser: this.getCurrentUser,
hasRole: this.hasRole,
reauthenticate: this.reauthenticate,
getFreshToken: this.getFreshToken,
client,
type,
}}
Expand Down
1 change: 1 addition & 0 deletions packages/testing/src/MockProviders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const fakeUseAuth = (): AuthContextInterface => ({
logOut: async () => undefined,
signUp: async () => undefined,
getToken: async () => null,
getFreshToken: async () => null,
getCurrentUser: async () => null,
hasRole: () => false,
reauthenticate: async () => undefined,
Expand Down
30 changes: 27 additions & 3 deletions packages/web/src/components/RedwoodApolloProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import {
ApolloProvider,
ApolloClientOptions,
ApolloClient,
ApolloLink,
InMemoryCache,
useQuery,
useMutation,
createHttpLink,
} from '@apollo/client'
import { setContext } from '@apollo/client/link/context'

import type { AuthContextInterface } from '@redwoodjs/auth'
import { AuthContextInterface, useAuth } from '@redwoodjs/auth'

import {
FetchConfigProvider,
Expand All @@ -20,12 +23,33 @@ const ApolloProviderWithFetchConfig: React.FunctionComponent<{
config?: Omit<ApolloClientOptions<InMemoryCache>, 'cache'>
}> = ({ config = {}, children }) => {
const { uri, headers } = useFetchConfig()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could remove headers here since this is where the auth-token and type came from previously.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing so would save you an extra re-render.

Copy link
Collaborator Author

@dac09 dac09 Jan 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I intentionally didn't do that, wanted to remove this if/when FetchContext is removed if it makes sense?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that make sense.

const { getFreshToken, type: authProviderType } = useAuth()

const withToken = setContext(async () => {
const token = await getFreshToken()
return { token }
})

const authMiddleware = new ApolloLink((operation, forward) => {
const { token } = operation.getContext()

operation.setContext(() => ({
headers: {
...headers,
// Duped, because we may remove FetchContext at a later date
'auth-provider': authProviderType,
authorization: token ? `Bearer ${token}` : null,
},
}))
return forward(operation)
})

const httpLink = createHttpLink({ uri })

const client = new ApolloClient({
cache: new InMemoryCache(),
uri,
headers,
...config,
link: ApolloLink.from([withToken, authMiddleware.concat(httpLink)]),
})

return <ApolloProvider client={client}>{children}</ApolloProvider>
Expand Down