Skip to content

Commit

Permalink
feat: add passport guide (#756)
Browse files Browse the repository at this point in the history
  • Loading branch information
wangsijie authored Aug 9, 2024
1 parent b5187f2 commit 625c5c1
Show file tree
Hide file tree
Showing 7 changed files with 204 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/quick-starts/framework/passport/README.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
slug: /quick-starts/passport
sidebar_label: Passport.js
sidebar_custom_props:
logoFilename: 'passport.svg'
description: Passport is authentication middleware for Node.js.
---

import FurtherReadings from '../../fragments/_further-readings.md';

import GuideTip from './_guide-tip.mdx';
import Installation from './_installation.mdx';
import Integration from './_integration.mdx';
import ScopesAndClaims from './_scopes-and-claims.mdx';

# Passport.js guide

This guide will show you how to integrate Logto into your application with [Passport.js](https://www.passportjs.org/) and OIDC strategy.

<GuideTip />

## Prerequisites

- A [Logto Cloud](https://cloud.logto.io) account or a self-hosted Logto (Check out the [⚡ Get started](../../../docs/get-started/) guide to create one if you don't have).
- A Logto traditional application created.
- An express project with session configured. Check out the [Express.js website](https://expressjs.com/).

## Installation

<Installation />

## Integration

<Integration />

## Scopes and claims

<ScopesAndClaims />

## Further readings

<FurtherReadings />
5 changes: 5 additions & 0 deletions docs/quick-starts/framework/passport/_guide-tip.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
:::tip

- In this guide, we assume you have set up Express with session in you project. If you haven't, check out the [Express.js website](https://expressjs.com/) to get started.

:::
3 changes: 3 additions & 0 deletions docs/quick-starts/framework/passport/_installation.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import NpmLikeInstallation from '../../fragments/_npm-like-installation.mdx';

<NpmLikeInstallation packageName="passport passport-openidconnect" />
109 changes: 109 additions & 0 deletions docs/quick-starts/framework/passport/_integration.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import Checkpoint from '../../fragments/_checkpoint-test-your-application.md';
import AssumingUrl from '../../fragments/_web-assuming-url.mdx';
import WebConfigureRedirectUris from '../../fragments/_web-configure-redirect-uris.mdx';
import SignInFlowSummary from '../../fragments/_web-sign-in-flow-summary.mdx';

### Initialize Passport.js with OIDC strategy

```ts title="passport.ts"
import passport from 'passport';
import OpenIDConnectStrategy, { type Profile, type VerifyCallback } from 'passport-openidconnect';

const endpoint = '<your-logto-endpoint>';
const appId = '<your-application-id>';
const appSecret = '<your-application-secret>';

export default function initPassport() {
passport.use(
new OpenIDConnectStrategy(
{
issuer: `${endpoint}/oidc`,
authorizationURL: `${endpoint}/oidc/auth`,
tokenURL: `${endpoint}/oidc/token`,
userInfoURL: `${endpoint}/oidc/me`,
clientID: appId,
clientSecret: appSecret,
callbackURL: '/callback',
scope: ['profile', 'offline_access'],
},
(issuer: string, profile: Profile, callback: VerifyCallback) => {
callback(null, profile);
}
)
);

passport.serializeUser((user, callback) => {
callback(null, user);
});

passport.deserializeUser(function (user, callback) {
callback(null, user as Express.User);
});
}
```

This code initializes Passport with the **`OpenIDConnectStrategy`**. The serialize and deserialize methods are set for demonstration purposes.

Ensure to initialize and attach Passport middleware in your application:

```tsx title="your-app-entry.ts"
import initPassport from './passport';

// ... other code
initPassport();
// ... other code
app.use(passport.authenticate('session'));
// ... other code
```

### Configure redirect URIs

<SignInFlowSummary />

<AssumingUrl />

<WebConfigureRedirectUris />

### Implement sign-in and sign-out

We'll now create specific routes for authentication processes:

```tsx title="your-app-entry.ts"
app.get('/sign-in', passport.authenticate('openidconnect'));
app.get(
'/callback',
passport.authenticate('openidconnect', {
successReturnToOrRedirect: '/',
})
);
app.get('/sign-out', (request, response, next) => {
request.logout((error) => {
if (error) {
next(error);
return;
}
response.redirect(`${endpoint}/oidc/session/end?client_id=${appId}`);
});
});
```

Then add to the homepage

```tsx title="your-app-entry.ts"
app.get('/', (request: Request, response) => {
const { user } = request;
response.setHeader('content-type', 'text/html');

if (user) {
response.end(
`<h1>Hello Logto</h1><p>Signed in as ${JSON.stringify(
user
)}, <a href="/sign-out">Sign Out</a></p>`
);
} else {
response.end(`<h1>Hello Logto</h1><p><a href="/sign-in">Sign In</a></p>`);
}
});
```

<Checkpoint />
19 changes: 19 additions & 0 deletions docs/quick-starts/framework/passport/_scopes-and-claims-code.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
```ts
export default function initPassport() {
passport.use(
new OpenIDConnectStrategy(
{
// ... other options
clientID: appId,
clientSecret: appSecret,
callbackURL: '/callback',
// highlight-start
scope: ['openid', 'offline_access', 'profile', 'email'],
// highlight-end
}
// ... other options
)
);
// ... other options
}
```
5 changes: 5 additions & 0 deletions docs/quick-starts/framework/passport/_scopes-and-claims.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import ScopesAndClaims from '../../fragments/_scopes-and-claims.mdx';

import ScopesAndClaimsCode from './_scopes-and-claims-code.md';

<ScopesAndClaims configScopesCode={<ScopesAndClaimsCode />} />
21 changes: 21 additions & 0 deletions static/img/logo/passport.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 625c5c1

Please sign in to comment.