# Authentication and Authorisation — API Design and Versioning

Source: https://www.geekswithgeeks.com/en/api-design/sec-auth

> Choose API keys, OAuth 2.0 or JWTs appropriately and enforce least-privilege scopes.

## Who are you, and what may you do?

**Authentication** proves identity; **authorisation** decides what that identity may do. **API keys** are simple for server-to-server access and identify an application, but they are long-lived secrets: send them in a header (never in the URL), allow rotation and revocation, and scope them. **OAuth 2.0** (with OpenID Connect for login) is the standard when users grant a third-party app limited access to their data: short-lived **access tokens** with **scopes** (`orders:read`) and refresh tokens; use the authorisation-code flow with PKCE for apps. **JWTs** are signed tokens that carry claims; validate signature, issuer, audience and expiry on every call. Always use **HTTPS**, check authorisation on **every request** on the server, and return `401` or `403` appropriately.

## Verify, limit, minimise

Authenticate every caller, check every object access and expose only what is needed.

![Three duties: authenticate, authorise, minimise.](assets/figures/api-design/section-4-map.svg) — Figure 4.1 — Authenticate, authorise and minimise.

## Scopes in an OpenAPI security scheme (illustrative)

Scopes let a token be limited to the operations a client really needs.

```yaml
components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://auth.example.com/authorize
          tokenUrl: https://auth.example.com/token
          scopes:
            orders:read: Read orders
            orders:write: Create and change orders
security:
  - oauth2: [orders:read]
```

## Never put secrets in URLs

URLs end up in logs, browser history and referrer headers. Send tokens in the `Authorization` header, not in query strings.

**Quiz:** Where should an access token be sent?

- [ ] In the URL query string
- [x] In the Authorization header over HTTPS
- [ ] In the page title
- [ ] In a public repository

*Answer:* In the Authorization header over HTTPS. Headers over TLS avoid leaking credentials into logs and history.
