Authentication


Unless all of the data you are loading is completely public, your app has some sort of users, accounts and permissions systems. If different users have different permissions in your application, then you need a way to tell the server which user is associated with each request.

Apollo Client uses the ultra flexible Apollo Link that includes several options for authentication.

If your app is browser based and you are using cookies for login and session management with a backend, tell your network interface to send the cookie along with every request. Pass the credentials option e.g. credentials: 'same-origin' if your backend server is the same domain, as shown below, or else credentials: 'include' if your backend is a different domain.

JavaScript
1const link = createHttpLink({
2  uri: '/graphql',
3  credentials: 'same-origin'
4});
5
6const client = new ApolloClient({
7  cache: new InMemoryCache(),
8  link,
9});

This option is passed through to the fetch implementation used by the HttpLink when sending the query.

Note: the backend must also allow credentials from the requested origin. e.g. if using the popular 'cors' package from npm in node.js, the following settings would work in tandem with the above apollo client settings:

JavaScript
1// enable cors
2var corsOptions = {
3  origin: '<insert uri of front-end domain>',
4  credentials: true // <-- REQUIRED backend setting
5};
6app.use(cors(corsOptions));

Another common way to identify yourself when using HTTP is to send along an authorization header. Add an authorization header to every HTTP request by chaining together Apollo Links. In this example, we'll pull the login token from localStorage every time a request is sent:

ReactJS example:

JavaScript
1import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
2import { setContext } from '@apollo/client/link/context';
3
4const httpLink = createHttpLink({
5  uri: '/graphql',
6});
7
8const authLink = setContext((_, { headers }) => {
9  // get the authentication token from local storage if it exists
10  const token = localStorage.getItem('token');
11  // return the headers to the context so httpLink can read them
12  return {
13    headers: {
14      ...headers,
15      authorization: token ? `Bearer ${token}` : "",
16    }
17  }
18});
19
20const client = new ApolloClient({
21  link: authLink.concat(httpLink),
22  cache: new InMemoryCache()
23});

VueJS example:

JavaScript
1import ApolloClient from "apollo-client";
2import { HttpLink } from "apollo-link-http";
3import { ApolloLink, concat } from "apollo-link";
4import { InMemoryCache } from "apollo-cache-inmemory";
5import { getMainDefinition } from "apollo-utilities";
6
7const httpLink = new HttpLink({ uri: process.env.VUE_APP_API_TARGET });
8
9const authMiddleware = new ApolloLink((operation, forward) => {
10  // add the authorization to the headers
11const token = localStorage.getItem('token');
12  operation.setContext({
13    headers: {
14      authorization: token ? `Bearer ${token}` : "",
15    },
16  });
17  return forward(operation);
18});
19export const apolloClient = new ApolloClient({
20  link: concat(authMiddleware, httpLink),
21  cache: new InMemoryCache(),
22});
23

The server can use that header to authenticate the user and attach it to the GraphQL execution context, so resolvers can modify their behavior based on a user's role and permissions.

Reset store on logout

Since Apollo caches all of your query results, it's important to get rid of them when the login state changes.

The most straightforward way to ensure that the UI and store state reflects the current user's permissions is to call client.resetStore() after your login or logout process has completed. This will cause the store to be cleared and all active queries to be refetched. If you just want the store to be cleared and don't want to refetch active queries, use client.clearStore() instead. Another option is to reload the page, which will have a similar effect.

JavaScript
1const PROFILE_QUERY = gql`
2  query CurrentUserForLayout {
3    currentUser {
4      login
5      avatar_url
6    }
7  }
8`;
9
10function Profile() {
11  const { client, loading, data: { currentUser } } = useQuery(
12    PROFILE_QUERY,
13    { fetchPolicy: "network-only" }
14  );
15
16  if (loading) {
17    return <p className="navbar-text navbar-right">Loading...</p>;
18  }
19
20  if (currentUser) {
21    return (
22      <span>
23        <p className="navbar-text navbar-right">
24          {currentUser.login}
25          &nbsp;
26          <button
27            onClick={() => {
28              // call your auth logout code then reset store
29              App.logout().then(() => client.resetStore());
30            }}
31          >
32            Log out
33          </button>
34        </p>
35      </span>
36    );
37  }
38
39  return (
40    <p className="navbar-text navbar-right">
41      <a href="/login/github">Log in with GitHub</a>
42    </p>
43  );
44}
Feedback

Edit on GitHub

Forums