Search code examples
angularswaggerangular7swagger-ui

Add Authorization key through code in angular swagger UI


I am trying to integrate swagger ui into an angular7 application. I am using the swagger-ui 3.37 from npm. API is using swagger 2.0 for docs. for It is working fine without authorization enabled in the API. Once authorization is enabled on the API side, I would like to add the authorization token through code so that users don't have to enter the authorization key manually for each endpoint.

I have added the below code in my component file. But it still not working.

onComplete: 
function() {
        swaggerui.preauthorizeApiKey("Authorization", usertoken);
      }

The authorization field still shows empty which needs to be entered manually everytime. I would like to set the authorization key through code which can be applied to all the end points and also would like to hide the "Authorize" button

Some help would be great.

Edit: Security Definition:

"securityDefinitions": {
    "Authorization": {
      "type": "apiKey",
      "description": "Filling bearer token here",
      "name": "Bearer",
      "in": "header"
    }
  }

swagger ui authorization is still empty

swagger ui authorization is still empty


Solution

  • I was not able to make this work through swagger configuration on the API as well as the config that is passed in the swagger ui constructor. Not sure why.

    But I was able to make it work by adding a hack on the TryOut button. In the onComplete handler in swagger ui constructor, I added a document listener event and captured the Tryout click event and added the authorization key in the Authorization textbox and bubbled the event up for its default behaviour. This worked for me.

    Hope this helps someone who gets stuck up as I did. :)