Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
Apollo Server executeOperation with authorization headers

How do we pass headers to Apollo server executeOperation in tests?

There is mention about passing a headers object here

I'm trying to pass an auth header with or without a JWT token to test access control.

const result = await server.executeOperation({ query: query, http: { headers: { authorization: "" } } })

// Type '{ authorization: string; }' is not assignable to type 'Headers'.
//  Object literal may only specify known properties, and 'authorization' does not exist in type 'Headers'.ts(2322)

This results in a type error. There is a Headers class defined in the Apollo server types in fetch.d.ts but I'm un able to import to instantiate it.

Using "apollo-server": "^2.25.2". Any hints or links to get this going?


Update: as a work around I'm decrypting and decoding the JWT in the server context and passing an authenticated user around in there. Then I'm able to mock the whole context and create a new test server with the mocked context. It'd be nice to be able to user headers for more production like experience but this works for now.

import { mockDeep, mockReset } from 'jest-mock-extended'

interface Context {
  prisma: PrismaClient
  user: () => User|null
}

export const context = mockDeep<Context>()

export const testServer = new ApolloServer({
  typeDefs,
  resolvers,
  context
});

// ...

context.user.mockReturnValue({
  id: 1,
  name: "Foo",
  slug: "foo",
})

const res = await testServer.executeOperation({ query: query })
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

To solve this, I have created a 'fake' request object with the already decrypted JWT token that I used to initialize my third party auth object (keycloak) and pass to the apollo context. I need to initialize the keycloak object because I have authentication schema directives that require the keycloak object to be initialized.

 const req = {
      kauth: {
        grant: {
          access_token: {
            isExpired: () => {
              return false;
            },
            token: "abc",
            content: {
              email: "me@me.com",
              resource_access: {
                "my-api": {
                  roles: ["admin"],
                },
              },
            },
          },
        },
      },
    };

    server = new ApolloServer({
      schema,
      resolvers,
      dataSources: () => ({
        users,
      }),
      context: () => {
        return { kauth: new KeycloakContext({ req }) };
      },
    });
  });

Still, I would like a solution that is more native to apollo and not a work around.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda