question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add JWT authorization header in Swagger v3

See original GitHub issue

I’m looking for a solution to add a JWT authorization header to each request like they did in this thread

Their solution for Swagger v2:

function addApiKeyAuthorization() {
	var key = encodeURIComponent($('#input_apiKey')[0].value);
	if (key && key.trim() != "") {
		var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header");
		window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth);
		log("added key " + key);
	}
}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:25
  • Comments:37 (7 by maintainers)

github_iconTop GitHub Comments

34reactions
fernandocamargoaicommented, Apr 26, 2017

After quite some time spent trying to figure it out, I found a workaround to do what I wanted. Basically, right after the basic configuration (index.html), I added the following code:

ui.authActions.authorize({JWT: {name: "JWT", schema: {type: "apiKey", in: "header", name: "Authorization", description: ""}, value: "Bearer <JWT>"}})

This is how my security definition is:

securityDefinitions:
  JWT:
    description: ""
    type: "apiKey"
    name: "Authorization"
    in: "header"
12reactions
srikanthpscommented, Feb 14, 2018

This is what I have done to get it working. I have Swagger Configuration coming from Server in Java Jersey based end point.

    Swagger swagger = new Swagger();
    // other calls on swagger object....
    
    ApiKeyAuthDefinition apiKeyAuth = new ApiKeyAuthDefinition();
    apiKeyAuth.setName("Authorization");
    apiKeyAuth.setIn(In.HEADER);
    swagger.securityDefinition("Authorization", apiKeyAuth);

This basically has effect of adding below to swagger JSON file:

"securityDefinitions":{"Authorization":{"vendorExtensions":{},"type":"apiKey","name":"Authorization","in":"header"}}

Due to above JSOn fragment, the swagger UI displays an “Authorize” button.

The issue I was observing was that even though swagger UI was collecting value for token, it was not adding the header “Authorization” when it made the REST API call. So, I decided that I will have to add the header programmatically. To do that, I needed a means to obtain the value of token I entered in the pop-up dialog that is displayed on clicking “Authorize” button.

In “index.html”, I redefined the authorize method - like below - wherein I capture the authorization value and store in a variable.

  var authToken = "None";
  var originalAuthorize = ui.authActions.authorize;
  ui.authActions.authorize = function(authorization) {
	  authToken = authorization.Authorization.value;
	  originalAuthorize(authorization);
  };
  
  window.ui = ui

Also, I had to add code to append header by implementing preFetch in ui object

  const ui = SwaggerUIBundle({
    url: window.location.protocol + '//' + window.location.host + window.location.pathname.replace(/swagger.+/,"rest/swagger.json"),
    dom_id: '#swagger-ui',
    configs: {
        preFetch: function(req) {
                if (authToken) {
                	req.headers["Authorization"] = "Bearer " + authToken;
                }
                return req;
        }
    },
    tagsSorter: 'alpha',
    docExpansion: 'none',
    deepLinking: true,
    validatorUrl: null,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

The overall effect of this change is that whenever I enter an auth token in “Authorize” dialog, I save it in a variable - and later append it to each request as header. This seems to work for me. I am not sure whether this additional code is needed or not. What I observed that swagger-ui demo site also does not add headers automatically, so looks like this is needed to get everything working.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How To Add JWT Bearer Token Authorization Functionality In ...
In this article, you will learn how to add JWT Bearer Token Authorization Functionality in Swagger?
Read more >
Bearer Authentication - Swagger
In OpenAPI 3.0, Bearer authentication is a security scheme with type: http and scheme: bearer ... In the example above, it is "JWT",...
Read more >
Configure JWT Authentication for OpenAPI - Baeldung
In this tutorial, we learned how to configure JWT authentication to our OpenAPIs. Swagger-UI provides a tool to document and test the REST...
Read more >
JWT Authorization Header Swagger Open API v3.0 - YouTube
JWT Authorization Header Swagger Open API V3.0- https://www.thecodebuzz.com/ jwt - authorization - token - swagger -open-api-asp-net-core- 3 -0/ Adding ...
Read more >
How to Pass JWT Bearer Token in Swagger UI - YouTube
Here I have explain How to pass JWT bearer token in Swagger UI header. The Swagger UI will display the " Authorize "...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found