コンテンツにスキップ
NextAuth.js v4 からの移行ですか?以下をお読みください 移行ガイド.

@auth/express

⚠️

@auth/express は現在実験段階です。API は将来変更される可能性があります。

Express Auth は Auth.js の公式 Express 統合です。数行のコードで Express アプリに認証を追加する簡単な方法を提供します。

インストール

npm install @auth/express

使い方

src/routes/auth.route.ts
import { ExpressAuth } from "@auth/express"
import GitHub from "@auth/express/providers/github"
import express from "express"
 
const app = express()
 
// If app is served through a proxy, trust the proxy to allow HTTPS protocol to be detected
// https://express.dokyumento.jp/en/guide/behind-proxies.html
app.set('trust proxy', true)
app.use("/auth/*", ExpressAuth({ providers: [ GitHub ] }))

AUTH_SECRET 環境変数を設定することを忘れないでください。これは、少なくとも 32 文字のランダムな文字列である必要があります。UNIX システムでは、openssl rand -hex 32 を使用するか、https://generate-secret.vercel.app/32 を確認してください。

また、実行時環境に環境変数をロードする必要があります。たとえば、Node.js では dotenv のようなパッケージを使用するか、Deno では Deno.env を使用します。

プロバイダー設定

プロバイダーで使用されるコールバック URL は、ExpressAuth ハンドラーを別のパスにマウントしない限り、次のように設定する必要があります

[origin]/auth/callback/[provider]

サインインとサインアウト

アプリケーションがマウントされたら、クライアント側のコードから次の REST API エンドポイントにリクエストを送信することでサインインまたはサインアウトできます。注意:すべてのサインインおよびサインアウトのリクエストの要求本文に csrfToken を含めるようにしてください。

セッションの管理

テンプレート エンジン (例: EJS、Pug) で Express を使用している場合は、次のようにミドルウェアを介してすべてのルートでセッション データを利用できるようにできます

app.ts
import { getSession } from "@auth/express"
 
export function authSession(req: Request, res: Response, next: NextFunction) {
  res.locals.session = await getSession(req)
  next()
}
 
app.use(authSession)
 
// Now in your route
app.get("/", (req, res) => {
  const { session } = res.locals
  res.render("index", { user: session?.user })
})

認証

セッションの存在を確認し、セッションが存在しない場合はログインページにリダイレクトすることで、ルートを保護できます。これは、ルートごとに行うことも、次のミドルウェアのようなミドルウェアを使用してルートのグループごとに行うこともできます

export async function authenticatedUser(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const session = res.locals.session ?? (await getSession(req, authConfig))
  if (!session?.user) {
    res.redirect("/login")
  } else {
    next()
  }
}

ルートごと

単一のルートを保護するには、次のようにミドルウェアをルートに追加するだけです

app.ts
// This route is protected
app.get("/profile", authenticatedUser, (req, res) => {
  const { session } = res.locals
  res.render("profile", { user: session?.user })
})
 
// This route is not protected
app.get("/", (req, res) => {
  res.render("index")
})
 
app.use("/", root)

ルートのグループごと

ルートのグループを保護するには、ルーターを定義し、次のようにミドルウェアをルーターに追加します

routes/protected.route.ts
import { Router } from "express"
 
const router = Router()
 
router.use(authenticatedUser) // All routes defined after this will be protected
 
router.get("/", (req, res) => {
  res.render("protected")
})
 
export default router

次に、次のようにルーターをマウントします

app.ts
import protected from "./routes/protected.route"
 
app.use("/protected", protected)

ESMに関する注意

@auth/express は ESM のみです。これは、package.json に "type": "module" が含まれている必要があり、tsconfig.json に "module": "NodeNext" または ESNext が含まれている必要があることを意味します。ファイルインポートでは、.js 拡張子を使用する必要があります。例:import { MyRouter } from "./my-router.js"

開発サーバーは、tsx を使用して tsx index.ts (高速起動、型チェックなし) で実行するか、ts-node を使用して ‘node —loader ts-node/esm index.ts’ (起動は遅いが型チェックあり) で実行する必要があります。

お勧めはしませんが、上記を変更せずに CommonJS プロジェクト内で @auth/express を使用したい場合は、tsx で開発サーバーを実行し、pkgroll でコンパイルできる場合があります。package.json に ‘“name”: ”./dist/index.js”’ または ‘“name”: ”./dist/index.mjs”’ を追加し、’pkgroll’ を実行して ESM と CommonJS の両方のサポートでコンパイルします。新しいプロジェクトでは、ESM を使用することをお勧めします。

