-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
82f398c
commit 6bfa53c
Showing
6 changed files
with
142 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
--- | ||
title: "Design - Next.js" | ||
--- | ||
|
||
# M2M auth with Next.js | ||
|
||
Design proposal on how to perform M2M auth for a SaaS applications built with Next.js that exposes route handlers for external clients. | ||
|
||
### UI Component | ||
|
||
Provide a component for keys 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 />; | ||
} | ||
``` | ||
|
||
### 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: Introduce a new option into existing middleware to authenticate certain routes via API keys in headers, rather than user identity. | ||
|
||
```ts | ||
import { authMiddleware } from "@clerk/nextjs"; | ||
|
||
export default authMiddleware({ | ||
protectedWithExternalKeys: ["/my-sass-api-route"], | ||
}); | ||
|
||
export const config = { | ||
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"], | ||
}; | ||
``` | ||
|
||
TODO: | ||
- How to handle user identity protected routes vs key protected routes | ||
- How to protect route handlers without using middleware | ||
- How to expose utilities outside of the component to handle keys, eg: Hooks, server actions |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
||
We'll use Clerk as the auth provider for this example. Although Clerk don't expose M2M authentication at the time of writing this, the goal is to showcase how this would fit their product and also integrate with [a component approach using Next.js](../next/). | ||
|
||
### 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 | ||
- Owner ID: Often this will be the user ID from the current session. If you're already using an auth provider like Clerk, it should be able to include it for you. | ||
|
||
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 relates the key to the user's id in which 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). | ||
|
||
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 for the purpose of protecting from external usage 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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters