# `OzMcp.Auth.Principal`
[🔗](https://github.com/oz-elixir/oz_mcp/blob/v0.9.0/lib/oz_mcp/auth/principal.ex#L1)

The authenticated caller.

The principal never holds the raw bearer token. It holds the identity
of the caller (`issuer` and `subject`), the granted scopes and the
claims the application copies from its own token check.

`audiences` holds the audiences of the token (the `aud` claim of a
JWT, RFC 7519). Give `nil`, one string, or a list of strings: `new!/1`
puts one string in a list. OzMcp compares the audiences with the
`resource_url` of the server (RFC 8707) and refuses a principal whose
audiences hold no entry for it with `401`, unless the server set
`audience_check false` in its `authorization` block. A principal with
no audiences is refused too (fail closed).

Keep `claims` small. The principal is held by the session and, for
task-augmented calls, copied into the task record for the life of the
task. Copy only the claims the callbacks need.

`expires_at` is Unix time in seconds, as the `exp` claim of a JWT. A
number with a fraction is allowed. A very large value is a valid time
that is far in the future: the computations of `expires_in/2` and
`expired?/2` never raise for a number. OzMcp reads the field in two places:
the gate refuses a principal that is expired and a `GET` stream ends when
its principal expires. The clock of the server decides. If the clocks of
the issuer and of the server can differ, subtract a margin from `exp`.

# `t`

```elixir
@type t() :: %OzMcp.Auth.Principal{
  audiences: [String.t()] | nil,
  claims: map(),
  client_id: String.t() | nil,
  expires_at: number() | nil,
  issuer: String.t() | nil,
  scopes: [String.t()],
  subject: String.t()
}
```

# `expired?`

```elixir
@spec expired?(t(), integer()) :: boolean()
```

True when the principal has an expiry and it is not in the future.

# `expires_in`

```elixir
@spec expires_in(t(), integer()) :: integer() | nil
```

Milliseconds until the principal expires. The result is zero or negative
when the principal is expired. It is `nil` when the principal has no
expiry.

`expires_at` is Unix time in seconds, as the `exp` claim of a JWT.

# `key`

```elixir
@spec key(t()) :: {String.t() | nil, String.t()}
```

The key that binds a session to a principal: `{issuer, subject}`.

# `new!`

```elixir
@spec new!(keyword() | map()) :: t()
```

Build a principal from keyword attributes or a map. Raises
`ArgumentError` when the subject is not a non-empty string, when the
issuer is neither a string nor `nil`, when the scopes are not a list of
strings, when `audiences` is neither a string, a list of strings nor
`nil`, when `expires_at` is neither a number nor `nil`, or when an
unknown attribute is given.

# `scope?`

```elixir
@spec scope?(t(), String.t() | [String.t()]) :: boolean()
```

True when the principal holds every needed scope. Accepts one scope or
a list of scopes.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
