# Authentication

Source: https://bogie-go.com/docs/authentication.html

`bogie g authentication` takes a shape, because the callers of an API service come in different kinds, and all three turned out to be a middleware on a route group.

```
bogie g authentication secret      # a trusted service calls this one
bogie g authentication token       # a user presents a bearer token
bogie g authentication api_key     # a machine client presents a key
```

## Three shapes, one mechanism

Each shape answers a different kind of caller:

- **secret**: a trusted service calls this one directly, over the private network. One shared secret, checked on every request.
- **token**: a user, already signed in somewhere else, presents a bearer JWT so this service knows who is asking without asking again.
- **api_key**: a machine client, a script or another system, presents a key made for it ahead of time and can be revoked without touching anyone's session.

Whichever shape, the mechanism is the same: a function that checks the request and either calls `c.Next()` or aborts with 401, mounted on a `*gin.RouterGroup` instead of the whole router, so only the routes in that group are guarded.

## What every shape writes

Three things, every time: the middleware and its test under `app/middlewares`, a group helper on the root `Server` in `app/controllers/authentication_<shape>.go`, and the setting itself, a group of the credentials file with its own struct in `config/`, registered in `config/config.go`. Here is `secret`:

```
      create  app/middlewares/require_secret.go
      create  app/middlewares/require_secret_test.go
      create  app/controllers/authentication_secret.go
      create  config/control.go
      insert  config/config.go: Control ControlConfig `mapstructure:"control"`
      insert  config/config.go: c.Control.defaults(env)
      insert  config/config.go: c.Control.validate(c.Env),
      insert  config/credentials.yml.enc: control.secret
        next  mount the routes it guards in app/controllers/routes.go: s.Posts.SetupRoutes(s.WithSecret(&r.RouterGroup))
```

`config/control.go` holds `ControlConfig`, the `control:` group; the three lines in `config/config.go` are its field, its defaults and its check at boot. Each key is overridden by the variable named after its path: `control.secret` is `CONTROL_SECRET`, and the token shape's `token.secret` is `TOKEN_SECRET`. (Before v0.3.0 these were flat keys, `control_secret` and `BLOG_CONTROL_SECRET`.)

The generator also writes a random development value into `config/credentials.yml.enc`, so the app keeps booting in development exactly as before. Staging and production get theirs by hand, with `make credentials ENV=staging` or `ENV=production`, each its own file and key. `requireSecret` is the check behind the third marker: in production it refuses to boot if the secret is shorter than 32 characters; everywhere else, the generated development value or the test's own is enough, so nothing is enforced until it has to be.

## Mounting the guard

The generator stops short of one edit, on purpose: mounting a controller on the guarded group instead of the plain router, in `app/controllers/routes.go`. That line is the exposure boundary, and it belongs where it can be read, not written by a tool that cannot see what the group should protect:

```
func (s *Server) SetupRoutes() {
	r := s.Router

	r.Use(middlewares.RequestID(), middlewares.Recover(s.Log), middlewares.Logger(s.Log))

	// Unauthenticated, no side effects: what a load balancer polls.
	r.GET("/healthz", func(c *gin.Context) { c.String(http.StatusOK, "ok") })

	// Guarded: every route Posts mounts needs the shared secret.
	s.Posts.SetupRoutes(s.WithSecret(&r.RouterGroup))

	// bogie:routes
}
```

A second guarded group reads the same way with `s.WithUser(&r.RouterGroup)` or `s.WithAPIKey(&r.RouterGroup)`; a controller that needs no guard at all stays on `&r.RouterGroup` directly, as `/healthz` does above.

## secret

A shared secret in the `X-<App>-Secret` header (the constant `middlewares.SecretHeader`), compared with `crypto/subtle.ConstantTimeCompare` so a wrong guess cannot be timed into a right one. A Basic auth fallback lets a browser open a guarded page too, since a browser cannot send a custom header; any username works and the password is the secret. For a caller it is one header on the request:

```
curl -H "X-Blog-Secret: $BLOG_SECRET" https://blog.example.com/posts
```

Try it: the app is the one from getting started with `Posts` mounted on the guarded group. The `X-Request-Id`, `Date` and `Content-Length` headers are left out of the responses on this page, and the request id differs on every call. A request without the header is refused:

**HTTP/1.1 401 Unauthorized**

```
$ curl -i localhost:8080/posts
HTTP/1.1 401 Unauthorized
Www-Authenticate: Basic realm="blog", charset="UTF-8"
```

The body is empty. A wrong value (`-H "X-Blog-Secret: wrong"`) and the Basic fallback with a wrong password (`-u x:wrong`) answer identically. The `Www-Authenticate: Basic realm="blog", charset="UTF-8"` header is what makes a browser prompt for a password. `/healthz` is outside the guard and answers `200 OK` with the body `ok` and no such header. With the right secret, `curl -i localhost:8080/posts -H "X-Blog-Secret: $BLOG_SECRET"` is a `200 OK` with the posts as JSON.

## token

