Authenticating ApolloClient

Hello everyone!
I need some help with how I authenticate apollo client queries to a 3rd party graphql server.

Right now, I have two cookies AuthToken and RefreshToken. AuthToken only lasts for 60 seconds, but I can get a new one with the given RefreshToken. My problem right now is that I set the Bearer token inside the ApolloClient. And in that object, I do not have access to doing queries to third parties, so I have no way to getting a new AuthToken. Does anyone have a better way to do this?

const httpLink = new HttpLink({
	uri: 'https://graphql.SERVER',
});

const authMiddleware = new ApolloLink((operation, forward) => {
	let AuthToken = Cookies.get('authToken');
	console.log('AuthToken', AuthToken);
	if (AuthToken) {
		operation.setContext(({ headers = {} }) => ({
			headers: {
				...headers,
				authorization: `Bearer ${AuthToken}`,
			},
		}));
	} else {
		operation.setContext(({ headers = {} }) => ({
			headers: {
				...headers,
			},
		}));
	}

	return forward(operation);
});

const link = createHttpLink({
	uri: `https://graphql.SERVER`,
});

const client = new ApolloClient({
	connectToDevTools: true,
	link: concat(authMiddleware, httpLink),
	cache,
	credentials: 'include',
});

export default client;

Is there a way to pass arguments to the client? That way I can pass the token to the client.

@martinowren anything you plug into the Apollo Link chain will be called on every request. This means you could store your token in some state container somewhere outside of Apollo Client, and just pull it from the container when you need it in the link chain. For example, you could store/update the token in localStorage and update your authMiddleware link to pull it from there. The Authentication section of the AC docs has an example of this.

1 Like

@hwillson , how would I go about updating it if I don’t have access to localStorage? Is there some way my application can deterministically update the link I created with setContext() with the new auth token?