Skip to Content

Inject Short-Lived Token into Upstream Requests

Published: 2022-05-23

You might have an upstream that has very high security standards. In order to authenticate against this upstream, you need to send a short-lived token alongside the request. This short-lived token can be obtained by authenticating against your Identity Provider on a per-request basis. Once the token is obtained, it needs to be injected into the upstream request.

First, let's configure our upstream so that we're forwarding the Authorization header from client requests:

// wundergraph.config.ts
const secureUpstream = introspect.graphql({
url: "http://localhost:8111",
loadSchemaFromString: someSchemaString,
headers: builder =>
builder.addClientRequestHeader("Authorization", "Authorization"),
});
const myApplication = new Application({
name: "app",
apis: [
secureUpstream,
],
});

The headers option on the upstream configuration defines that the "Authorization" header should be forwarded from the client request to the upstream request using the same name. If you're using this technique for multiple upstreams, you can use different Header names to avoid conflicts. What's missing is that we need to implement a hook to fetch the short-lived token and inject it into the client request headers.

// wundergraph.server.ts
import {configureWunderGraphServer} from "@wundergraph/sdk";
import type {HooksConfig} from "./generated/wundergraph.hooks";
import type {InternalClient} from "./generated/wundergraph.internal.client";
export default configureWunderGraphServer<HooksConfig,
InternalClient>((serverContext) => ({
hooks: {
mutations: {
draw: {
preResolve: async (ctx, input) => {
const token = await fetchShortLivedToken();
ctx.setClientRequestHeader('Authorization', 'Bearer ' + token);
}
}
},
}
}));

In this hook, we fetch the short-lived token from our Identity Provider and use the ctx.setClientRequestHeader method to inject it into the client request. This way, it's being picked up by the HTTP transport when we're sending a request to the upstream.

Conclusion#

  1. Configure the upstream to forward the Authorization header from client requests
  2. Implement a hook to fetch the short-lived token and inject it into the client request headers
  3. The WunderGraph HTTP will set the header on all upstream requests

Product

Comparisons

Subscribe to our newsletter!

Stay informed when great things happen! Get the latest news about APIs, GraphQL and more straight into your mailbox.

© 2022 WunderGraph