Skip to content

Commit

Permalink
feat(docs): Add design for Next.js
Browse files Browse the repository at this point in the history
  • Loading branch information
LauraBeatris committed Apr 8, 2024
1 parent 82f398c commit 0c95c7d
Show file tree
Hide file tree
Showing 6 changed files with 187 additions and 6 deletions.
4 changes: 2 additions & 2 deletions docs/malta.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
{
"title": "Design",
"pages": [
["Next.js SDK", "/design/sdk"],
["Components", "/design/components"]
["With Next.js", "/design/next"],
["With Node.js", "/design/node"]
]
},
{
Expand Down
2 changes: 1 addition & 1 deletion docs/pages/communication/credentials/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Instead of managing those credentials in-house, it's a good practice to use a th

### JSON Web Tokens

Regardless the authentication protocol chose for M2M communication, it'll involves [JWT]([JSON Web Token](https://datatracker.ietf.org/doc/html/rfc7519)) at some point, therefore let's do a quick recap on it.
Regardless the authentication protocol chose for M2M communication, it'll involves [JSON Web Token](https://datatracker.ietf.org/doc/html/rfc7519) at some point, therefore let's do a quick recap on it.

#### JWT vs API Keys

Expand Down
2 changes: 1 addition & 1 deletion docs/pages/communication/use-cases/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ This section outlines use cases in which applications have to support for secure

### API Key Management

The first scenario involves API Key Management, it behaves a bit different than Service-to-Service Tokens. When SaaS applications have their own set of APIs that need to communicate with their customer machines without using user's identity.
The first scenario involves API Key Management, it behaves differently than Service-to-Service Tokens. When SaaS applications have their own set of APIs that need to communicate with their customer machines without using the user's identity.

A set of API keys are generated from the SaaS application which can then be sent from the customer's API request via a HTTP header.

Expand Down
104 changes: 104 additions & 0 deletions docs/pages/design/next/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
---
title: "Design - Next.js"
---

# M2M auth with Next.js

Design proposal on how to perform M2M auth for SaaS applications built with Next.js that exposes route handlers for external clients.

Clerk is used as the auth provider for this example. Although Clerk doesn't expose M2M auth at the time of writing this, the goal is to showcase how this would fit their product.

### UI Component

Provide a component for key management, eliminating the need for developers to directly interact with the authorization server to build the UI from scratch.

```tsx
import { KeysManager } from '@clerk/nextjs';

export default function Page() {
return <KeysManager />;
}
```

### UI utilities

Besides the UI component, some utilities could also be exposed to manage API keys from the client-side.

React Hooks, such as: `useApiKeys()`

```tsx
"use client";

import { useApiKeys } from "@clerk/clerk-react";

export default function Page() {
const { apiKeys, createApiKeys } = useApiKeys();

return (...);
}
```

### Protecting route handlers

```ts
import { NextResponse } from 'next/server';
import { auth } from '@clerk/nextjs';

export async function GET() {
const { externalClientId } = auth();

if (!externalClientId){
return new Response("Unauthorized", { status: 401 });
}

const data = { message: 'Hello World' };

return NextResponse.json({ data });
}
```

### With middleware

**First approach (recomended):** Introduce a new option into the existing `authMiddleware` to authenticate certain routes via API keys, rather than using the user's identity.

```ts
import { authMiddleware } from "@clerk/nextjs";

export default authMiddleware({
protectedWithExternalKeys: ["/my-sass-api-route"],
});

export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};
```

The current workaround for developers that integrate [Unkey](https://unkey.dev) with Clerk, requires setting protected routes with keys to `publicRoutes` in order to bypass the user's identity verification on the request headers, which is not intuitive.

**Second approach:** Introduce new middleware that authenticates via API keys only.

```ts
import { authMiddleware } from "@clerk/nextjs";

export default keysMiddleware();

export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};
```

#### Identify external client within the request

The `Auth` object should contain a `externalClientId`, essentially the identifier of your customer machine.

This should be accessible via the `auth` helper (requiring the `authMiddleware` to be enabled).

```ts
import { auth } from "@clerk/nextjs";

export default function Page() {
const { externalClientId } = auth();

return (...);
}
```
79 changes: 79 additions & 0 deletions docs/pages/design/node/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: "Design - Node.js"
---

# M2M auth with Node.js

Design proposal on how to perform M2M auth for SaaS applications built with Node.js that expose API endpoints for external clients.

Clerk is used as the auth provider for this example. Although Clerk doesn't expose M2M auth at the time of writing this, the goal is to showcase how this would fit their product.

### API Endpoints

#### Creating keys

This example is only providing the key `name` as metadata, but other properties might be needed as well for further customization, such as:
- Roles, for access control
- Expiration time
- Limit the number of requests a key can make

For reference, [Unkey](https://unkey.com) is a service for key management which provides further customization, such as rate limiting per key.

```ts
app.post('/create-key', ClerkExpressRequireAuth(), async (req, res) => {
try {
const { key } = await clerkClient.createKey({
name: req.body.name,
// Links a Clerk API key to a customer record
// Clerk's API should also relate a key to the user's id who created the key and it's Clerk application
externalClientId: req.body.teamId
})

res.json({ key })
} catch (error) {
res.json({ error: error.message })
}
})
```

The key should already be associated with your application client ID, so you don't have to [programmatically create it like with Okta](https://developer.okta.com/blog/2018/06/06/node-api-oauth-client-credentials#register-clients-on-the-fly), however it's necessary to associate with your customer's record so you can access this information on the request.

The hashed key should be returned in the response for better security. When attempting to verify the API Key, then the `key` argument provided should be hashed and compared to the stored hashed key. If they match, then the API Key is valid.

#### Protecting API endpoints with keys

**First approach:** Calls SDK to verify key and handles the response.
```js
app.post('/protected-with-key', async (req, res) => {
const authHeader = req.headers["authorization"]
const key = authHeader?.toString().replace("Bearer ", "");

if (!key) {
return res.status(401).send("Unauthorized")
}

try {
const { error } = await clerkClient.verifyKey(key)

if (error) {
return res.status(500).send("Internal Server Error")
}

res.json({ protected: true })
} catch (error) {
res.json({ error: error.message })
}
})
```
**Second approach:** Integrate with a middleware that already reads the key from the request. It could reuse the existing [`ClerkExpressRequireAuth` Express middleware](https://clerk.com/docs/backend-requests/handling/nodejs) or create a new middleware to protect with API keys only.
```js
app.post('/protected-with-key', ClerkExpressRequireKey(), async (req, res) => {
res.json({ protected: true })
})
```
#### Identify external client within the request
The `req.auth` would contain the `externalClientId` that provides the link to your customer record.
2 changes: 0 additions & 2 deletions docs/pages/research/stytch/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ The API call returns `client_id` and `client_secret` credentials to be exchanged

Permissions can be enforced by specifying `scopes` in which is going to be contained in the returned `access_token`.

An application has to call this API endpoint in order to surface credentials for usage in other external services.

### Calling Stytch's `/oauth2/token` endpoint to retrieve access token

```bash
Expand Down

0 comments on commit 0c95c7d

Please sign in to comment.