简体   繁体   English

自定义登录表单错误:使用 CredentialsProvider 重定向到 https://localhost:3000/api/auth/signin?csrf=true

[英]Custom Login Form Error : Redirecting to https://localhost:3000/api/auth/signin?csrf=true using CredentialsProvider

DESCRIPTION: I'm facing while implementing custom login form in my nextjs site using next-auth.描述:我在使用 next-auth 在我的 nextjs 站点中实现自定义登录表单时遇到了问题。 It keeps on redirecting to "https://localhost:3000/api/auth/signin?csrf=true"它不断重定向到“https://localhost:3000/api/auth/signin?csrf=true”

SERVER SIDE CODE WRITTEN IN "[...nextauth.js]" FILE INSIDE "pages/api/auth/" folder.在“pages/api/auth/”文件夹内的“[...nextauth.js]”文件中写入的服务器端代码。

    import NextAuth from 'next-auth';
    import CredentialsProvider from 'next-auth/providers/credentials';
    
    const providers = [
        CredentialsProvider({
            id: 'credentials',
            name: 'credentials',
            authorize: async (credentials) => {
                console.log("AUTHORIZING...",credentials,req);
                const res = await fetch(process.env.apiURL+"api/users/authenticate", {
                    method: 'POST',
                    body: JSON.stringify(credentials),
                    headers: { "Content-Type": "application/json" }
                });
                const user = await res.json();
                if (res.ok && user) {
                    return user;
                }
                return null;
            }
        }),
    ];
    
    const callbacks = {
        async signIn({ user, account, profile, email, credentials }) {
            console.log("IN CALLBACK HERE!!!");
            const isAllowedToSignIn = true
            if (isAllowedToSignIn) {
              return true
            } else {
              return false
            }
        },
        async redirect({ url, baseUrl }) {
            return baseUrl;
        },
        async session(session, token) {
          console.log("IN THE CALLBACK SESSION NOW");
          session.accessToken = token.accessToken
          return session
        }
    }
    
    const options = {
        providers,
        callbacks,
        secret: process.env.JWT_SECRET,
        pages: {
            signIn: '/my-account',
            signUp: '/signup',
            error: '/my-account'
        },
        debug: true
    }

export default (req, res) => NextAuth(req, res, options);

MY CUSTOM LOGIN FORM'S SUBMIT BUTTON ACTION:我的自定义登录表单的提交按钮操作:

const res = await signIn('credentials', { redirect: false, username: user.username, passw: user.passw, callbackUrl: `${window.location.origin}` });
            console.log(res);
            if (res?.error) {
                console.error(res.error);
            }
            if (res.url) router.push(res.url);

ENVIRONMENT VARIABLES环境变量

NEXTAUTH_URL=https://localhost:3000/api/auth
NEXTAUTH_SECRET=PETSFINEST

ERROR IS the Authorize function of Credentials Provider is not at all being called.. as soon as I press SIGNIN button from my custom login form, it simply redirects to "https://localhost:3000/api/auth/signin?csrf=true" URL and thats it.错误是凭证提供程序的授权 function 根本没有被调用。当我从我的自定义登录表单中按下 SIGNIN 按钮时,它只是重定向到“https://localhost:3000/api/auth/signin?csrf=真”URL 就是这样。

Please help guys.. what am I doing wrong here?请大家帮忙..我在这里做错了什么? There's no other details available anywhere, and I've followed the documentation provided on next-auth site.在任何地方都没有其他详细信息,我已经按照 next-auth 站点上提供的文档进行操作。

Hey try changing to http on the NEXTAUTH_URL env variable So change this:嘿,尝试在NEXTAUTH_URL变量上更改为http所以改变这个:

    NEXTAUTH_URL=https://localhost:3000/api/auth

into进入

    NEXTAUTH_URL=http://localhost:3000/api/auth

Open the browser inspect tools and check the network tab.打开浏览器检查工具并检查网络选项卡。 Pay attention to the payload on the submit.注意提交时的有效载荷。 You should have csrfToken showing a value.您应该让 csrfToken 显示一个值。 Check that email, password and csrf are present in the payload.检查有效载荷中是否存在 email、密码和 csrf。 This helped me solve my issue similar to this when implementing passwordless email form.这帮助我在实现无密码 email 表单时解决了与此类似的问题。 Here is my custom signin...这是我的自定义登录...

