swaggo / gin-swagger

gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
MIT License
3.79k stars 271 forks source link

How can I use the Bearer Authentication for apis? #90

Open xxiaocheng opened 4 years ago

nfyxhan commented 4 years ago

Definition // @securityDefinitions.basic BasicAuth or

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

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

xxiaocheng commented 4 years ago

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?

Aiglobelam commented 3 years ago

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"
codechaitu commented 3 years ago

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>)

ansonhwa92 commented 3 years ago

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

ericlingit commented 2 years ago

To summarize the findings of previous posters:

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

avail-auth

JohnSalazar commented 1 year ago

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.
  2. 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

luizjhonata commented 2 months ago

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?

JohnSalazar commented 2 months ago

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.


halfstring commented 2 months ago

https://github.com/swaggo/swag/pull/1854 the swaggo will support it~ beartoken