React&Apollo,用户登录时如何设置授权头?

时间:2019-10-25 10:23:06

标签: reactjs graphql apollo apollo-client

假设我们最初创建这样的客户

const client = new ApolloClient({
  uri:'https://api.com/graphql'
})

此api最初具有一些暴露的变体,例如signInsignUp,不需要身份验证。

用户可以在某处登录并接收auth令牌。现在,需要在我们的阿波罗client上将此令牌设置为标头,即

headers: {
   Authorization: `Bearer ${token}`
}

是否可以“即时”更新client以应用此标头,以便将来的api请求使用它?

1 个答案:

答案 0 :(得分:3)

根据documentation,您可以执行以下操作:

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

更新

您可以使用'apollo-boost'

更新令牌
  

请注意,上面的示例正在使用apollo-client软件包中的ApolloClient。仍然可以使用apollo-boost包中的ApolloClient修改标头,但是由于apollo-boost不允许修改它使用的HttpLink实例,因此标头必须作为配置参数传递:

import ApolloClient from 'apollo-boost'

const client = new ApolloClient({
  request: (operation) => {
    const token = localStorage.getItem('token')
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : ''
      }
    })
  }
})