import React from 'react'
import {getProviders, signIn} from 'next-auth/react'
import { getCsrfToken } from "next-auth/react"
import styles from '../../styles/signin.module.css'
import Logo from '../../components/Logo'
import Link from 'next/link'
import { GoogleLogin } from '../../components/GoogleLogin'

export default function SignIn ({ csrfToken, providers }) {
  console.log(providers.google.signinUrl);
  return (
    <div className={styles.content}>
      <div className={styles.cardWrapper}>
        <Logo className={styles.logo}/>
        <div className={styles.cardContent}>
          <form method="post" action="/api/auth/signin/email">
            <input name="csrfToken" type="hidden" defaultValue={csrfToken} />
            <input type="email" id="email" name="email" placeholder='Email..' />
            <button className={styles.primaryBtn} type="submit">Sign in with Email</button>
          </form>
          <p className={styles.seperator}> Or  </p>
          <form method="post" action="/api/auth/signin/google">
            <input name="csrfToken" type="hidden" defaultValue={csrfToken} />
            <button className={styles.primaryBtn} type="submit">Sign in with Google</button>
          </form>
        </div>
      </div>
    </div>
  )
}
export async function getServerSideProps(context) {
  const csrfToken = await getCsrfToken(context)
  const providers = await getProviders(context)
  return {
    props: { csrfToken, providers },
  }
}

I think you can do something similar for credentials as long as you have set it up correctly as per docs in [...nextauth].js.我认为只要按照 [...nextauth].js 中的文档正确设置凭据,您就可以对凭据执行类似操作。

The code above can be put into seperate components to "Reactify" the code.上面的代码可以放入单独的组件中以“Reactify”代码。

Hope this helps.希望这可以帮助。

I ran into this same issue.我遇到了同样的问题。 After banging my head against the wall for ages, it ends up https was being used because I was running it with Vercel...在把我的头撞到墙上很久之后,它最终被使用了 https,因为我正在使用 Vercel 运行它......

So rather than using vercel dev I switched it to npx next dev and it resolved the issue for me.因此,我没有使用vercel dev ,而是将其切换到npx npx next dev ,它为我解决了这个问题。

I've been having the same exact issue and banging my head against the wall for a few hours trying to debug this.我一直遇到同样的问题,并且用头撞墙几个小时试图调试它。 The problem for me was that my SMTP server string was still using the 'smtp.example.com' from the docs instead of (in my case) 'smtp.sendgrid.net'.我的问题是我的 SMTP 服务器字符串仍在使用文档中的“smtp.example.com”而不是(在我的例子中)“smtp.sendgrid.net”。

EMAIL_SERVER="smtp://<user>:<password>@smtp.example.com:587"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Next-auth signin 重定向到 /signin?csrf=true - Next-auth signin redirects to /signin?csrf=true 使用 CredentialsProvider 实现 Next Auth 登录 - implement Next Auth login with CredentialsProvider NEXT-AUTH - /api/auth/signin 上的 500 内部服务器错误,无法访问实时站点上的登录页面 - NEXT-AUTH - 500 Internal Server Error on /api/auth/signin, cannot access login page on live site CORS error when trying to redirect from http://localhost:3000 to https://api.twitter.com in Next.js using next-connect? - CORS error when trying to redirect from http://localhost:3000 to https://api.twitter.com in Next.js using next-connect? Next Auth:部署的代码在登录时将我重定向到本地主机 - Next Auth: Deployed code redirecting me to localhost on login 将请求 localhost:3000/api/product 代理到 http://localhost:5000/ 时发生错误 - Error occurred while proxying request localhost:3000/api/product to http://localhost:5000/ [next-auth][error][client_fetch_error] NextAuthJS CredentialsProvider“providers SyntaxError: JSON position 0 中的意外令牌 <” - [next-auth][error][client_fetch_error] NextAuthJS CredentialsProvider "providers SyntaxError: Unexpected token < in JSON at position 0" next-auth 自定义登录表单不将用户名和密码传递给 [...nextauth].js - next-auth custom signIn form don't pass username and password to [...nextauth].js 登录失败将我重定向到 /api/auth/error on next-auth - failed login redirects me to /api/auth/error on next-auth 使用谷歌提供商的下一个身份验证登录在表单中不起作用 - next-auth signIn with google provider is not working within form
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM