Apollo Client: Client Certificate Authentication

Hello everyone, I’m looking to set up Client Certificate Authentication with the Apollo Client.

I know how to do this with a basic node request which would look something like this

var fs = require('fs');
var https = require('https');
var options = {
    hostname: 'localhost',
    port: 4433,
    path: '/',
    method: 'GET',
    key: fs.readFileSync('ssl/client1-key.pem'),
    cert: fs.readFileSync('ssl/client1-crt.pem'),
    ca: fs.readFileSync('ssl/ca-crt.pem') 
};

var req = https.request(options, function(res) {
    res.on('data', function(data) {
        process.stdout.write(data);
    });
});
req.end();
req.on('error', function(e) {
    console.error(e);
});

But I was wondering if there were examples somewhere of writing a custom networkInterface or middleware that would ensure that certificates are passed with every request.

Kind regards,
Kris

Hi Kris,
I used fetchOptions.agent to set key, cert and ca properties.

import { InMemoryCache, NormalizedCacheObject } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import crossFetch from 'cross-fetch';
import fs from 'fs';
import { Agent } from 'https';

function getApolloClient(): ApolloClient<NormalizedCacheObject> {

  const link = createHttpLink({
    'https://localhost:8000/graphql',
    fetch: crossFetch,
    fetchOptions: {
      agent: new Agent({
        key: fs.readFileSync('./certs/ns_test_key.pem'),
        cert: fs.readFileSync('./certs/ns_test_local_cert.pem'),
        ca: [fs.readFileSync('./certs/server_local_cert.pem')],
      }),
    },
  });

  const defaultOptions: object = {
    query: {
      fetchPolicy: 'no-cache',
    },
    mutate: {
      fetchPolicy: 'no-cache',
    },
  };

  return new ApolloClient({
    defaultOptions,
    link,
    cache: new InMemoryCache(),
  });
}

Andrej