Support Multiple API Keys (#3450)

* Support Multiple API Keys

* Use maps

* Fix readme template

* Update readme

* Address readme review
This commit is contained in:
Nicholas Muesch
2019-09-14 09:28:31 -04:00
committed by William Cheng
parent 87dce1bfe1
commit 334d0dcb48
3 changed files with 23 additions and 26 deletions

View File

@@ -31,7 +31,7 @@ go get github.com/antihax/optional
Put the package under your project folder and add the following in import:
```golang
import "./{{packageName}}"
import sw "./{{packageName}}"
```
## Documentation for API Endpoints
@@ -54,19 +54,14 @@ Class | Method | HTTP request | Description
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}
## {{{name}}}
### {{{name}}}
{{#isApiKey}}- **Type**: API key
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{{keyParamName}}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
Example
```golang
auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{
Key: "APIKEY",
Prefix: "Bearer", // Omit if not necessary.
})
r, err := client.Service.Operation(auth, args)
```
Note, each API key must be added to a map of `map[string]APIKey` where the key is: {{keyParamName}} and passed in as the auth context for each request.
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication

View File

@@ -276,19 +276,21 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx _context.Context{{#hasParams
{{^isKeyInCookie}}
if ctx != nil {
// API Key Authentication
if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {
var key string
if auth.Prefix != "" {
key = auth.Prefix + " " + auth.Key
} else {
key = auth.Key
if auth, ok := ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
if auth, ok := auth["{{keyParamName}}"]; ok {
var key string
if auth.Prefix != "" {
key = auth.Prefix + " " + auth.Key
} else {
key = auth.Key
}
{{#isKeyInHeader}}
localVarHeaderParams["{{keyParamName}}"] = key
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParams.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
{{#isKeyInHeader}}
localVarHeaderParams["{{keyParamName}}"] = key
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParams.Add("{{keyParamName}}", key)
{{/isKeyInQuery}}
}
}
{{/isKeyInCookie}}

View File

@@ -25,8 +25,8 @@ var (
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth