170

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: []
Helen
  • 87,344
  • 17
  • 243
  • 314
Elmer Thomas
  • 2,068
  • 2
  • 13
  • 11

7 Answers7

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

Helen
  • 87,344
  • 17
  • 243
  • 314
David Lopez
  • 2,127
  • 1
  • 10
  • 7
  • 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 '16 at 18:00
  • 1
    OK, nevermind. Apparently the "Authenticate" is something you can click on to get a login form. – Rob Feb 11 '16 at 20:27
  • So how do i set a value to the token? i tried curl -x get --header "Authorization: apiKey=123" but nothing happened – Gobliins Apr 04 '16 at 10:35
  • 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 08 '16 at 16:25
  • Ah yes thx, but what i dont get is when the connection between the header and the swagger security-definition is happening. Where and when is the validation? I could send this header token just without the security definition at all, where is the use of it? – Gobliins Apr 11 '16 at 08:42
  • @david-lopez have you tried to generate a SDK by swagger-codegen with these Security Definitions? Because while Swagger 2.0 Specification accepts these YAML and validates it. Swagger-codegen v2.1.6 generates an SDK without anyway possible to `token` into the function and appends to Authorization header. Mostly because specification and related not support JWT (Authorization Header) natively. – Paulo Oliveira Jul 29 '16 at 20:28
  • 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 – Abe Voelker Jun 02 '18 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 '20 at 17:21
  • I have used the same code but getting below error **Operation accepts API keys transported in a header over network** Also, any idea how to represent empty security? (means no auth token for some operations). Used below code **security: []** Got below error **The security section of the operation 'options' contains an empty array** – Sridhar Adurthi Jun 03 '23 at 15:42
103

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
  }
})
Helen
  • 87,344
  • 17
  • 243
  • 314
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"
      }
    }
  }
}
TheYogi
  • 976
  • 8
  • 15
  • 1
    Worked like a charm :-)) – Naren Oct 30 '20 at 18:15
  • 1
    While reading swagger docs I can't get where the token endpoint in this scheme is – Kakash1hatake Apr 27 '22 at 11:59
  • @Kakash1hatake You need to add it as a GET request with two parameters (username, password). The response will be the token. – Vitaly Sazanovich Aug 30 '22 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 – Kakash1hatake Aug 31 '22 at 07: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.

Jarosław Kończak
  • 3,387
  • 2
  • 19
  • 36
Paulo Oliveira
  • 2,411
  • 1
  • 31
  • 47
  • 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 '19 at 09:29
1

By using requestInterceptor, it worked for me:

const ui = SwaggerUIBundle({
  ...
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization;
    return req;
  },
  ...
});
Pang
  • 9,564
  • 146
  • 81
  • 122
nhaht
  • 1,005
  • 12
  • 21
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

}

xXPhenom22Xx
  • 1,265
  • 5
  • 29
  • 63
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": {}},
     *},
Evidence Ekanem
  • 101
  • 1
  • 8