171

I am trying to convey that the authentication/security scheme requires setting a header as follows:

Authorization: Bearer <token>

This is what I have based on the swagger documentation:

securityDefinitions:
  APIKey:
    type: apiKey
    name: Authorization
    in: header
security:
  - APIKey: []

7 Answers 7

190

Maybe this can help:

swagger: '2.0'
info:
  version: 1.0.0
  title: Bearer auth example
  description: >
    An example for how to use Bearer Auth with OpenAPI / Swagger 2.0.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
    description: >-
      Enter the token with the `Bearer: ` prefix, e.g. "Bearer abcde12345".
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

You can copy&paste it to https://editor.swagger.io to check out the results.

There are also several examples in the Swagger Editor web with more complex security configurations which could help you.

Important: In this example, API consumers must include the "Bearer" prefix as part of the token value. For example, when using Swagger UI's "Authorize" dialog, you need to enter Bearer your_token instead of just your_token.

Swagger UI's Authorization dialog

9
  • 4
    I don't see how you tell the editor what user and password or Basic token to send so you can get a 200. Am I missing something?
    – Rob
    Feb 11, 2016 at 18:00
  • 1
    OK, nevermind. Apparently the "Authenticate" is something you can click on to get a login form.
    – Rob
    Feb 11, 2016 at 20:27
  • 2
    @Gobliins you want curl -X GET -H "Authorization: Bearer your_token", where your_token is your bearer token. E.g. curl -X GET -H "Accept: application/json" -H "Authorization: Bearer 00000000-0000-0000-0000-000000000000" "http://localhost/secure-endpoint"
    – Steve K
    Apr 8, 2016 at 16:25
  • 26
    Unfortunately this doesn't work well with Swagger UI - clicking "Authorize" and providing a bare token will generate "Try it out" curl examples with -H "Authorization: foo" instead of -H "Authorization: Bearer foo" like the OpenAPI 3 answer Jun 2, 2018 at 20:11
  • 5
    Workaround for me was to put Bearer xxxxxxxx as the key in the UI authorization box. This worked, though the drawback is telling users to manually enter Bearer and then the key. Alternatively, you can modify your function/method for returning the API key to included the Bearer prefix as part of the key.
    – csteel
    Nov 25, 2020 at 17:21
104

Bearer authentication in OpenAPI 3.x

OpenAPI 3.0 and later versions support Bearer/JWT authentication natively. It's defined like this:

openapi: 3.0.0
...

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT  # optional, for documentation purposes only

security:
  - bearerAuth: []

This is supported in Swagger UI 3.4.0+ and Swagger Editor 3.1.12+ (again, for OpenAPI 3.x specs only!).

UI will display the "Authorize" button, which you can click and enter the bearer token (just the token itself, without the "Bearer " prefix). After that, "try it out" requests will be sent with the Authorization: Bearer xxxxxx header.

Adding the Authorization header programmatically (Swagger UI 3.x+)

If you use Swagger UI and, for some reason, need to add the Authorization header programmatically instead of having the users click "Authorize" and enter the token, you can use the requestInterceptor. This solution is for Swagger UI 3.x+; UI 2.x used a different technique.

// index.html

const ui = SwaggerUIBundle({
  url: "https://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})
5
  • 2
    How do I implement this in flask-restplus generated swagger documentation ?
    – Chang Zhao
    Dec 6, 2018 at 2:03
  • I doubt if answer aligns with the question that was asked.
    – Vishrant
    May 26, 2019 at 18:17
  • by doing this im getting no routes matches error Feb 10, 2021 at 12:08
  • 1
    This one worked for me, it`s documented here: swagger.io/docs/specification/authentication/… Feb 28 at 20:19
  • Is there a way to add the token programmatically in swagger UI. requestInterceptor doesn't seem to be working.
    – RoRFan
    Jul 7 at 9:46
37

Posting 2023 answer in JSON using openapi 3.0.0:

{
  "openapi": "3.0.0",
  ...
  "servers": [
    {
      "url": "/"
    }
  ],
  ...
  "paths": {
    "/skills": {
      "put": {
        "security": [
           {
              "bearerAuth": []
           }
        ],
       ...
  },


  "components": {        
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}
4
  • 1
    Worked like a charm :-))
    – Naren
    Oct 30, 2020 at 18:15
  • 1
    While reading swagger docs I can't get where the token endpoint in this scheme is Apr 27, 2022 at 11:59
  • @Kakash1hatake You need to add it as a GET request with two parameters (username, password). The response will be the token. Aug 30, 2022 at 20:48
  • @vitaly-sazanovich No, you don't see the point. When schema is oauth2 - it has dedicated authorizationUrl parameter to hold the endpoint address where to get then token. And bearer schema lacks it. But I suppose that it is used with external identity provider, so token is generated there Aug 31, 2022 at 7:42
21

Why "Accepted Answer" works... but it wasn't enough for me

This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.

But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:

this.rootGet = function(callback) { ... }

This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.

My alternative

Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.

Note: which is being discussed in

So, it's handle authentication like a standard header. On path object append an header paremeter:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

This will generate a client with a new parameter on method signature:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

To use this method in the right way, just pass the "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

And works.

1
  • 1
    "token comes from elsewhere"... I'm interested in the elsewhere. What when you logged got directed to your login and redirected to your swagger api, how can you use the access token you received?
    – seawave_23
    May 10, 2019 at 9:29
1

By using requestInterceptor, it worked for me:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});
0

My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:

At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
  url: "{{.URL}}",
  dom_id: '#swagger-ui',
  validatorUrl: null,
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ,
  layout: "StandaloneLayout",
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization
  return req
  }
})

window.ui = ui

}

0

Solving this from laravel 7x ("openapi": "3.0.0"), edit your config\l5-swagger.php with the following codes

'securityDefinitions' => [
                'securitySchemes' => [
                    'bearerAuth' => [ 
                        'type' => 'http',
                        'scheme' => 'bearer',
                        'bearerFormat' => 'JWT', 
                    ], 
                ],

then you can add this as a security annotation for your endpoint:

*security={
     *{
     *"bearerAuth": {}},
     *},

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.