AuthError

すべての Auth.js エラーの基本エラークラス。logger.error オプションを介して、サーバーログに適切にフォーマットされて出力されるように最適化されています。

拡張

コンストラクター

new AuthError(message, errorOptions)

new AuthError(message?, errorOptions?): AuthError
パラメーター
パラメーター
message?string | ErrorOptions
errorOptions?ErrorOptions
戻り値

AuthError

オーバーライド

Error.constructor

プロパティ

cause?

optional cause: Record<string, unknown> & {
  err: Error;
};
型宣言
err?
optional err: Error;
オーバーライド

Error.cause

message

message: string;
継承元

Error.message

name

name: string;
継承元

Error.name

stack?

optional stack: string;
継承元

Error.stack

type

type: ErrorType;

ログでエラーを識別するために使用されるエラーの種類。

prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any;

スタックトレースをフォーマットするためのオプションのオーバーライド

参照

https://v8.dokyumento.jp/docs/stack-trace-api#customizing-stack-traces

パラメーター
パラメーター
errError
stackTracesCallSite[]
戻り値

any

継承元

Error.prepareStackTrace

stackTraceLimit

static stackTraceLimit: number;
継承元

Error.stackTraceLimit

メソッド

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

ターゲットオブジェクトに .stack プロパティを作成します

パラメーター
パラメーター
targetObjectobject
constructorOpt?Function
戻り値

void

継承元

Error.captureStackTrace


CredentialsSignin

Credentialsプロバイダーのauthorizeコールバックからスローできます。authorizeコールバック中にエラーが発生すると、次の2つのことが起こります。

  1. ユーザーはサインインページにリダイレクトされ、URLにerror=CredentialsSignin&code=credentialsが含まれます。codeは設定可能です。
  2. フォームアクションをサーバー側で処理するフレームワークでこのエラーをスローすると、ユーザーをリダイレクトする代わりに、このエラーがスローされるため、処理する必要があります。

拡張

コンストラクター

new CredentialsSignin(message, errorOptions)

new CredentialsSignin(message?, errorOptions?): CredentialsSignin
パラメーター
パラメーター
message?string | ErrorOptions
errorOptions?ErrorOptions
戻り値

CredentialsSignin

継承元

SignInError.constructor

プロパティ

cause?

optional cause: Record<string, unknown> & {
  err: Error;
};
型宣言
err?
optional err: Error;
継承元

SignInError.cause

code

code: string;

codeリダイレクトURLのクエリパラメータに設定されているエラーコード。

⚠ 注意: このプロパティはURLに含まれるため、機密性の高いエラーを示唆しないようにしてください。

デバッグが必要な場合、完全なエラーは常にサーバーにログされます。

一般的に、ユーザーが間違ったユーザー名またはパスワードを具体的に使用した場合を示すことはお勧めしません。「無効な資格情報」のようなものを試してください。

message

message: string;
継承元

SignInError.message

name

name: string;
継承元

SignInError.name

stack?

optional stack: string;
継承元

SignInError.stack

type

type: ErrorType;

ログでエラーを識別するために使用されるエラーの種類。

継承元

SignInError.type

kind

static kind: string;
継承元

SignInError.kind

prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any;

スタックトレースをフォーマットするためのオプションのオーバーライド

参照

https://v8.dokyumento.jp/docs/stack-trace-api#customizing-stack-traces

パラメーター
パラメーター
errError
stackTracesCallSite[]
戻り値

any

継承元

SignInError.prepareStackTrace

stackTraceLimit

static stackTraceLimit: number;
継承元

SignInError.stackTraceLimit

type

static type: string;

メソッド

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

ターゲットオブジェクトに .stack プロパティを作成します

パラメーター
パラメーター
targetObjectobject
constructorOpt?Function
戻り値

void

継承元

SignInError.captureStackTrace


アカウント

通常、使用されているプロバイダーに関する情報が含まれており、OAuthプロバイダーから返されるさまざまなトークンであるTokenSetも拡張します。

拡張

プロパティ

access_token?

optional readonly access_token: string;
継承元

Partial.access_token

authorization_details?

optional readonly authorization_details: AuthorizationDetails[];
継承元

Partial.authorization_details

expires_at?

optional expires_at: number;

TokenEndpointResponse.expires_inに基づく計算値。

これは、TokenEndpointResponse.access_tokenの有効期限が切れる絶対タイムスタンプ(秒単位)です。

この値は、TokenEndpointResponse.refresh_tokenと組み合わせてトークンローテーションを実装するために使用できます。

