最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to resolve next-auth untrusted host error? - Stack Overflow

programmeradmin0浏览0评论

PM2 logs

I have a nextjs app that i deployed on hostinger vps using nginx reverse proxy (client request), i used next auth to setup the authentication for the dashboard, in local environment everything works perfect but in production when I am trying to log in I am getting untrusted host error but I have set the environment variables correctly and set the trusthost to true as well despite all I am still getting this error and not able to fix it. Kindly help

set environment variables to domain name through which I am accessing set trusthost to true in auth config.

I am using next-auth 5.0.0.25 beta

//Auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
import CredentialsProvider from "next-auth/providers/credentials"
import bcrypt from "bcryptjs"

const prisma = new PrismaClient()

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  pages: {
    signIn: "/login",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id
      }
      return token
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id as string
      }
      return session
    },
    async redirect({ url, baseUrl }) {
      const deployedBaseUrl = process.env.NEXTAUTH_URL || baseUrl;
      if (url.startsWith("/")) return `${deployedBaseUrl}${url}`
      else if (new URL(url).origin === deployedBaseUrl) return url
      return deployedBaseUrl
    },
    async authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isCMSRoute = nextUrl.pathname.startsWith('/CMS')
      
      if (isCMSRoute) {
        if (isLoggedIn) return true
        return false 
      }
      return true
    },
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          return null
        }

        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email
          }
        })

        if (!user) {
          return null
        }

        const isPasswordValid = await bcryptpare(
          credentials.password,
          user.password
        )

        if (!isPasswordValid) {
          return null
        }

        return {
          id: user.id,
          email: user.email,
        }
      }
    })
  ],
  session: {
    strategy: "jwt"
  },
  trustHost: true,
})

//Actions.ts
'use server'

import { AuthError } from 'next-auth'
import { signIn } from '@/auth'
import { redirect } from 'next/navigation'

export async function authenticate(
  prevState: string | undefined,
  formData: FormData,
) {
  try {
    const result = await signIn('credentials', {
      email: formData.get('email'),
      password: formData.get('password'),
      redirect: false,
    })

    if (!result?.error) {
      // Use the deployed URL for redirection
      redirect(`${process.env.NEXTAUTH_URL}/CMS`)
    }

    return 'Invalid credentials.'
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          return 'Invalid credentials.'
        default:
          return 'Something went wrong.'
      }
    }
    throw error
  }
}

PM2 logs

I have a nextjs app that i deployed on hostinger vps using nginx reverse proxy (client request), i used next auth to setup the authentication for the dashboard, in local environment everything works perfect but in production when I am trying to log in I am getting untrusted host error but I have set the environment variables correctly and set the trusthost to true as well despite all I am still getting this error and not able to fix it. Kindly help

set environment variables to domain name through which I am accessing set trusthost to true in auth config.

I am using next-auth 5.0.0.25 beta

//Auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
import CredentialsProvider from "next-auth/providers/credentials"
import bcrypt from "bcryptjs"

const prisma = new PrismaClient()

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  pages: {
    signIn: "/login",
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id
      }
      return token
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id as string
      }
      return session
    },
    async redirect({ url, baseUrl }) {
      const deployedBaseUrl = process.env.NEXTAUTH_URL || baseUrl;
      if (url.startsWith("/")) return `${deployedBaseUrl}${url}`
      else if (new URL(url).origin === deployedBaseUrl) return url
      return deployedBaseUrl
    },
    async authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user
      const isCMSRoute = nextUrl.pathname.startsWith('/CMS')
      
      if (isCMSRoute) {
        if (isLoggedIn) return true
        return false 
      }
      return true
    },
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          return null
        }

        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email
          }
        })

        if (!user) {
          return null
        }

        const isPasswordValid = await bcryptpare(
          credentials.password,
          user.password
        )

        if (!isPasswordValid) {
          return null
        }

        return {
          id: user.id,
          email: user.email,
        }
      }
    })
  ],
  session: {
    strategy: "jwt"
  },
  trustHost: true,
})

//Actions.ts
'use server'

import { AuthError } from 'next-auth'
import { signIn } from '@/auth'
import { redirect } from 'next/navigation'

export async function authenticate(
  prevState: string | undefined,
  formData: FormData,
) {
  try {
    const result = await signIn('credentials', {
      email: formData.get('email'),
      password: formData.get('password'),
      redirect: false,
    })

    if (!result?.error) {
      // Use the deployed URL for redirection
      redirect(`${process.env.NEXTAUTH_URL}/CMS`)
    }

    return 'Invalid credentials.'
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          return 'Invalid credentials.'
        default:
          return 'Something went wrong.'
      }
    }
    throw error
  }
}

Share Improve this question asked Jan 18 at 10:28 kunal srivastavakunal srivastava 11 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

If your application is behind a reverse proxy (it is in your situation), you need to set AUTH_TRUST_HOST as true.

Do not fet to set your AUTH_SECRET as well.

I advise you to read Deployment section carefully

https://authjs.dev/getting-started/deployment

发布评论

评论列表(0)

  1. 暂无评论