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

Next.js+Azure SQL仅Entra认证登录失败问题求助

解决Next.js连接Azure SQL(仅Entra认证)时的空用户登录失败问题

针对你遇到的ConnectionError: Login failed for user ' '错误,以下是针对性的排查和修复步骤:

1. 补充依赖包并修正连接配置

mssql的azure-active-directory-default认证方式在Node.js环境下依赖@azure/identity包来获取凭证,首先安装该依赖:

npm install @azure/identity

然后修改db.js的配置,显式指定凭证获取逻辑,避免自动检测的不确定性:

const sql = require("mssql");
const { DefaultAzureCredential } = require("@azure/identity");

const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT) || 1433;
const authenticationType = "azure-active-directory-default";

const config = {
  server,
  port,
  database,
  authentication: {
    authenticationType,
    options: {
      // 显式使用DefaultAzureCredential,覆盖自动检测逻辑
      credential: new DefaultAzureCredential()
    }
  },
  options: {
    encrypt: true,
  },
};

const pool = new sql.ConnectionPool(config);

async function connect() {
  try {
    // 打印环境变量值,排查配置是否正确加载
    console.log("Server:", server, "Database:", database, "Port:", port);
    await pool.connect();
    console.log("Connected to SQL Server!");
    return pool;
  } catch (err) {
    console.error("Error connecting to SQL Server:", err);
    console.log("Auth Type: ", authenticationType);
    throw err;
  }
}

module.exports = {
  connect,
  pool,
};

2. 本地开发环境的身份验证上下文检查

  • 确保你已通过Azure CLI登录拥有Azure SQL访问权限的账号:
    az login
    
    运行az account show确认当前登录账号,同时要将该账号添加到Azure SQL的Entra身份列表中,并授予db_datareader/db_datawriter权限。

3. Azure Web App生产环境的托管标识配置

  • 在Azure Portal中打开你的Web App,进入身份 -> 系统分配,将状态设为开启,保存后复制生成的Object ID。
  • 在Azure SQL的查询编辑器中执行以下SQL,为Web App的托管标识分配数据库权限:
    CREATE USER [你的Web App名称] FROM EXTERNAL PROVIDER;
    ALTER ROLE db_datareader ADD MEMBER [你的Web App名称];
    ALTER ROLE db_datawriter ADD MEMBER [你的Web App名称];
    
  • 确保Web App的应用设置中没有配置传统的SQL用户名/密码环境变量,避免干扰Entra认证流程。

4. 环境变量有效性验证

  • 确认AZURE_SQL_SERVER的格式为xxx.database.windows.net,无多余前缀或后缀。
  • 本地开发时,检查.env.local文件中的变量是否拼写正确,重启Next.js开发服务器确保变量加载生效;生产环境则在Web App的配置 -> 应用设置中确认所有AZURE_SQL_*变量值正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:01:11