I am trying to get a basic Rails, Graphql, Apollo-Client setup working but having trouble with 422 errors 'invalid auth token' on the rails side.
Does my use of apollo look wrong?
It is a Rails 5 app with graphql gem and apollo client.
const csrfToken = document.getElementsByName('csrf-token')[0].content
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri: '/graphql',
credentials: 'same-origin',
headers: {
'X-CSRF-Token': csrfToken
}
}),
});
client.query({
query: gql`
query Camillo2 {
user {
id
email
created_at
}
}
`,
})
.then(data => console.log(data))
.catch(error => console.error(error));
Rails log:
Started POST "/graphql" for ::1 at 2017-03-10 08:51:58 -0800
Processing by GraphqlController#create as */*
Parameters: {"query"=>"query Camillo2 {\n user {\n id\n email\n created_at\n __typename\n }\n}\n", "operationName"=>"Camillo2", "graphql"=>{"query"=>"query Camillo2 {\n user {\n id\n email\n created_at\n __typename\n }\n}\n", "operationName"=>"Camillo2"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
Your GraphQL API probably needs to control which users can see and interact with the various data it provides. Authentication is determining whether a given user is logged in, and subsequently determining which user someone is. Authorization is then determining what a given user has permission to do or see.
Authenticating GraphQL is quite simple. We make use of queries and mutations. For a user to have access he has to register first, that's why we have register pages on almost all websites. The registration hits a particular endpoint, for example, it is usually like this https://URL_HERE/register API in a REST endpoint.
Since Apollo 2.0 and according to
https://github.com/apollographql/apollo-client/blob/master/Upgrade.md
Just do this way
const csrfToken = document.querySelector('meta[name=csrf-token]').getAttribute('content');
const client = new ApolloClient({
link: new HttpLink({
credentials: 'same-origin',
headers: {
'X-CSRF-Token': csrfToken
}
}),
cache: new InMemoryCache()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With