Home » WebServices » GraphQL » Apollo Server and Secured Playground

Apollo Server and Secured Playground

In the last article of the series on how to create a GraphQL server with TypeScript and Apollo I demonstrate how easy is to setup the playground. However, there is still a piece that is missing and is authentication. In first post, I explicitly mentioned that every request goes first through Apache that has a special module that handles authentication. Apache will set in the HTTP request some headers with authorization information like a bearer token. At the moment, the playground receives the header but not for any subsequent calls it performs. It leads to HTTP requests that are not authenticated. In my particular case, the request was performing a HTTP 302 trying to redirect to the web portal to get authenticated. Great! The security kick-in! However, how can we force subsequent code to have the header in the playground was the question.

Fortunately, the ApolloServerConfig has the property playground that can be something else than a boolean. It can be a ISettings. The interface has a “request.credentials” and by default “omit”. Changing the default to “same-origin” will carry the missing headers.

playground: {
    settings: {
        "general.betaUpdates": false,
        "editor.theme": "dark",
        "editor.reuseHeaders": true,
        "tracing.hideTracingResponse": false,
        "editor.fontSize": 14,
        "editor.fontFamily": "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace",
        "request.credentials": "same-origin"
    }
}

 I had to specify additional configuration because the TypeScript definition type has all the field required, so I copy pasted the default value I found under the gear icon in the playground.

The playground’s configurations

Summary

In this article we configured subsequent calls to keep the authentication set in the former request that brought the playground in the browser. In the next article we will see how to read the content of the header to know which user is authenticated. The next step is crucial to have a user experience secured and tailored to the active user.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.