参照

expires_in?

optional readonly expires_in: number;
継承元

Partial.expires_in

id_token?

optional readonly id_token: string;
継承元

Partial.id_token

プロバイダー

provider: string;

このアカウントのプロバイダーのID。例: "google"。完全なリストはhttps://authjs.dokyumento.jp/reference/core/providers を参照してください。

providerAccountId

providerAccountId: string;

この値は、アカウント作成に使用されるプロバイダーのタイプによって異なります。

  • oauth/oidc: OAuthアカウントのID。 profile() コールバックから返されます。
  • email: ユーザーのメールアドレス。
  • credentials: authorize() コールバックから返される id

refresh_token?

optional readonly refresh_token: string;
継承元

Partial.refresh_token

scope?

optional readonly scope: string;
継承元

Partial.scope

token_type?

optional readonly token_type: Lowercase<string>;

注意: 値は大文字と小文字を区別しないため、常に小文字で返されます

継承元

Partial.token_type

type

type: ProviderType;

このアカウントのプロバイダーのタイプ

userId?

optional userId: string;

このアカウントが属するユーザーのID

参照

https://authjs.dokyumento.jp/reference/core/adapters#adapteruser


DefaultSession

拡張元

プロパティ

expires

expires: string;

user?

optional user: User;

Profile

OAuthプロバイダーから返されるユーザー情報。

参照

https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims

インデックス可能

[claim: string]: unknown

プロパティ

address?

optional address: null | {
  country: null | string;
  formatted: null | string;
  locality: null | string;
  postal_code: null | string;
  region: null | string;
  street_address: null | string;
};

birthdate?

optional birthdate: null | string;

email?

optional email: null | string;

email_verified?

optional email_verified: null | boolean;

family_name?

optional family_name: null | string;

gender?

optional gender: null | string;

given_name?

optional given_name: null | string;

id?

optional id: null | string;

locale?

optional locale: null | string;

middle_name?

optional middle_name: null | string;

name?

optional name: null | string;

nickname?

optional nickname: null | string;

phone_number?

optional phone_number: null | string;

picture?

optional picture: any;

preferred_username?

optional preferred_username: null | string;

profile?

optional profile: null | string;

sub?

optional sub: null | string;

updated_at?

optional updated_at: null | string | number | Date;

website?

optional website: null | string;

zoneinfo?

optional zoneinfo: null | string;

セッション

ログインしているユーザーのアクティブなセッション。

拡張

プロパティ

expires

expires: string;
継承元

DefaultSession.expires

user?

optional user: User;
継承元

DefaultSession.user


ユーザー

OAuthプロバイダーの profile コールバックで返されるオブジェクトの形状。データベースを使用している場合は、jwt および session コールバック、または session コールバックの2番目のパラメーターで利用可能です。

拡張元

プロパティ

email?

optional email: null | string;

id?

optional id: string;

image?

optional image: null | string;

name?

optional name: null | string;

ExpressAuthConfig

type ExpressAuthConfig: Omit<AuthConfig, "raw">;

GetSessionResult

type GetSessionResult: Promise<Session | null>;

customFetch

const customFetch: unique symbol;
🚫

このオプションを使用すると、プロバイダーがプロバイダーのOAuthエンドポイントに直接リクエストを行うために使用するデフォルトの fetch 関数をオーバーライドできます。誤って使用すると、セキュリティ上の影響が生じる可能性があります。

これは、企業プロキシ、カスタムfetchライブラリのサポート、キャッシュディスカバリーエンドポイント、テスト用のモックの追加、ログ記録、仕様に準拠していないプロバイダー用のカスタムヘッダー/パラメーターの設定などに使用できます。

import { Auth, customFetch } from "@auth/core"
import GitHub from "@auth/core/providers/github"
 
const dispatcher = new ProxyAgent("my.proxy.server")
function proxy(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {
  return undici(args[0], { ...(args[1] ?? {}), dispatcher })
}
 
const response = await Auth(request, {
  providers: [GitHub({ [customFetch]: proxy })]
})

参照


ExpressAuth()

ExpressAuth(config): (req, res, next) => Promise<void>

パラメーター

パラメーター
configExpressAuthConfig

戻り値

Function

パラメーター

パラメーター
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>
nextNextFunction

戻り値

Promise<void>


getSession()

getSession(req, config): GetSessionResult

パラメーター

パラメーター
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
configExpressAuthConfig

戻り値

GetSessionResult

Auth.js © Balázs Orbán and Team -2024