swaggo/gin-swagger

How can I use the Bearer Authentication for apis?

Opened this issue Β· 11 comments

How can I use the Bearer Authentication for apis?

Definition
// @securityDefinitions.basic BasicAuth
or

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name X-Token

use
// @Security BasicAuth
or
// @Security ApiKeyAuth

Definition
// @securityDefinitions.basic BasicAuth
or

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name X-Token

use
// @Security BasicAuth
or
// @Security ApiKeyAuth

I use comment
// @securityDefinitions.apikey ApiKeyAuth // @in header // @name Authorization
for the main function ,and use // @Security ApiKeyAuth for the api function.
But I have to fill in this value for the apiKey like bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzQ0ODc1NzQsInVzZXJuYW1lIjoieGlhb2NoZW5nIn0.3HtjJoc5u3-2h_b3mLRpmgvKai8MoLQIxWHQsJ_M92s manually.
It can get the token when fill the username and password automatically?

Hi, I am very new to this, and for sure I use the wrong syntax!?

I'm trying to get the Header value prefixed with Bearer

@xxiaocheng At way back =), did you find a solution?

In main.go I did like this:

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization

And then at the routes I added // @Security BearerAuth

But in the gui I have to add the string Bearer XYZ...... for the header to have the correct value...
Swagger_UI

The generated files for ex docs/swagger.json seem to generate a ApiKeyAuth instead even if I specified BearerAuth

"securityDefinitions": {
        "BearerAuth": {
            "type": "apiKey",
            "name": "Authorization",
            "in": "header"
        }
}

At Swagger see BearerAuth it seems that you should specify Bearerauth like this:

"BearerAuth":
      "type": "http",
      "scheme": "bearer"

If you want to use with swagger v2.0, then after trying few solutions, it worked for me.
// @Param Authorization header string true "Insert your access token" default(Bearer <Add access token here>)

Hi, I am very new to this, and for sure I use the wrong syntax!?

I'm trying to get the Header value prefixed with Bearer

@xxiaocheng At way back =), did you find a solution?

In main.go I did like this:

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization

And then at the routes I added // @Security BearerAuth

But in the gui I have to add the string Bearer XYZ...... for the header to have the correct value...
Swagger_UI

The generated files for ex docs/swagger.json seem to generate a ApiKeyAuth instead even if I specified BearerAuth

"securityDefinitions": {
        "BearerAuth": {
            "type": "apiKey",
            "name": "Authorization",
            "in": "header"
        }
}

At Swagger see BearerAuth it seems that you should specify Bearerauth like this:

"BearerAuth":
      "type": "http",
      "scheme": "bearer"

Server.go
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization

At controller:
// @Security BearerAuth

To summarize the findings of previous posters:

  • OpenAPI 2.0 does not support bearer authorization syntax (it's supported in OpenAPI 3.0). Since this library generates 2.0 spec, there is no direct way to specify bearer authorization.
  • To work around that, add the following comments:
    1. To your main.go:
      // @securityDefinitions.apikey ApiKeyAuth
      // @in header
      // @name Authorization
    2. To your handler/controller:
      // @Security ApiKeyAuth
      func myHandler(c *gin.Context) {...}

When using Swagger UI in a browser, you must specify bearer in the value field of the authorization pop up:

avail-auth

Hi, for OpenAPI 2.0 just enter the following comments and generate the docs by swag init.

  1. To your main.go:
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.
  1. To your handler/controllers that need authentication
// Profile godoc
// @Summary      Profile user
// @Description  get user info
// @Tags         users
// @Accept       json
// @Produce      json
// @Success      200  {object}  dtos.User
// @Failure      400  {object}  httputil.ResponseError
// @Failure      401  {object}  httputil.ResponseError
// @Failure      403  {object}  httputil.ResponseError
// @Router       /profile [get]
// @Security Bearer  <-----------------------------------------add this in all controllers that need authentication
func (auth *AuthController) Profile(c *gin.Context) {...}

On Swagger UI in a browser, you must specify the bearer in the value field of the authorization pop up:

Bearer_Authorization

How can I have "Bearer" as the default value in authorization, so I only need to add the JWT token, like when I use Postman and select "Auth Type: Bearer Token" and only need to add the token in the field?

To pre-fill the token field with the "Bearer" prefix in Swagger, you can customize the Swagger template generated by Swaggo. Unfortunately, Swaggo does not provide a direct configuration to automatically add the "Bearer" prefix to the authentication field, but there is an alternative solution:

  1. Add a Hook to Configure the Bearer Token in Swagger UI: Use preauthorizeApiKey to automatically configure the token with the "Bearer" prefix.

  2. Edit the Swagger UI Template: If you are serving the Swagger interface with gin-swagger, you can inject custom JavaScript to add the "Bearer" prefix.

Here is an example of how to do this:

Step 1: Inject JavaScript into Swagger

Create a JS file (e.g., swagger-setup.js) to inject the prefix:

document.addEventListener('DOMContentLoaded', function() {
  const ui = window.ui;
  
  ui.preauthorizeApiKey('Bearer', 'Bearer ');
  
  // Configure the token field to automatically fill with "Bearer " at the start
  const authTokenInput = document.querySelector('input[placeholder="api_key"]');
  if (authTokenInput) {
    authTokenInput.addEventListener('input', function() {
      if (!authTokenInput.value.startsWith('Bearer ')) {
        authTokenInput.value = 'Bearer ' + authTokenInput.value;
      }
    });
  }
});

Step 2: Include the JS in Swagger Initialization

In your code where you set up Swagger with gin-swagger, add a reference to the script:

import (
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
)

func main() {
    r := gin.Default()

    // Serve Swagger UI with the custom script
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.CustomJS("/swagger-setup.js")))

    r.Run()
}

Step 3: Serve the JavaScript File

Make sure the swagger-setup.js file is available on the web server. You can serve it directly with Gin, for example:

r.Static("/swagger-setup.js", "./swagger-setup.js")

This way, when you open the Swagger UI, the token field will be automatically pre-filled with "Bearer ", and you will only need to add the token manually.


swaggo/swag#1854 the swaggo will support it~ beartoken

looks like it is merged but this is not working when I use
// @securitydefinitions.bearerauth BearerAuth
the json generated just won't include it