api-key

command
v14.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause Imports: 2 Imported by: 0

Documentation

Overview

API keys: authenticating a service, a cron job or a webhook sender.

apikey.New(apikey.Options{...}) returns a plain iris.Handler, so it guards exactly the router or the route it is mounted on. The key arrives on "Authorization: Bearer <key>" by default, or on a header of your own when the caller cannot set that one. It is compared against every configured key in constant time, then handed to Lookup when nothing matched, and the principal that won is stored on the Context for apikey.Get and for ctx.User().

The default is to deny: a middleware with no Keys and no Lookup rejects every request and logs a warning, rather than quietly letting everyone through when a secret is missing from the environment.

The three groups below are the three shapes worth knowing:

/reports   Authorization: Bearer, secrets in the configuration
/webhooks  X-API-Key with apikey.NoScheme, a bare value on a custom header
/partners  Options.Hash with apikey.SHA256: the configuration holds only
           digests, and Lookup resolves the keys that live in a database

Secrets are inline here so the curl lines run as they are. In a real service they come from the environment, and with Hash set what the deployment holds is the digest, never a usable credential.

The 401 body is the rest/errors envelope every other rejection in the framework uses ("id" is the tracking id written to the log too):

{"id":"98db6518-4156-49a2-9e26-8fc4b0afdf18",
 "http_error_code":{"canonical_name":"UNAUTHENTICATED","status":401},
 "message":"apikey: the presented key matched nothing: apikey: credentials are invalid",
 "data":[{"message":"apikey: credentials are invalid"}]}

A request with no key at all reports apikey.ErrMissing instead, so a custom ErrorHandler can tell the two apart with errors.Is and log them differently.

Learn: guard a router with API keys from the configuration, a custom header or a database Lookup, storing only digests on the server. Before: ../basicauth

Run:

go run main.go

Try:

curl -i -H "Authorization: Bearer reporting-key" http://localhost:8080/reports/daily   # 200
curl -i -X POST -H "X-API-Key: stripe-key" http://localhost:8080/webhooks/stripe       # 200
curl -i -H "Authorization: Bearer partner-key" http://localhost:8080/partners/quota    # 200, matched a digest
curl -i -H "Authorization: Bearer rotated-key" http://localhost:8080/partners/quota    # 200, resolved by Lookup
curl -i -H "Authorization: Bearer wrong" http://localhost:8080/reports/daily           # 401 UNAUTHENTICATED
curl -i http://localhost:8080/reports/daily                                            # 401 UNAUTHENTICATED, apikey.ErrMissing

Next: ../jwt-middleware

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL