thilinistg
thilinistg

Reputation: 417

Bearer token based authentication in swagger 3.x

I'm currently using swagger-ui 2.x and following is the authentication I've been using with swagger-ui 2.x.

var key = $(this).val(); swaggerUi.api.clientAuthorizations.add("default", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer "+ key, "header"));

Currently, I'm upgrading the swagger-ui into latest 3.x version and I need to know how to achieve above with swagger 3.x. Can I have on bearer token based authentication?

Upvotes: 0

Views: 13826

Answers (2)

Helen
Helen

Reputation: 97540

The requestInterceptor can be used used if you want to authenticate "try it out" requests automatically. If you instead want to provide UI where your users can enter their Bearer token, you can add the corresponding security definition to your API definition:

securityDefinitions:
  bearerAuth:
    type: apiKey
    in: header
    name: Authorization
    description: Enter your bearer token in the format **Bearer <token>**

security:
  - bearerAuth: []

In this case, Swagger UI will show the "Authorize" button. The users can click this button to enter their bearer token:

Bearer auth in Swagger UI

That's if you are using OpenAPI 2.0 (fka Swagger 2.0).

OpenAPI 3.0 supports Bearer authentication natively, so that the bearer token can be entered without the "Bearer" prefix.

Upvotes: 1

Praminda
Praminda

Reputation: 575

At the moment SwaggerUI 3.x doesn't seem to have an exact way of doing this. However you can add a request interceptor when initializing SwaggerUIBundle. There you can inject the authorization header to achieve you requirement.

Ex:

SwaggerUIBundle({
    spec: spec ,
    dom_id: '#someId',
    presets: [
        SwaggerUIBundle.presets.apis
    ],
    requestInterceptor: function(request) {
        request.headers.Authorization = "Bearer " + key;
        return request;
    }
});

Upvotes: 3

Related Questions