DEV Community

Gerbrand van Dieyen
Gerbrand van Dieyen

Posted on • Originally published at software-creation.nl on

1

Using Swagger to access your secured api

Swagger, http://swagger.io/ is a great way make your api accessible. Not only documentation is provided, but your users, your co-developers or your self can try out your api. But what if your API is secured using a token based security system like webtokens?

Well, it’s quite easy to modify your swagger frontend to allow adding any token to requests.

First somewhere in your swagger template file, add the following:

<form onsubmit="addApiKeyAuthorization()">
                <div class="input">
                    <input placeholder="access_token" id="input_apiKey" name="input_apiKey" type="text">
                    <input type="submit" value="Authenticate"/>
                </div>
            </form>

Then in the header add the following Javascript

<script>
    function addApiKeyAuthorization(){
        var apiKey = getUrlVars().input_apiKey;

        if (apiKey && apiKey.trim() != "") {
            console.log("initialzing oauth via api-key")
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + apiKey, "header");
            window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth );
            //For clarity, also add in the input field
            $('#input_apiKey')[0].value=apiKey
        }
    }

</script>

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more