Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚠️ DO NOT MERGE YET | Add support for Federated Connection Access Token #1924

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
- [Custom routes](#custom-routes)
- [Testing helpers](#testing-helpers)
- [`generateSessionCookie`](#generatesessioncookie)
- [Getting access tokens for connections](#getting-access-tokens-for-connections)
- [On the server (App Router)](#on-the-server-app-router-3)
- [On the server (Pages Router)](#on-the-server-pages-router-3)
- [Middleware](#middleware-3)

## Passing authorization parameters

Expand Down Expand Up @@ -752,3 +756,134 @@ const sessionCookieValue = await generateSessionCookie(
}
)
```

## Getting access tokens for connections
You can retrieve an access token for a connection using the `getAccessTokenForConnection()` method, which accepts an object with the following properties:
- `connection`: The federated connection for which an access token should be retrieved.
- `login_hint`: The optional login_hint parameter to pass to the `/authorize` endpoint.

### On the server (App Router)

On the server, the `getAccessTokenForConnection()` helper can be used in Server Routes, Server Actions and Server Components to get an access token for a connection.

> [!IMPORTANT]
> Server Components cannot set cookies. Calling `getAccessTokenForConnection()` in a Server Component will cause the access token to be refreshed, if it is expired, and the updated token set will not to be persisted.
>
> It is recommended to call `getAccessTokenForConnection(req, res)` in the middleware if you need to refresh the token in a Server Component as this will ensure the token is refreshed and correctly persisted.

For example:

```ts
import { NextResponse } from "next/server"

import { auth0 } from "@/lib/auth0"

export async function GET() {
try {
const token = await auth0.getAccessTokenForConnection({ connection: 'google-oauth2' })
// call external API with token...
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
}

return NextResponse.json({
message: "Success!",
})
}
```

### On the server (Pages Router)

On the server, the `getAccessTokenForConnection({}, req, res)` helper can be used in `getServerSideProps` and API routes to get an access token for a connection, like so:

```ts
import type { NextApiRequest, NextApiResponse } from "next"

import { auth0 } from "@/lib/auth0"

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<{ message: string }>
) {
try {
const token = await auth0.getAccessTokenForConnection({ connection: 'google-oauth2' }, req, res)
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
}

res.status(200).json({ message: "Success!" })
}
```

### Middleware

In middleware, the `getAccessTokenForConnection({}, req, res)` helper can be used to get an access token for a connection, like so:

```tsx
import { NextRequest, NextResponse } from "next/server"

import { auth0 } from "@/lib/auth0"

export async function middleware(request: NextRequest) {
const authRes = await auth0.middleware(request)

if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes
}

const session = await auth0.getSession(request)

if (!session) {
// user is not authenticated, redirect to login page
return NextResponse.redirect(new URL("/auth/login", request.nextUrl.origin))
}

const accessToken = await auth0.getAccessTokenForConnection({ connection: 'google-oauth2' }, request, authRes)

// the headers from the auth middleware should always be returned
return authRes
}
```

> [!IMPORTANT]
> The `request` and `response` objects must be passed as a parameters to the `getAccessTokenForConnection({}, request, response)` method when called from a middleware to ensure that the refreshed access token can be accessed within the same request.

If you are using the Pages Router and are calling the `getAccessTokenForConnection` method in both the middleware and an API Route or `getServerSideProps`, it's recommended to propagate the headers from the middleware, as shown below. This will ensure that calling `getAccessTokenForConnection` in the API Route or `getServerSideProps` will not result in the access token being refreshed again.

```ts
import { NextRequest, NextResponse } from "next/server"

import { auth0 } from "@/lib/auth0"

export async function middleware(request: NextRequest) {
const authRes = await auth0.middleware(request)

if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes
}

const session = await auth0.getSession(request)

if (!session) {
// user is not authenticated, redirect to login page
return NextResponse.redirect(new URL("/auth/login", request.nextUrl.origin))
}

const accessToken = await auth0.getAccessTokenForConnection({ connection: 'google-oauth2' }, request, authRes)

// create a new response with the updated request headers
const resWithCombinedHeaders = NextResponse.next({
request: {
headers: request.headers,
},
})

// set the response headers (set-cookie) from the auth response
authRes.headers.forEach((value, key) => {
resWithCombinedHeaders.headers.set(key, value)
})

// the headers from the auth middleware should always be returned
return resWithCombinedHeaders
}
```
2 changes: 1 addition & 1 deletion examples/with-shadcn/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { NextRequest } from "next/server"
import { auth0 } from "./lib/auth0"

export async function middleware(request: NextRequest) {
return await auth0.middleware(request)
return await auth0.middleware(request);
}

export const config = {
Expand Down
2 changes: 1 addition & 1 deletion examples/with-shadcn/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"lint": "next lint"
},
"dependencies": {
"@auth0/nextjs-auth0": "^4.0.0",
"@auth0/nextjs-auth0": "^4.0.1",
"@radix-ui/react-avatar": "^1.1.1",
"@radix-ui/react-collapsible": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.2",
Expand Down
10 changes: 5 additions & 5 deletions examples/with-shadcn/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions src/errors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,49 @@ export class AccessTokenError extends SdkError {
this.code = code;
}
}

/**
* Enum representing error codes related to access tokens for connections.
*/
export enum AccessTokenForConnectionErrorCode {
/**
* The session is missing.
*/
MISSING_SESSION = "missing_session",

/**
* The refresh token is missing.
*/
MISSING_REFRESH_TOKEN = "missing_refresh_token",

/**
* Failed to exchange the refresh token.
*/
FAILED_TO_EXCHANGE = "failed_to_exchange_refresh_token"
}

/**
* Error class representing an access token for connection error.
* Extends the `SdkError` class.
*/
export class AccessTokenForConnectionError extends SdkError {
/**
* The error code associated with the access token error.
*/
public code: string;
public cause?: OAuth2Error;

/**
* Constructs a new `AccessTokenForConnectionError` instance.
*
* @param code - The error code.
* @param message - The error message.
* @param cause - The OAuth2 cause of the error.
*/
constructor(code: string, message: string, cause?: OAuth2Error) {
super(message);
this.name = "AccessTokenForConnectionError";
this.code = code;
this.cause = cause;
}
}
Loading