A bearer token, JWT, HS256, signed with one shared secret: `token.secret` in the credentials file, `TOKEN_SECRET` in the environment. Whatever signs users in mints the token with any JWT library and the same secret, and this service only ever verifies. It requires `iss` (the app's name), a non-empty `sub` and an `exp`; tokens it mints itself also carry `iat` and `jti`:

```
{ "iss": "blog", "sub": "42", "iat": 1793000000, "exp": 1793000900, "jti": "…" }
```

Since v0.7.0 the payload may also carry an optional `role` claim. `Mint(subject, ttl)` still signs a token with no role; `MintFor(subject, role, ttl)` sets that claim, and `middlewares.Role(c)` reads it. See [Authorization](https://bogie-go.com/docs/authorization.html).

`bogie g authentication token` prints:

```
      create  app/services/token/token.go
      create  app/services/token/token_suite_test.go
      create  app/services/token/token_test.go
      create  app/middlewares/require_user.go
      create  app/middlewares/require_user_test.go
      create  app/controllers/authentication_token.go
      create  test/testapp/authentication_token.go
      create  config/token.go
      insert  config/config.go: Token TokenConfig `mapstructure:"token"`
      insert  config/config.go: c.Token.defaults(env)
      insert  config/config.go: c.Token.validate(c.Env),
      insert  config/credentials.yml.enc: token.secret
         run  go mod tidy
        next  mount the routes it guards in app/controllers/routes.go: s.Posts.SetupRoutes(s.WithUser(&r.RouterGroup))
```

Try it: with no token, the guard answers 401 and says what is missing:

```
$ curl -i localhost:8080/posts
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Www-Authenticate: Bearer realm="blog"

{"status":"error","error":"a bearer token is required"}
```

A wrong scheme word, as in `Authorization: Token ...`, is treated as no token and gets the same answer. A token the guard cannot accept is **HTTP/1.1 401 Unauthorized** with a different header and body; garbage (`-H "Authorization: Bearer not-a-token"`), a token signed with another secret and a token with another issuer all give the identical **token: invalid**:

```
$ curl -i localhost:8080/posts -H "Authorization: Bearer not-a-token"
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Www-Authenticate: Bearer realm="blog", error="invalid_token"

{"status":"error","error":"token: invalid"}
```

An expired token gets the same status and header with the body **token: expired**:

```
{"status":"error","error":"token: expired"}
```

A good token is a `200 OK`.

In a handler behind `WithUser`, `middlewares.Subject(c)` is the token's subject, usually a user id, and `middlewares.Role(c)` is the role string the token carried, or empty when it carried none. Nothing is loaded for you, because who the subject is is for the caller and the handler to agree on. A service that signs users in itself, rather than trusting another service's token, mints its own with `s.Tokens().Mint(subject, ttl)`, or `MintFor(subject, role, ttl)` when the token should carry a role.

`Verify` refuses a token that is expired, signed with another secret, issued for another issuer, or signed with any algorithm but HS256, so a token claiming `"none"` or an asymmetric algorithm never reaches the key at all.

## api_key

A machine client presents a key rather than a session. The generator adds an `api_keys` table (`name`, a public `prefix`, and a bcrypt `digest`, never the key itself) and a subcommand:

```
bogie api_keys:create NAME
```

which prints the key once, as `<prefix>.<secret>`; there is no way to see it again, only to verify it or make another. The client sends it as a bearer token, the same header shape as `token`, and a handler behind `WithAPIKey` reads `middlewares.APIKeyName(c)` to see which key the request presented. Because this shape adds a migration, run `bogie db:migrate` (or restart the app, since it migrates at boot) before `api_keys:create` works.

`bogie g authentication api_key` prints:

```
      create  db/migrate/20261105015917_create_api_keys.sql
      create  db/queries/api_keys.sql
      create  app/models/api_key.go
      create  app/models/api_key_test.go
      create  db/adapter/api_keys.go
      create  db/adapter/api_keys_test.go
      create  test/factories/api_keys.go
      create  app/services/api_keys/api_keys.go
      create  app/services/api_keys/api_keys_suite_test.go
      create  app/services/api_keys/api_keys_test.go
      create  app/middlewares/require_api_key.go
      create  app/middlewares/require_api_key_test.go
      create  app/controllers/authentication_api_key.go
      create  cli_api_keys.go
      insert  app/controllers/application.go: APIKeys *api_keys.Service
      insert  app/application.go: server.APIKeys = api_keys.New(store)
      insert  main.go: "api_keys": runAPIKeys,
         run  go mod tidy
        next  mount the routes it guards in app/controllers/routes.go: s.Posts.SetupRoutes(s.WithAPIKey(&r.RouterGroup))
         run  sqlc generate
```

After the migration, `bogie api_keys:create ci` prints the key and then confirms it. The key is shown once; the real one is longer than the `…` here:

```
dc43792c3668.…
api key "ci" made (1); it is shown once:
```

Before the migration has run, the same command fails:

```
blog: store: create api_key: ERROR: relation "api_keys" does not exist (SQLSTATE 42P01)
```

**relation "api_keys" does not exist** means the table is not there yet. Run `bogie db:migrate`, then `bogie api_keys:create ci` again.

Without a name, it prints a usage text and ends with:

```
Usage: blog api_keys create NAME
...
blog: api_keys: create NAME is the one command
```

**api_keys: create NAME is the one command**: give the key a name, as in `bogie api_keys:create ci`.

Try it: with no key, the guard answers 401:

```
$ curl -i localhost:8080/posts
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Www-Authenticate: Bearer realm="blog"

{"status":"error","error":"an api key is required"}
```

A key that does not verify is **HTTP/1.1 401 Unauthorized** with **invalid api key**, and no `Www-Authenticate` header. Garbage (`-H "Authorization: Bearer not-a-key"`) and the real prefix with a wrong secret part answer the same:

```
$ curl -i localhost:8080/posts -H "Authorization: Bearer not-a-key"
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8

{"status":"error","error":"invalid api key"}
```

The real key, sent the same way, is a `200 OK`. The generated guards still answer 401 for every authentication refusal. Since v0.7.0, authorization is a separate step: `bogie g policy` writes a policy and a service, and a denial is 403. See [Authorization](https://bogie-go.com/docs/authorization.html).

## Removing

`bogie d authentication <shape>` removes the middleware, its test, and the group helper, and removes its group from `config/` and `config/config.go`. The development value stays behind in the credentials file; it guards nothing once the field that read it is gone, so it is harmless left in place.
