You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Postman调用NextAuth的Credentials登录接口?

解决NextAuth CredentialsProvider通过Postman调用返回HTML的问题

问题原因

默认情况下,/api/auth/signin端点是用于展示登录页面的(返回HTML),直接请求它不会触发CredentialsProvider的认证逻辑。要通过API方式调用认证,需要指定对应的provider端点并使用正确的请求格式。

解决方案

1. 调整请求地址和方法

不要请求通用的/api/auth/signin,而是直接请求CredentialsProvider对应的端点:

POST http://localhost:3000/api/auth/signin/credentials

这里的credentials是你配置中CredentialsProvider的id值,必须和配置里的一致。

2. 设置正确的请求参数和头

方式一:使用JSON格式请求

  • 请求头添加:Content-Type: application/json
  • 请求Body选择raw -> JSON,传入参数(必须包含action: "signin"):
{
    "email": "myemail@email.com",
    "password": "12345678",
    "action": "signin"
}

方式二:使用表单格式请求

  • 请求头添加:Content-Type: application/x-www-form-urlencoded
  • 请求Body选择form-data或x-www-form-urlencoded,传入三个参数:
    • email: myemail@email.com
    • password: 12345678
    • action: signin

3. 调整NextAuth配置(可选,针对JSON请求优化)

默认情况下,authorize函数的credentials参数仅解析表单格式的请求。如果使用JSON格式请求,需要在authorize中从req.body获取参数,修改你的[...nextauth].js中的authorize函数:

async authorize(credentials, req) {
    // 优先从req.body取JSON参数,兼容表单参数
    const { email, password } = req.body || credentials;
    try {   
        const user = await prisma.user.findFirst({
            where: {
                email: email
            }
        });

        if (user !== null) {
            const res = await confirmPasswordHash(password, user.password);
            if (res === true) {
                return user;
            } else {
                console.log("Hash not matched logging in");
                return null;
            }
        } else {
            return null;
        }
    } catch (err) {
        console.log("Authorize error:", err);
    }
}

4. 验证响应

请求成功后,你会收到包含用户信息的JSON响应,同时响应头会包含Set-Cookie字段(用于后续请求的会话验证)。如果认证失败,会返回对应的错误JSON或状态码。

内容的提问来源于stack exchange,提问作者Boby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:48:18