クイックスタート:Next.js
App Routerを使うNext.jsアプリにサインインを追加します。@usher/nextjs SDKは提供予定です。それまでの間、このガイドでは標準のOpenID Connectフローを使います。これはまさに、SDKが代わりに行うことそのものです。
始める前に
- App Routerを使う、Next.js 15または16のアプリ。
- Usherの環境。Usher Consoleでプロジェクトを開いて環境を選び、その発行者を控えておきます。
アプリを登録する
Consoleでアプリケーションに移動し、Webアプリケーションを作成します。次のリダイレクトURIを、このとおりに追加してください。
http://localhost:3000/auth/callbackクライアントIDとクライアントシークレットをコピーします。シークレットが表示されるのは一度だけです。
環境変数を追加する
.env.local
USHER_ISSUER=https://acme.usherid.com
USHER_CLIENT_ID=your_client_id
USHER_CLIENT_SECRET=your_client_secret
APP_URL=http://localhost:3000OpenID Connectクライアントをインストールする
認定済みのクライアントなら、どれでも使えます。このガイドでは、ディスカバリ、PKCE、トークンの検証を扱うopenid-clientを使います。
ターミナル
pnpm add openid-client発行者をディスカバリする
ディスカバリでは、発行者のエンドポイントと鍵を一度だけ読み込むため、何もハードコードする必要がありません。
lib/usher.ts
import * as client from 'openid-client'
let config: Promise<client.Configuration> | undefined
export function usher() {
config ??= client.discovery(
new URL(process.env.USHER_ISSUER!),
process.env.USHER_CLIENT_ID!,
process.env.USHER_CLIENT_SECRET!,
)
return config
}
export const redirectUri = `${process.env.APP_URL}/auth/callback`ユーザーをLobbyへ送る
ルートハンドラーがPKCEベリファイアとstate値を作り、有効期間の短いCookieに保存してから、Lobbyへリダイレクトします。
app/auth/sign-in/route.ts
import * as client from 'openid-client'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { redirectUri, usher } from '@/lib/usher'
export async function GET() {
const config = await usher()
const codeVerifier = client.randomPKCECodeVerifier()
const state = client.randomState()
const jar = await cookies()
jar.set('usher_flow', JSON.stringify({ codeVerifier, state }), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/auth',
maxAge: 600,
})
const url = client.buildAuthorizationUrl(config, {
redirect_uri: redirectUri,
scope: 'openid profile email offline_access',
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
code_challenge_method: 'S256',
state,
})
redirect(url.href)
}コールバックを処理する
Usherは、コードを付けてユーザーを送り返します。それをトークンと交換してください。state、PKCEベリファイア、IDトークンの署名は、openid-clientが確認します。
app/auth/callback/route.ts
import * as client from 'openid-client'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { usher } from '@/lib/usher'
export async function GET(request: Request) {
const config = await usher()
const jar = await cookies()
const flow = JSON.parse(jar.get('usher_flow')?.value ?? '{}')
jar.delete('usher_flow')
const tokens = await client.authorizationCodeGrant(config, new URL(request.url), {
pkceCodeVerifier: flow.codeVerifier,
expectedState: flow.state,
})
const claims = tokens.claims()! // sub, email, name, …
// start your own session here: store claims.sub, and keep the refresh token server-side
redirect('/')
}サインアウト
アプリでユーザーのセッションを終了し、続いてUsherのend-sessionエンドポイントへ送ります。こうすることで、Lobbyもそのユーザーのことを忘れます。
app/auth/sign-out/route.ts
import * as client from 'openid-client'
import { redirect } from 'next/navigation'
import { usher } from '@/lib/usher'
export async function GET() {
const config = await usher()
// clear your own session first
const url = client.buildEndSessionUrl(config, {
post_logout_redirect_uri: process.env.APP_URL!,
})
redirect(url.href)
}SDKを使う場合
@usher/nextjsが公開されると、同じアプリは次のようになります。以下のプレビューは、リリース前に変更される可能性があります。
app/layout.tsx · app/page.tsx(プレビュー)
// app/layout.tsx
import { UsherProvider } from '@usher/nextjs'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<UsherProvider>{children}</UsherProvider>
</body>
</html>
)
}
// app/page.tsx
import { SignIn, UserButton, currentUser } from '@usher/nextjs'
export default async function Page() {
const user = await currentUser()
return user ? <UserButton /> : <SignIn />
}