Search code examples
node.jsauthenticationgraphqlkeystonejs

Perform an authenticated keystone.js / GraphQL API query


I am new to Keystone.js and GraphQL. So far I have been able to successfully execute the following API queries (taken from this page) via a POST request:

const SIGNIN = `mutation signin($identity: String, $secret: String) {
  authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
    item {
      id
      name
    }
  }
}`;

// Returns id and name of authenticated user

and

const GET_ALL_POSTS = `query GetPosts {
  allPosts {
    name
    id
  }
}`;

// Returns id and name of all posts (if no access controls)

If I set access controls for the list Post I get an access error from the second query as expected, but I can't work how to then perform an authenticated query for allPosts, e.g. I want:

  • To (programatically) authenticate a user by their email and password
  • If successful, run a query for allPosts and return the results

What am I doing wrong?


Solution

  • The answer is to first submit the query below, to authenticate your user and generate an access token:

    query: `mutation ($identity: String, $secret: String) {
      authenticate: authenticateUserWithPassword(email: $identity, password: $secret) {
        token
      }
    }`
    

    Subsequent queries are then authenticated by adding the provided token to your headers of your request with:

    'Authorization: Bearer <token>'.
    

    Further information here.

    More generally, the GraphQL playground is well worth a look for anyone getting into keystonejs and new to GraphQL.