> For the complete documentation index, see [llms.txt](https://timechain.gitbook.io/neucron/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timechain.gitbook.io/neucron/neucron-oauth-2.0.md).

# Neucron OAuth 2.0

This documentation is stack-agnostic. Use it with any frontend, backend, or hosting environment. Only your platform name, redirect URIs, and credentials are project-specific.

***

### 1. Overview

**Sign in with Neucron** authenticates users with their Neucron account and returns an access token your application can use to call Neucron APIs.

| Item               | Detail                                           |
| ------------------ | ------------------------------------------------ |
| Protocol           | OAuth 2.0 **Authorization Code**                 |
| Authorize endpoint | `{AUTHORIZE_HOST}/v1/oauth/authorize`            |
| Token endpoint     | `{AUTHORIZE_HOST}/v1/oauth/token`                |
| Hosted UI          | Neucron login / registration pages               |
| Typical host       | `https://dev.neucron.io` (environment-dependent) |

Your application:

1. Redirects the user to Neucron for authentication.
2. Receives an authorization `code` on your registered callback URL.
3. Exchanges the `code` for an `access_token` **on the server** (client secret never leaves the backend).
4. Stores the token and uses it as a bearer credential for Neucron REST APIs.

***

### 2. OAuth flow

```mermaid
sequenceDiagram
    participant User
    participant App as Your Application
    participant Server as Your Backend
    participant Neucron as Neucron OAuth
    participant API as Neucron REST API

    User->>App: Click "Sign in with Neucron"
    App->>Server: Start OAuth (e.g. GET /auth/login)
    Server->>Neucron: GET /v1/oauth/authorize
    Neucron-->>Server: { redirect_url }
    Server-->>User: Redirect to Neucron hosted login
    User->>Neucron: Complete sign-in or sign-up
    Neucron-->>Server: Redirect to callback?code&state
    Server->>Neucron: GET /v1/oauth/token (code exchange)
    Neucron-->>Server: { access_token }
    Server-->>App: Establish session / return token
    App->>API: Authorized requests with access_token
```

***

### 3. Prerequisites

* Access to the Neucron developer / OAuth console
* Ability to create an OAuth client for **your** platform / app
* A publicly reachable (or locally tunneled) **redirect URI** for the callback
* A backend (or serverless function) that can hold `client_secret` securely
* Test users with access to **your** platform on Neucron

***

### 4. Register your OAuth application

1. Open the Neucron OAuth / developer console.
2. Create an OAuth application.
3. Set the **platform / app name** (e.g. `YourApp`). This value must match the `platform` parameter you send in the authorize request.
4. Copy the **Client ID** and **Client Secret**.
5. Register one or more **exact** redirect URIs, for example:
   * Development: `https://localhost:3000/auth/callback` (or your callback path)
   * Production: `https://your-domain.com/auth/callback`
6. Ensure test accounts are granted access to your platform on Neucron.

{% hint style="warning" %}
`redirect_uri` must match **exactly** (scheme, host, port, path) between:

* what you register in the Neucron console
* what you send on authorize
* what you send on token exchange
  {% endhint %}

***

### 5. Configuration

Store credentials in environment variables (or a secrets manager). Never expose `client_secret` to the browser.

| Variable                | Required    | Description                                             |
| ----------------------- | ----------- | ------------------------------------------------------- |
| `NEUCRON_CLIENT_ID`     | Yes         | OAuth client ID                                         |
| `NEUCRON_CLIENT_SECRET` | Yes         | OAuth client secret (server only)                       |
| `PUBLIC_AUTHORIZE_HOST` | Yes         | Neucron host, e.g. `https://dev.neucron.io`             |
| `NEUCRON_API_BASE_URL`  | Yes         | REST API base, typically `{AUTHORIZE_HOST}/v1`          |
| `OAUTH_REDIRECT_URI`    | Recommended | Exact callback URL registered with Neucron              |
| `PLATFORM_NAME`         | Recommended | Platform string sent as `platform` (must match console) |

Example:

```env
NEUCRON_CLIENT_ID=<from Neucron console>
NEUCRON_CLIENT_SECRET=<from Neucron console>
PUBLIC_AUTHORIZE_HOST=https://dev.neucron.io
NEUCRON_API_BASE_URL=https://dev.neucron.io/v1
OAUTH_REDIRECT_URI=https://your-domain.com/auth/callback
PLATFORM_NAME=YourApp
```

***

### 6. Authorization request

#### Endpoint

```http
GET {PUBLIC_AUTHORIZE_HOST}/v1/oauth/authorize
```

#### Query parameters

| Parameter       | Required    | Description                                         |
| --------------- | ----------- | --------------------------------------------------- |
| `response_type` | Yes         | Must be `code`                                      |
| `client_id`     | Yes         | Your OAuth client ID                                |
| `redirect_uri`  | Yes         | Exact registered callback URL                       |
| `state`         | Recommended | Opaque CSRF token (e.g. UUID); validate on callback |
| `platform`      | Yes         | Your registered platform / app name                 |
| `flow`          | Optional    | `sign-in` (default) or `sign-up`                    |

#### Example

```http
GET https://dev.neucron.io/v1/oauth/authorize
  ?response_type=code
  &client_id=YOUR_CLIENT_ID
  &redirect_uri=https%3A%2F%2Fyour-domain.com%2Fauth%2Fcallback
  &state=550e8400-e29b-41d4-a716-446655440000
  &platform=YourApp
  &flow=sign-in
Accept: application/json
```

#### Response

Neucron returns JSON containing a hosted login URL:

```json
{
  "redirect_url": "https://dev.neucron.io/..."
}
```

Redirect the user's browser to `redirect_url`.

{% hint style="info" %}
Call authorize from your **backend** (or a BFF), then `302` the browser to `redirect_url`. Do not embed `client_secret` in this step.
{% endhint %}

***

### 7. Token exchange

After the user authenticates, Neucron redirects to your `redirect_uri`:

```
https://your-domain.com/auth/callback?code=AUTHORIZATION_CODE&state=STATE
```

#### Endpoint

```http
GET {PUBLIC_AUTHORIZE_HOST}/v1/oauth/token
```

#### Query parameters

| Parameter       | Required    | Description                            |
| --------------- | ----------- | -------------------------------------- |
| `grant_type`    | Yes         | `authorization_code`                   |
| `code`          | Yes         | Authorization code from the callback   |
| `redirect_uri`  | Yes         | Same URI used in the authorize request |
| `client_id`     | Yes         | OAuth client ID                        |
| `client_secret` | Yes         | OAuth client secret                    |
| `state`         | Recommended | Same `state` from authorize / callback |

#### Example

```http
GET https://dev.neucron.io/v1/oauth/token
  ?grant_type=authorization_code
  &code=AUTHORIZATION_CODE
  &redirect_uri=https%3A%2F%2Fyour-domain.com%2Fauth%2Fcallback
  &client_id=YOUR_CLIENT_ID
  &client_secret=YOUR_CLIENT_SECRET
  &state=550e8400-e29b-41d4-a716-446655440000
```

#### Response

```json
{
  "access_token": "..."
}
```

Treat `access_token` as an opaque bearer token. Perform this exchange **only on the server**.

***

### 8. Callback & session

#### Callback handler responsibilities

1. Reject missing `code`.
2. Validate `state` against the value you issued at authorize time.
3. Exchange `code` for `access_token` (see Token exchange).
4. Persist the session using a pattern appropriate to your stack, for example:
   * **httpOnly cookie** (recommended for browser apps)
   * **Server session store** keyed by session ID
   * **Secure token storage** for mobile / native clients
5. Redirect the user into your authenticated app area.

#### Suggested browser session pattern

| Storage                                         | Readable by JS | Purpose                                                    |
| ----------------------------------------------- | -------------- | ---------------------------------------------------------- |
| Server httpOnly cookie (e.g. `neucron_session`) | No             | Holds OAuth `access_token` after callback                  |
| Client-readable token (optional bridge)         | Yes            | Used if the SPA must attach `Authorization` headers itself |

If the SPA needs the token in the browser:

1. Keep the primary token in an httpOnly cookie.
2. Expose a same-origin endpoint such as `GET /auth/me` that returns `{ authenticated, token }` when the cookie is present.
3. Call that endpoint with credentials included (`credentials: 'include'` in `fetch`).

***

### 9. Client integration

#### Sign-in button

Any UI can start the flow by navigating the browser to your backend authorize starter, for example:

```
GET /auth/login?flow=sign-in
```

Your backend builds the Neucron authorize URL, fetches `redirect_url`, and redirects the user.

Minimal client example:

```js
function signInWithNeucron(flow = 'sign-in') {
  window.location.href = `/auth/login?flow=${encodeURIComponent(flow)}`;
}
```

Use a full-page redirect (not XHR alone) so the browser can follow Neucron’s hosted login redirects.

#### Recommended backend routes

| Route            | Method       | Purpose                                                |
| ---------------- | ------------ | ------------------------------------------------------ |
| `/auth/login`    | `GET`        | Start OAuth; redirect to Neucron                       |
| `/auth/callback` | `GET`        | Receive `code`, exchange token, set session            |
| `/auth/me`       | `GET`        | Return session status / token to the client (optional) |
| `/auth/logout`   | `POST`/`GET` | Clear session cookie and client state                  |

Route paths are conventions — adapt them to your framework (Express, Nest, Next.js, Django, Spring, Go, etc.).

#### Post-login bootstrap

On app load:

1. Check for an existing session / token.
2. If missing, call your session endpoint (e.g. `/auth/me`) with cookies.
3. If authenticated, load user profile and app data from Neucron APIs.

***

### 10. API usage after login

Call Neucron REST APIs with the access token:

```http
GET {NEUCRON_API_BASE_URL}/auth/user/info
Authorization: <access_token>
```

Common headers:

| Header                  | When                 | Description                              |
| ----------------------- | -------------------- | ---------------------------------------- |
| `Authorization`         | Always               | Access token from OAuth (or email login) |
| `X-Neucron-Business-ID` | Business-scoped APIs | Active business / team ID                |

Typical hydration after sign-in:

1. `GET /auth/user/info`
2. Load businesses / teams
3. Resolve roles / permissions
4. Load product-specific resources (wallets, assets, etc.)

***

### 11. Flows: sign-in vs sign-up

| `flow` value | Behavior                           |
| ------------ | ---------------------------------- |
| `sign-in`    | Existing Neucron account (default) |
| `sign-up`    | Neucron registration path          |

Both use the same authorize → callback → token exchange pipeline. Only the hosted UI path differs.

***

### 12. Security guidelines

1. **Never expose `client_secret`** to browsers, mobile binaries, or public repos.
2. Always use **HTTPS** in production for authorize, callback, and token exchange.
3. Generate a random **`state`** per login attempt and verify it on callback (CSRF protection).
4. Prefer **httpOnly**, `Secure`, `SameSite=Lax` (or `Strict`) cookies for browser sessions.
5. Keep `redirect_uri` allowlists tight — no wildcards unless Neucron explicitly supports and you need them.
6. On logout, clear **both** server session cookies and any client-stored tokens.
7. Treat the access token as opaque; do not rely on client-side JWT decoding for authorization decisions.

***

### 13. Verification checklist

* [ ] OAuth app created; platform name matches `platform` param
* [ ] Client ID and secret configured on the server only
* [ ] Redirect URI registered and identical in authorize + token steps
* [ ] Authorize returns `redirect_url`; browser reaches Neucron hosted login
* [ ] After login, callback receives `code` and `state`
* [ ] Token exchange returns `access_token`
* [ ] Session is established (cookie / store)
* [ ] Authenticated API call succeeds (e.g. `/auth/user/info`)
* [ ] Logout clears the session completely

***

### 14. Troubleshooting

| Symptom                               | Likely cause                               | Fix                                                                |
| ------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------ |
| Authorize error / no `redirect_url`   | Invalid `client_id`, host, or `platform`   | Verify credentials, `PUBLIC_AUTHORIZE_HOST`, and platform name     |
| Redirect URI rejected                 | URI mismatch                               | Align console registration with authorize and token `redirect_uri` |
| Token exchange failed                 | Wrong secret, reused code, or URI mismatch | Check `client_secret`; codes are single-use; keep URI identical    |
| Session missing after callback        | Cookie flags / domain / path issues        | Confirm `Secure`/`SameSite`/`Path`; call APIs with credentials     |
| User cannot access app                | Account lacks platform grant               | Grant your platform access on Neucron                              |
| Logged out then immediately logged in | OAuth session cookie not cleared           | Clear server session on logout                                     |

***

### 15. Reference

#### Endpoints summary

| Step                | Method | URL                                          |
| ------------------- | ------ | -------------------------------------------- |
| Authorize           | `GET`  | `{PUBLIC_AUTHORIZE_HOST}/v1/oauth/authorize` |
| Token               | `GET`  | `{PUBLIC_AUTHORIZE_HOST}/v1/oauth/token`     |
| User info (example) | `GET`  | `{NEUCRON_API_BASE_URL}/auth/user/info`      |

#### Authorize parameters

`response_type`, `client_id`, `redirect_uri`, `state`, `platform`, `flow`

#### Token parameters

`grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `client_secret`, `state`

#### Platform name

`platform` is **project-specific**. Register it in the Neucron console and send the same string from your login handler. Do not reuse another application’s platform name.

***

*Neucron OAuth 2.0 Authorization Code — Sign in with Neucron. Applicable to any application stack.*
