How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

223,796

Solution 1

Maybe this can help:

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: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
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 out here: http://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.

Solution 2

Bearer authentication in OpenAPI 3.0.0

OpenAPI 3.0 now supports 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.0 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 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: "http://your.server.com/swagger.json",
  ...

  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer xxxxxxx"
    return req
  }
})

Solution 3

Posting 2022 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"
      }
    }
  }
}

Solution 4

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.

Solution 5

By using requestInterceptor, it worked for me:

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

Related videos on Youtube

Elmer Thomas
Author by

Elmer Thomas

Hacker in Residence @SendGrid, Father, Husband, Friend. Learning, so I can teach. Productivity nut, entrepreneur, developer, engineer and lover of APIs &amp; IPAs.

Updated on January 05, 2022

Comments

  • Elmer Thomas
    Elmer Thomas over 2 years

    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: []
    
  • Rob
    Rob about 8 years
    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
    Rob about 8 years
    OK, nevermind. Apparently the "Authenticate" is something you can click on to get a login form.
  • Gobliins
    Gobliins about 8 years
    So how do i set a value to the token? i tried curl -x get --header "Authorization: apiKey=123" but nothing happened
  • Steve K
    Steve K about 8 years
    @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"
  • Gobliins
    Gobliins about 8 years
    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?
  • Paulo Oliveira
    Paulo Oliveira almost 8 years
    @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.
  • Abe Voelker
    Abe Voelker almost 6 years
    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
  • Chang Zhao
    Chang Zhao over 5 years
    How do I implement this in flask-restplus generated swagger documentation ?
  • seawave_23
    seawave_23 almost 5 years
    "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?
  • Vishrant
    Vishrant almost 5 years
    I doubt if answer aligns with the question that was asked.
  • Naren
    Naren over 3 years
    Worked like a charm :-))
  • csteel
    csteel over 3 years
    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.
  • Humayun Naseer
    Humayun Naseer about 3 years
    by doing this im getting no routes matches error
  • Kakash1hatake
    Kakash1hatake about 2 years
    While reading swagger docs I can't get where the token endpoint in this scheme is