0

In my ServiceStack web service I have a global request filter that inspects the headers for the presence of an API Key (X-FooKey), this check is preventing the loading of the Swagger/Postman UI. I created a horrible hack for Postman to work by inspecting the dto type and comparing it to the dto for Postman, again, not very robust. Swagger on the other hand is a mess and I really don't want to mimic what I did with Postman, so I'm open to suggestions.

Ultimately I would like both plugins to be able to provide the key automatically, but that would more than likely entail a PR, which given my time constraints is unrealistic.

Thank you, Stephen

Stephen Patten
  • 6,333
  • 10
  • 50
  • 84

1 Answers1

3

In our current project we had the same issue. We're using the swagger plugin for servicestack and have a custom request header for an API key. We solved this quite easy by editing swagger-ui/index.html. Disadvantage is you can't let the file get updated by nuget, or merge manually.

Extend the html form with an additional input for the api key

<form id='api_selector'>
    <div id="login-logout">
        <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text" /></div>
        <div class='input'><input placeholder="username" id="input_username" name="username" type="text" /></div>
        <div class='input'><input placeholder="password" id="input_password" name="password" type="password" /></div>
        <div class='input'><a id="login" href="#">Login</a></div>
    </div>
</form>

In the javascript pieces change the apiKeyName:

window.swaggerUi = new SwaggerUi({
    apiKey: "",
    apiKeyName: "x-fookey"
});

And then edit the login function:

$('#login').on('click', function (event) {
    event.preventDefault();

    var apiKey = $('#input_apiKey').val();
    var username = $('#input_username').val();
    var password = $('#input_password').val();

    $.ajax({
        url: '../api/auth/credentials',
        type: 'POST',
        data: {
            UserName: username,
            Password: password
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-FooKey', apiKey);
        }
    });
});

In our API we only need the apikey header on the login request. To have it added to each request, see this SO question: How to get Swagger to send API key as a http instead of in the URL

Community
  • 1
  • 1
nickvane
  • 2,979
  • 2
  • 20
  • 23