swaggo / http-swagger

Default net/http wrapper to automatically generate RESTful API documentation with Swagger 2.0.
MIT License
420 stars 72 forks source link

how to set bearer token #119

Open JubaerHossain opened 1 month ago

JubaerHossain commented 1 month ago

// @Summary Get all departments // @Description Get details of all departments // @Tags departments // @Accept json // @Produce json // @Security Bearer // @Success 200 {object} entity.DepartmentResponsePagination // @Router /departments [get]

. use this but not working

dominique-boerner commented 1 month ago

I could set the Bearer Token following the description of https://github.com/swaggo/swag/issues/1030#issuecomment-1398453614.

My main.go:

// @title       Foxdeck API
// @version     1.0
// @description This API handles requests from the Foxdeck App.

// @query.collection.format multi

// @securityDefinitions.apikey Bearer <-- add Security Definition
// @in header                                      <-- where security is stored
// @name Authorization                     <-- name of your header
// @description Type "Bearer" followed by a space and JWT token. <-- description (optional)

// @externalDocs.description  Developer Guide
// @externalDocs.url          https://docs.foxdeck.de
func main() {
   ...
}

In your controller you should add the @Security Comment, e. g.:

// CreateResource
// @Summary     Creates a new resource for the logged-in user
// @Security    Bearer                       <---- Add Security annotation
// @Tags        auth
// @Produce     json
// @Param       request     body      resources.CreateResourceRequest   true  "Query Parameter"
// @Success     200         {object}  resources.CreateResourceResponse
// @Router      /resource [post]
func CreateResource(responseWriter http.ResponseWriter, request *http.Request) {

This works for me and I can now enter the bearer token in Swagger and it is evaluated correctly.

JubaerHossain commented 1 week ago

@dominique-boerner It didn't work the same way I tried it, but this way worked for me

// @Security ApiKeyAuth