使用Rails,Graphql,Apollo客户端的无效令牌

dne*_*man 5 ruby-on-rails authenticity-token graphql apollo-client

我试图让一个基本的Rails,Graphql,Apollo-Client设置工作,但在rails侧遇到422个错误'无效的auth令牌'.

我使用apollo看起来不对吗?

它是一个带有graphql gem和apollo客户端的Rails 5应用程序.

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));  
Run Code Online (Sandbox Code Playgroud)

Rails日志:

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)
Run Code Online (Sandbox Code Playgroud)

小智 7

自从阿波罗2.0和根据

https://github.com/apollographql/apollo-client/blob/master/Upgrade.md

就这样做吧

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()
});
Run Code Online (Sandbox Code Playgroud)


rmo*_*lgo 1

前几天我正在试验 Apollo on Rails,以下是对我有用的配置:

var RailsNetworkInterface = apollo.createNetworkInterface('/graphql', {
  credentials: 'same-origin',
  headers: {
    'X-CSRF-Token': $("meta[name=csrf-token]").attr("content"),
  }
});

var client = new apollo.ApolloClient({networkInterface: RailsNetworkInterface})

client.query({ query: gql`{ event(id: 7) { name } }`})
Run Code Online (Sandbox Code Playgroud)

但是,看起来你的也同样有效!

您能否确认是否将正确的令牌发送到服务器?例如,如果您打开 Chrome devtools 的网络选项卡,然后进行查询,您可以X-CSRF-Token在“请求标头”部分中看到 吗?

此外,Rails 可能正在更新 DOM 中的 CSRF 令牌,但 NetworkInterface 保留旧的、过时的 CSRF 令牌。您能否确认“请求标头”部分中的令牌与标记中的当前<meta>值匹配?(令我惊讶的是,我自己使用 Turbolinks Classic 时没有遇到这个问题。)