# Authentication

Choose a personal API key or OAuth 2.1 with PKCE.

Use a [personal API key](/docs/partners-api/api-keys.mdx) for your own scripts. Use OAuth for an application acting for other NinjaBuy customers, including MCP clients.

## OAuth 2.1

Use the authorization code flow with PKCE S256. REST and [MCP](/docs/mcp.mdx) accept the same NinjaBuy OAuth access token. Each token acts for the account that signed in and approved access; you cannot select another account in the request body.

All OAuth endpoints use the origin `https://www.ninjabuy.com`. Discovery and authorization paths:

[OAuth discovery](https://www.ninjabuy.com/.well-known/oauth-authorization-server) · [MCP resource discovery](https://www.ninjabuy.com/.well-known/oauth-protected-resource/mcp)

```text
POST /api/auth/mcp/register
GET  /api/auth/mcp/authorize
POST /api/auth/mcp/token
```

1. Register your client at `POST /api/auth/mcp/register`. A public client sends JSON with `client_name`, `redirect_uris` and `token_endpoint_auth_method: "none"`. Keep the returned `client_id`.
2. Generate a fresh random `state` and PKCE `code_verifier`. Derive the base64url-encoded SHA-256 `code_challenge`.
3. Open `/api/auth/mcp/authorize` in the user's browser with `response_type=code`, `client_id`, `redirect_uri`, `state`, `code_challenge`, `code_challenge_method=S256` and `scope=openid offline_access`.
4. The user signs in with their NinjaBuy phone number and approves your application. At your callback, verify `state` before using the returned `code`.
5. Send a form-encoded POST to `/api/auth/mcp/token` with `grant_type=authorization_code`, `code`, `client_id`, the same `redirect_uri` and `code_verifier`.

Send the resulting access token on REST requests:

```http
Authorization: Bearer YOUR_ACCESS_TOKEN
```

Access tokens last 1 hour. With `offline_access`, refresh tokens allow renewal for up to 7 days. Refresh through the same token endpoint using a form-encoded POST with `grant_type=refresh_token`, `client_id` and `refresh_token`. Store tokens securely and sign in again when renewal is no longer valid.

A missing, expired or invalid access token returns `401` with a `WWW-Authenticate` discovery challenge. See [Errors](/docs/partners-api/errors.mdx).
