Repository navigation
API Keys
github-actions[bot] edited this page Oct 31, 2026
·
5 revisions
apikey.Authenticator turns a presented API key into an auth.Identity: static keys from configuration (name, secret, roles, permissions) and keys your application issues, looked up by a Resolver. Works with any provider and in front of the session.Guard.
Tested (apikey/example_test.go):
authenticator, err := apikey.New(&apikey.Options{
Keys: []apikey.Key{{
Name: "ci",
Secret: "ci-secret-0123456789",
Roles: []string{auth.RoleAdmin},
Permissions: []auth.Permission{{Resource: "builds", Access: auth.AccessWrite}},
}},
})Mount it before the Guard: authenticator.Middleware()(guard.RequireAPI()(handler)), on gin ginadapter.Middleware(authenticator.Middleware()) before ginadapter.Middleware(guard.RequireAPI()). The Guard passes a request that already carries an identity; requests without a key fall through to the session.
- Keys come from
X-API-Key(HeaderName; notAuthorization) orAuthorization: Bearer <key>(scheme in any case). - No key: passes through untouched. A wrong key: 401
invalid_api_key, never a fall-through, also when a valid session cookie is present. - Static key identity:
Providerapikey,SubjectandUsernamethe key name, the key'sRolesandPermissions,Activetrue. - Secrets: at least 16 bytes, no surrounding whitespace, names and secrets unique; compared as SHA-256 in constant time.
-
Resolver func(ctx, key) (*auth.Identity, error)for keys you issue: return an error matchingauth.ErrUnauthenticatedfor unknown or revoked keys (any other error is 500, its chain dropped; onlycontext.Canceledandcontext.DeadlineExceededstay detectable); setActive: trueyourself; put the key's access level intoPermissions(e.g. a storedread_onlylevel becomes*:read); never repeat the key in an error text: it is reported inOutcome.Errand recorded on the wide event.
- A route behind
apikeyrefuses every bearer token that is not a key (an SPA's own token, a forward-auth JWT): do not combine it withjwt.Verifieron the same route. - A
Resolveridentity withoutActiveis refused by every check exceptIsAuthenticated(403). - Static keys get only what you configure:
Roles: []string{auth.RoleAdmin}for admin checks, permissions forHasPermission.
Source: apikey/apikey.go.
Mirror of docs/wiki at v1.3.0 (486bfa3). Edit the repository, not this wiki.