使用Azure AD身份验证对Azure SQL DB的基于令牌的身份验证支持

时间:2020-04-08 21:01:55

标签: azure azure-active-directory azure-sql-database

根据此页面。

https://docs.microsoft.com/en-us/archive/blogs/sqlsecurity/token-based-authentication-support-for-azure-sql-db-using-azure-ad-auth

仅当客户端处于Windows环境下时,才支持基于AAD令牌的身份验证来访问Azure SQL DB。

MacOS和Linux是否可以支持基于AAD令牌的身份验证来访问Azure SQL DB?

https://github.com/mkleehammer/pyodbc/issues/228

    token = context.acquire_token_with_client_credentials(
        database_url,
        azure_client_id,
        azure_client_secret
    )
    print(token)

    tokenb = bytes(token["accessToken"], "UTF-8")
    exptoken = b''
    for i in tokenb:
        exptoken += bytes({i})
        exptoken += bytes(1)
    tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
    tokenstruct

    SQL_COPT_SS_ACCESS_TOKEN = 1256
    CONNSTRING = "DRIVER={};SERVER={};DATABASE={}".format("ODBC Driver 17 for SQL Server", prod_server, prod_db)

    db_connector = pyodbc.connect(CONNSTRING, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: tokenstruct})

这是我在MacOS下运行的代码,它是python。

我一直遇到这个问题

pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect)")

有人有主意吗?

1 个答案:

答案 0 :(得分:1)

似乎您尚未将应用程序服务主体添加到Azure SQL数据库中。

您需要做的是

1。为您的Azure SQL Server启用AAD身份验证。请在此步骤中选择一个AAD用户。

enter image description here

2。使用在步骤1中设置的用户帐户连接到Azure SQL数据库。

3。将应用程序服务主体添加到SQL Server,并向其发出适当的警报。

CREATE USER [Azure_AD_principal_name] FROM EXTERNAL PROVIDER;
EXEC sp_addrolemember 'db_owner', 'Azure_AD_principal_name';

在这里,Azure_AD_principal_name应该是应用程序的名称。

4。使用AAD连接到Azure SQL数据库

enter image description here