Authentication Example
This example shows how to configure multiple authentication schemes — Bearer tokens, API keys, and OAuth2 — and apply them to different endpoints. Endpoints reference schemes by name in Security; the Bearer and API key schemes are registered on Config.Auth, and the OAuth2 flow is set on the built spec.
The Full Program
package main
import (
"fmt"
"net/http"
openswag "github.com/gopackx/open-swag-go"
"github.com/gopackx/open-swag-go/pkg/spec"
)
func main() {
// --- Scheme definitions (root-package helpers) ---
bearerScheme := openswag.BearerAuth("bearerAuth")
bearerScheme.Description = "JWT access token obtained from /auth/login"
apiKeyScheme := openswag.APIKeyAuth("apiKey", "X-API-Key")
apiKeyScheme.Description = "API key for service-to-service calls"
docs := openswag.New(openswag.Config{
Info: openswag.Info{
Title: "Multi-Auth API",
Version: "1.0.0",
Description: "An API demonstrating multiple authentication schemes.",
},
Servers: []openswag.Server{
{URL: "http://localhost:8080"},
},
Auth: openswag.AuthConfig{
Schemes: []openswag.AuthScheme{bearerScheme, apiKeyScheme},
},
})
docs.AddAll(
// Public — no auth required
openswag.Endpoint{
Method: "POST",
Path: "/auth/login",
Summary: "Login",
Description: "Authenticate with username and password. Returns a JWT.",
Tags: []string{"Auth"},
RequestBody: &openswag.RequestBody{
Description: "Login credentials",
ContentType: "application/json",
Required: true,
},
Responses: openswag.Responses{
200: {Description: "JWT token"},
401: {Description: "Invalid credentials"},
},
},
// Bearer auth — standard user endpoints
openswag.Endpoint{
Method: "GET",
Path: "/users/me",
Summary: "Get current user",
Tags: []string{"Users"},
Security: []string{"bearerAuth"},
Responses: openswag.Responses{
200: {Description: "User profile"},
401: {Description: "Unauthorized"},
},
},
// API key auth — service-to-service
openswag.Endpoint{
Method: "GET",
Path: "/internal/health",
Summary: "Internal health check",
Description: "Used by monitoring services. Requires an API key.",
Tags: []string{"Internal"},
Security: []string{"apiKey"},
Responses: openswag.Responses{
200: {Description: "Service healthy"},
403: {Description: "Invalid API key"},
},
},
// OAuth2 — third-party integrations
openswag.Endpoint{
Method: "GET",
Path: "/users",
Summary: "List users",
Description: "Returns all users. Requires the oauth2 scheme.",
Tags: []string{"Users"},
Security: []string{"oauth2"},
Responses: openswag.Responses{
200: {Description: "User list"},
401: {Description: "Unauthorized"},
403: {Description: "Insufficient scope"},
},
},
// Multiple schemes — admin endpoints require both bearer AND API key
openswag.Endpoint{
Method: "DELETE",
Path: "/users/{id}",
Summary: "Delete a user",
Description: "Permanently removes a user. Requires both a JWT and an API key.",
Tags: []string{"Admin"},
Security: []string{"bearerAuth", "apiKey"},
Parameters: []openswag.Parameter{
{Name: "id", In: "path", Required: true, Description: "User ID", Schema: spec.NewSchema("string")},
},
Responses: openswag.Responses{
204: {Description: "User deleted"},
401: {Description: "Unauthorized"},
403: {Description: "Forbidden — missing API key"},
404: {Description: "User not found"},
},
},
)
// --- OAuth2 needs flows, which AuthScheme cannot express: set it on the built spec ---
openapi := docs.BuildSpec()
openapi.AddSecurityScheme("oauth2", &spec.SecurityScheme{
Type: "oauth2",
Description: "OAuth2 authorization code flow",
Flows: &spec.OAuthFlows{
AuthorizationCode: &spec.OAuthFlow{
AuthorizationURL: "https://auth.example.com/authorize",
TokenURL: "https://auth.example.com/token",
Scopes: map[string]string{"read:users": "Read user profiles"},
},
},
})
mux := http.NewServeMux()
docs.Mount(mux, "/docs")
fmt.Println("Multi-Auth API docs at http://localhost:8080/docs")
http.ListenAndServe(":8080", mux)
}Key Concepts
Referencing schemes by name
Each endpoint lists the scheme names it requires in Security (a []string). The matching definitions are registered once: bearerAuth and apiKey through Config.Auth.Schemes with the openswag.BearerAuth / openswag.APIKeyAuth helpers, and oauth2 (which needs flows) with AddSecurityScheme on the built spec. Without that call, the name oauth2 (openswag.SecurityOAuth2) would fall back to a built-in placeholder flow.
| Name | Type | Use case |
|---|---|---|
bearerAuth | HTTP Bearer (JWT) | User-facing endpoints |
apiKey | API Key (header) | Service-to-service calls |
oauth2 | OAuth2 | Third-party integrations |
Per-endpoint security
Endpoints without a Security field are public (like /auth/login).
Combining multiple schemes
The admin endpoint passes both "bearerAuth" and "apiKey" in Security, so the client must satisfy both — a logical AND.
Run It
go run main.goOpen http://localhost:8080/docs. The docs UI groups endpoints by tag and shows a lock icon on authenticated endpoints.