github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/examples/authentication/README.md (about)

     1  # Authentication sample
     2  
     3  Define the following security scheme (in `swagger.yml` specification document):
     4  
     5  ```yaml
     6  securityDefinitions:
     7    key:
     8      type: apiKey
     9      in: header
    10      name: x-token
    11  ```
    12  
    13  Specify the following security requirements for all endpoints: so by default,
    14  all endpoints use the API key auth.
    15  
    16  ```yaml
    17  security:
    18    - key: []
    19  ```
    20  
    21  Add security princial model definition:
    22  
    23  ```yaml
    24  definitions:
    25  
    26  ...
    27  
    28    principal:
    29      type: string
    30  ```
    31  
    32  Generate the code with a security principal:
    33  
    34  ```shell
    35  swagger generate server -A AuthSample -P models.Principal -f ./swagger.yml
    36  ```
    37  
    38  Edit the ./restapi/configure_auth_sample.go file
    39  
    40  ```go
    41  func configureAPI(api *operations.AuthSampleAPI) http.Handler {
    42  	// configure the api here
    43  	api.ServeError = errors.ServeError
    44  
    45  	// Set your custom logger if needed. Default one is log.Printf
    46  	// Expected interface func(string, ...interface{})
    47  	//
    48  	// Example:
    49  	api.Logger = log.Printf
    50  
    51  	api.JSONConsumer = runtime.JSONConsumer()
    52  
    53  	api.JSONProducer = runtime.JSONProducer()
    54  
    55  	// Applies when the "x-token" header is set
    56  	api.KeyAuth = func(token string) (*models.Principal, error) {
    57  		if token == "abcdefuvwxyz" {
    58  			prin := models.Principal(token)
    59  			return &prin, nil
    60  		}
    61  		api.Logger("Access attempt with incorrect api key auth: %s", token)
    62  		return nil, errors.New(401, "incorrect api key auth")
    63  	}
    64  
    65  	api.CustomersCreateHandler = customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder {
    66  		return middleware.NotImplemented("operation customers.Create has not yet been implemented")
    67  	})
    68  	api.CustomersGetIDHandler = customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder {
    69  		return middleware.NotImplemented("operation customers.GetID has not yet been implemented")
    70  	})
    71  
    72  	api.ServerShutdown = func() {}
    73  
    74  	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
    75  }
    76  ```
    77  
    78  Run the server:
    79  
    80  ```shell
    81  go run ./cmd/auth-sample-server/main.go --port 35307
    82  ```
    83  
    84  Exercise auth:
    85  
    86  ```shellsession
    87  ± ivan@avalon:~  
    88   » curl -i -H 'Content-Type: application/keyauth.api.v1+json' -H 'X-Token: abcdefuvwxyz' http://127.0.0.1:35307/api/customers
    89  ```
    90  ```http
    91  HTTP/1.1 501 Not Implemented
    92  Content-Type: application/keyauth.api.v1+json
    93  Date: Fri, 25 Nov 2016 19:14:14 GMT
    94  Content-Length: 57
    95  
    96  "operation customers.GetID has not yet been implemented"
    97  ```
    98  ```shellsession
    99  ± ivan@avalon:~  
   100   » curl -i -H 'Content-Type: application/keyauth.api.v1+json' -H 'X-Token: abcdefu' http://127.0.0.1:35307/api/customers
   101  ```
   102  ```http
   103  HTTP/1.1 401 Unauthorized
   104  Content-Type: application/keyauth.api.v1+json
   105  Date: Fri, 25 Nov 2016 19:16:49 GMT
   106  Content-Length: 47
   107  
   108  {"code":401,"message":"incorrect api key auth"}
   109  ```