0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NextAuth v5でGitHub認証をCloudRun上でやるときの注意

Posted at

やりたいこと

Cloud Runにデプロイしているアプリケーションで、NextAuthを使ってGitHubアカウントで認証したい。

前提

  • Nextでアプリを構築している
  • NextAuthのインストール・セットアップ済み
    • NextAuthはv5のベータ版
  • ローカルでNextAuthによるGitHubアカウント認証が実装できている
  • Dockerを使ってCloud Runにアプリケーションを展開済み

設定済みの環境変数

  • AUTH_SECRET
    • openssl rand -base64 33の値を設定
  • AUTH_GITHUB_ID
  • AUTH_GITHUB_SECRET
    • GitHub Appsで生成したID・キー値を設定

詰まったこと1

デプロイはできたのに、サーバーエラーでアプリケーションが開けない。

[0m UntrustedHost: Host must be trusted. URL was: https://{公開先オリジン}/api/auth/session. Read more at https://errors.authjs.dev#untrustedhost

解決

こちらの記事を参考に、Trust Hostを有効にしました。
https://zenn.dev/nbstsh/scraps/336b9865cd8765

/src/app/lib/auth.ts
export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: providers,
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {...},
  trustHost: true,  // <----ここを追加
})

詰まったこと2

GitHub認証の許可ページまで行って、許可したと思ったらエラー

ログを見たら次のようなエラーに。

[31m[auth][error][0m CallbackRouteError: Read more at https://errors.authjs.dev#callbackrouteerror

ちなみにこの直前のログではGitHubからのコールバックが記録されていた。

https://{OriginURI}/api/auth/callback/github?code=XXXXXXXXXXX

また、詳しいログが下記のように記録されていた。

{
    "body": {
        "error": "redirect_uri_mismatch",
        "error_description": "The redirect_uri MUST match the registered callback URL for this application.",
        "error_uri": "https://docs.github.com/apps/managing-oauth-apps/troubleshooting-authorization-request-errors/#redirect-uri-mismatch2"
    },
    "provider": "github"
}

なんとなく理解したエラーの仕組み

  1. /auth/signinにアクセス
  2. GitHubにリダイレクト
  3. GitHubアカウントで認可されたら/api/auth/callback/github?code=XXXへコールバック
  4. するとなぜかhttps://0.0.0.0:3000/api/authへリダイレクト ← ????
  5. うまくいかないよエラーに

ちなみになぜhttps://0.0.0.0:3000/になるかは、Docker Fileの記述っぽい。
公式ドキュメントのDeploy設定 → https://authjs.dev/getting-started/deployment

EXPOSE 3000
 
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

いろいろ見てみたが、このDockerファイルの設定は問題ない。

暫定解決

公式ドキュメントの環境変数をCloudRun側にきちんと設定してあげる。
https://authjs.dev/getting-started/deployment#environment-variables

基本は設定いらないと書いてあるAUTH_URLを設定。
ついでに、(前項で解決していたけど)AUTH_TRUST_HOSTも設定。

スクリーンショット 2025-09-24 12.13.53.png

まとめ

おそらく、他の認証方法(Googleなど)でもこの問題は発生しそうなので、環境変数の設定で解決してください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?