Skip to content

Instantly share code, notes, and snippets.

@craigmit
Created February 19, 2021 01:15
Show Gist options
  • Save craigmit/0cce78ffe33ca3551fbcc35016e8b3e2 to your computer and use it in GitHub Desktop.
Save craigmit/0cce78ffe33ca3551fbcc35016e8b3e2 to your computer and use it in GitHub Desktop.
GraphiQL that sets the Authorization from a # parameter
<!DOCTYPE html>
<!--
Example usage is: graphiqlSetAuth.html#[JWT_TOKEN]
The JWT TOKEN with then automatically be set in the header, and removed from the URL.
-->
<html lang="en">
<head>
<meta charset="utf-8" />
<meta content="noindex" name="robots" />
<meta content="origin" name="referrer" />
<meta content="width=device-width, initial-scale=1" name="viewport" />
<title>GraphiQL With Auth</title>
<style>
body {
height: 100vh;
margin: 0;
overflow: hidden;
}
#splash {
color: #333;
display: flex;
flex-direction: column;
font-family: system, -apple-system, "San Francisco", ".SFNSDisplay-Regular", "Segoe UI", Segoe, "Segoe WP", "Helvetica Neue", helvetica, "Lucida Grande", arial, sans-serif;
height: 100vh;
justify-content: center;
text-align: center;
}
</style>
<script src="/vendor/graphiql/es6-promise.auto.min.js"></script>
<script src="/vendor/graphiql/fetch.min.js"></script>
<script src="/vendor/graphiql/react.min.js"></script>
<script src="/vendor/graphiql/react-dom.min.js"></script>
<link href="/vendor/graphiql/graphiql.min.css" rel="stylesheet" />
<link href="/vendor/graphiql/favicon.ico" rel="icon" type="image/x-icon">
<script src="/vendor/graphiql/graphiql.min.js"></script>
<script src="/vendor/graphiql/subscriptions-transport-ws-browser-client.js"></script>
<script src="/vendor/graphiql/graphiql-subscriptions-fetcher-browser-client.js"></script>
</head>
<body>
<div id="splash">
Loading&hellip;
</div>
<script>
var editorThemeCss = ''
if (editorThemeCss !== '') {
var link = document.createElement("link")
link.href = editorThemeCss
link.type = "text/css"
link.rel = "stylesheet"
link.media = "screen,print"
document.getElementsByTagName("head")[0].appendChild(link)
}
// Parse the search string to get url parameters.
var search = window.location.search
var parameters = {}
search.substr(1).split('&').forEach(function(entry) {
var eq = entry.indexOf('=')
if (eq >= 0) {
parameters[decodeURIComponent(entry.slice(0, eq))] =
decodeURIComponent(entry.slice(eq + 1))
}
})
// if variables was provided, try to format it.
if (parameters.variables) {
try {
parameters.variables = JSON.stringify(JSON.parse(parameters.variables), null, 2)
} catch (e) {
// Do nothing, we want to display the invalid JSON as a string, rather
// than present an error.
}
}
// When the query and variables string is edited, update the URL bar so
// that it can be easily shared
function onEditQuery(newQuery) {
parameters.query = newQuery
updateURL()
}
function onEditVariables(newVariables) {
parameters.variables = newVariables
updateURL()
}
function onEditOperationName(newOperationName) {
parameters.operationName = newOperationName
updateURL()
}
function updateURL() {
var newSearch = '?' + Object.keys(parameters).filter(function(key) {
return Boolean(parameters[key])
}).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key])
}).join('&')
history.replaceState(null, null, newSearch)
}
var headers
const tokenParam = window.location.hash.substr(1);
if (tokenParam) {
headers = {"Authorization": "Bearer " + tokenParam}
window.history.replaceState({}, document.title, window.location.href.split('#')[0]);
}
function addRequiredHeadersIfAbsent() {
if (!headers['Accept']) {
headers['Accept'] = 'application/json'
}
if (!headers['Content-Type']) {
headers['Content-Type'] = 'application/json'
}
}
function onEditHeaders(newHeaders) {
try {
headers = JSON.parse(newHeaders)
} catch (e) {
headers = {}
}
addRequiredHeadersIfAbsent()
}
// Defines a GraphQL fetcher using the fetch API. You're not required to
// use fetch, and could instead implement graphQLFetcher however you like,
// as long as it returns a Promise or Observable.
function graphQLFetcher(graphQLParams) {
// This example expects a GraphQL server at the path /graphql.
// Change this to point wherever you host your GraphQL server.
return fetch('/graphql', {
method: 'post',
headers: headers,
body: JSON.stringify(graphQLParams),
credentials: 'include'
}).then(function(response) {
return response.text()
}).then(function(responseBody) {
try {
return JSON.parse(responseBody)
} catch (error) {
return responseBody
}
})
}
var loc = window.location, newUri
if (loc.protocol === "https:") {
newUri = "wss:"
} else {
newUri = "ws:"
}
newUri += "//" + loc.host
newUri += "/subscriptions"
var subscriptionsClient = new window.SubscriptionsTransportWs.SubscriptionClient(newUri, {
reconnect: false,
timeout: 30000
})
var subscriptionsFetcher = window.GraphiQLSubscriptionsFetcher.graphQLFetcher(subscriptionsClient,
graphQLFetcher)
var props = {"headerEditorEnabled":"true"}
if (parameters.query) {
props.query = parameters.query
}
if (parameters.variables) {
props.variables = parameters.variables
}
if (parameters.operationName) {
props.operationName = parameters.operationName
}
props.fetcher = subscriptionsFetcher
props.onEditQuery = onEditQuery
props.onEditVariables = onEditVariables
props.onEditOperationName = onEditOperationName
props.onEditHeaders = onEditHeaders
props.headers = props.headers || '{}'
if (headers) {
var newHeaders = Object.assign({}, JSON.parse(props.headers), headers)
props.headers = JSON.stringify(newHeaders, undefined, 2)
}
onEditHeaders(props.headers)
// Render <GraphiQL /> into the body.
ReactDOM.render(
React.createElement(GraphiQL, props),
document.body
)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment