简体   繁体   English

npm mssql是否支持认证类型azure-active-directory-access-token连接azure sql服务器

[英]Does npm mssql supports authentication type azure-active-directory-access-token to connect to azure sql server

I have read that mssql module uses Tedious internally to connect to azure sql db.我读过 mssql 模块在内部使用 Tedious 连接到 azure sql db。 Hence i am trying to establish a connection using azure-active-directory-access-token.因此,我正在尝试使用 azure-active-directory-access-token 建立连接。 However, i am getting error as ConnectionError: Login failed for user token-identified principal但是,我收到错误 ConnectionError: Login failed for user token-identified principal

Sample Code:-示例代码:-

const mssql = require('mssql');
const msrestAzure = require("ms-rest-azure");

const clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
const serverName = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
const databaseName = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
const clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
const tenantId = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
let token = 0;

msrestAzure.loginWithServicePrincipalSecret(clientId,
    clientSecret,
    tenantId,
    {
        tokenAudience: "https://database.windows.net/",
    },
).then((databaseCredentials) => {
    return new Promise((resolve, reject) => {
        databaseCredentials.getToken((err, results) => {
            if (err) return reject(err);
            resolve(results.accessToken);
        });
    });
}).then((token) => {
    // console.log(token);
    var config = {
        server: serverName,
        authentication: {
            type: "azure-active-directory-access-token",
            options: {
                token: token,
            }
        },
        options: {
            database: databaseName,
            encrypt: true,
        }
    };
    return new mssql.connect(config);
}).then(pool => {
    console.log('Connected to MSSQL')
    return pool;
}).catch((error) => {
    console.log(error);
});

There is way you can use it connect Azure SQL Server using Service Principal in NodeJS(NPM) authentication by azure-active-directory-access-token.有一种方法可以使用它连接 Azure SQL 服务器,通过 azure-active-directory-access-token 在 NodeJS(NPM) 身份验证中使用服务主体。

1.Create A service principal 1.创建一个服务主体

az login
az ad sp create-for-rbac -n 'MyApp' --skip-assignment

2.Configure SQL Database 2.配置SQL数据库

a. A。 Use your Azure Sql AD admin to connect Azure SQL vai SSMS 使用您的 Azure Sql AD 管理员连接 Azure SQL vai SSMS

b. b. Add the service principal to the database you need use将服务主体添加到您需要使用的数据库中

create user [<Azure_AD_principal_name>] from external provider
ALTER ROLE db_owner ADD MEMBER [<Azure_AD_principal_name>]

3.Code 3.代码

 var msrestAzure = require("ms-rest-azure");
    var { Connection, Request } = require("tedious");
    
    let clientSecret = "xxx";
    let serverName = "xxx.database.windows.net";
    let databaseName = "xxx";
    let clientId = "xxx";
    let tenantId = "xxx";
    
    async function getConnect() {
      // way for Azure Service Principal
      let databaseCredentials = await msrestAzure.loginWithServicePrincipalSecret(
        clientId,
        clientSecret,
        tenantId,
        {
          tokenAudience: "https://database.windows.net/",
        },
      );
    
      // getting access token
      let databaseAccessToken = await new Promise((resolve, reject) => {
        databaseCredentials.getToken((err, results) => {
          if (err) return reject(err);
          resolve(results.accessToken);
        });
      });
      var config = {
        server: serverName,
        authentication: {
          type: "azure-active-directory-access-token",
          options: {
            token: databaseAccessToken,
          },
        },
        options: {
          debug: {
            packet: true,
            data: true,
            payload: true,
            token: false,
            log: true,
          },
          database: databaseName,
          encrypt: true,
        },
      };
    
      var connection = new Connection(config);
      connection.connect();
      connection.on("connect", function (err) {
        if (err) {
          console.log(err);
        }
        executeStatement(connection);
      });
    
      connection.on("debug", function (text) {
        console.log(text);
      });
    }
    function executeStatement(connection) {
      request = new Request("select * from CSVTest", function (err, rowCount) {
        if (err) {
          console.log(err);
        } else {
          console.log(rowCount + " rows");
        }
    
        connection.close();
      });
    
      request.on("row", function (columns) {
        columns.forEach(function (column) {
          if (column.value === null) {
            console.log("NULL");
          } else {
            console.log(column.value);
          }
        });
      });
    
      request.on("done", function (rowCount, more) {
        console.log(rowCount + " rows returned");
      });
    
      connection.execSql(request);
    }
    
    getConnect()
      .then(() => {
        console.log("run successfully");
      })
      .catch((err) => {
        console.log(err);
      });

Reference: Connecting to Azure SQL using Service Principal in NodeJS, but token is rejected参考: 在 NodeJS 中使用服务主体连接到 Azure SQL,但令牌被拒绝

暂无
暂无

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

相关问题 使用 Azure Active Directory Service Principal 身份验证为 Keycloak 配置 SQL 服务器 - Configure SQL Server with Azure Active Directory Service Principal authentication for Keycloak 如何使用 Active Directory 身份验证从 Tableau Desktop 访问 Azure SQL 服务器/数据库 - How to Access Azure SQL Server/Database from Tableau Desktop using Active Directory Authentication Azure Active Directory 身份验证 401,Bearer Token 签名无效 - Azure Active Directory Authentication 401, Bearer Token The signature is invalid 具有 Azure Active Directory 身份验证的 Postgres - Postgres with Azure Active Directory Authentication Azure SQL 来自 SSIS package 的 Active Directory 交互式身份验证 - Azure SQL Active Directory interactive authentication from SSIS package Azure Active Directory 应用程序服务无法使用用户凭据/令牌连接到 Azure Keyvault - Azure Active Directory app service can't connect to Azure Keyvault using user creds/token Azure SQL 与 Azure Active Directory 身份验证 - 用于安全性 function 用于行级安全性 - Azure SQL with Azure Active Directory authentication - use in security function for row-level security Azure DevOps 组织“无法连接到 #### Azure Active Directory - Azure DevOps organization "failed to connect to the #### Azure Active Directory Azure Active Directory Oauth 2.0 客户端凭证流与 API 管理访问令牌问题 - Azure Active Directory Oauth 2.0 Client Credentials Flow with API Management Access Token issue 如何刷新通过 Azure 身份验证收到的访问令牌? - How to refresh access token received with Azure authentication?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM