如何像我们使用 axios 身份验证选项一样通过 apollo 客户端传递应用程序凭据

How to pass application credentials through apollo client like we do with axios auth options

我想知道如何像在 axios 中那样将应用程序凭据(甚至是通过代码的用户凭据)传递给 apollo 客户端。

在 axios 中 -

const data = await axios({
  method: "POST",
  url: `${SOME_URL}`,
  auth: {
    username: USER,   //like this//
    password: PASS,
  },
  data: req.body,
  headers: { Accept: "application/json" },
});

对于 apollo 客户端,我使用了 apollo-link-http,我的设置如下所示 -

import fetch from "unfetch";
import { ApolloClient } from "apollo-client";
import { from } from "apollo-link";
import { onError } from "apollo-link-error";
import { createHttpLink } from "apollo-link-http";

const client = new ApolloClient({
  link: from([errorLink, standardVariablesLink, typenameCleanerLink, createHttpLink({ uri: "https://graphql-backend/graphql", fetch })]),
  cache,
});

我尝试在 createHttpLink 对象中添加 credentials option 作为 credentials: ${USER}:${PASS} 或作为对象

credentials: {
  user: USER,
  password: PASS
}

但这没有用。

感谢任何帮助。谢谢!!

问题:

axios 中的 auth 是什么? ... 搜索一下:basic auth 选项! axios 在内部将其转换为 header。

Apollo 客户端不太好...你需要将参数转换成 header 本身并使用这种方式:

 const link = createHttpLink({   
   headers: {     
     authorization: "Basic btoa_converted_username_password";   
   }, 

axios 中的 auth 选项只是构造 Basic Authorization header 的 shorthand 方法。为了构造要包含在 header 中的凭据值,您执行以下操作:

  • The username and the password are combined with a colon (aladdin:opensesame).
  • The resulting string is base64 encoded (YWxhZGRpbjpvcGVuc2VzYW1l).

所以你可以这样做:

createHttpLink({
  uri: '...',
  headers: {
    Authorization: `Basic ${window.btoa(`${username}:${password}`)}`,
  }
})

如果您是 运行 Node.js 中的此代码,您将使用以下代码代替 btoa

Buffer.from(`${username}:${password}`).toString('base64')

另请注意,如果此代码是 运行 client-side,您可能希望使用 setContext 动态注入 header。