Skip to content

Core\Api\KeyIn

The place where a client sends the key of an ApiKey security scheme. You write it as in: in an #[Core\Api\Scheme].

There are three cases:

  • Query is a query parameter in the URL.
  • Header is a request header.
  • Cookie is a cookie.

parameter: is the name of that query parameter, header or cookie. name: is the name of the scheme itself. A route uses that name in #[Core\Api(security: [...])].

nvs build --openapi writes the case as the scheme's in, for example header.

Good to know: a key in the query is part of the URL. Servers and proxies often write URLs to their logs, so a header is usually the safer place for a key.

Examples

The three places a key can go

<?nvs
// Shows the three places where a client can send an API key.
// This scheme says that a client sends its key in a header named `X-Api-Key`.
#[Core\Api\Scheme(name: 'key', type: Core\Api\SchemeType::ApiKey, in: Core\Api\KeyIn::Header, parameter: 'X-Api-Key')]
class Auth
{}
class Places
{
// Returns one line that tells a client how to send a key named `$parameter`.
public static function howToSend(Core\Api\KeyIn $in, string $parameter): string
{
return match ($in) {
Core\Api\KeyIn::Query => 'add ?' . $parameter . '=... to the URL',
Core\Api\KeyIn::Header => 'send the header ' . $parameter . ': ...',
Core\Api\KeyIn::Cookie => 'send the cookie ' . $parameter . '=...',
};
}
}
array<Core\Api\KeyIn> $everywhere = [
Core\Api\KeyIn::Query,
Core\Api\KeyIn::Header,
Core\Api\KeyIn::Cookie,
];
foreach ($everywhere as Core\Api\KeyIn $in) {
echo Places::howToSend($in, 'shop_key'), "\n";
}
Output
add ?shop_key=... to the URL
send the header shop_key: ...
send the cookie shop_key=...

A key in a header and a key in a cookie

<?nvs
// Declares two key schemes, one in a header and one in a cookie, and a route that accepts both.
// `parameter` is the name of the header or the cookie. `name` is the name of the scheme.
#[Core\Api\Scheme(name: 'partnerKey', type: Core\Api\SchemeType::ApiKey, in: Core\Api\KeyIn::Header, parameter: 'X-Partner-Key')]
#[Core\Api\Scheme(name: 'session', type: Core\Api\SchemeType::ApiKey, in: Core\Api\KeyIn::Cookie, parameter: 'shop_session')]
class Auth
{}
class Products
{
/// List the products.
#[Core\Route(path: '/products', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
// A partner sends its key in a header. A browser sends the session cookie.
#[Core\Api(security: ['partnerKey', 'session'])]
public function list(): string
{
return 'tea, coffee';
}
}
// `nvs build --openapi` writes both schemes to the API document.
// When the program runs, the route works the same with or without them.
Products $products = new Products();
// This prints `tea, coffee`.
echo $products->list(), "\n";
Output
tea, coffee