Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
xxiaocheng opened this issue Nov 22, 2019 · 10 comments
Open

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

xxiaocheng opened this issue Nov 22, 2019 · 10 comments

Comments

@xxiaocheng
Copy link

No description provided.

@nfyxhan
Copy link

nfyxhan commented Nov 22, 2019

Definition
// @securityDefinitions.basic BasicAuth
or

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

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

@xxiaocheng
Copy link
Author

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
Copy link

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
Copy link

codechaitu commented Jan 11, 2021

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
Copy link

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
Copy link

ericlingit commented Apr 19, 2022

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

@JohnSalazar
Copy link

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

@luizjhonata
Copy link

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
Copy link

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants