问题
I'm wanting to connect to an Azure SQL DB via SQLAlchemy with an AD token.
I've followed https://github.com/felipefandrade/azuresqlspn and can successfully connect with this method. However, I want to extend this and use SQLAlchemy to manage the connection.
from os import environ
import struct
import adal
from sqlalchemy import create_engine
import pyodbc
clientSecret = environ.get('clientSecret')
clientID = environ.get('clientID')
tenantID = environ.get('tenantID')
authorityHostUrl = "https://login.microsoftonline.com"
authority_url = authorityHostUrl + '/' + tenantID
resource = "https://database.windows.net/"
context = adal.AuthenticationContext(authority_url, api_version=None)
token = context.acquire_token_with_client_credentials(
resource,
clientID,
clientSecret)
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
driver = "Driver={ODBC Driver 17 for SQL Server}"
server = ";SERVER={0}".format(environ.get('server'))
database = ";DATABASE={0}".format(environ.get('database'))
connString = driver + server + database
SQL_COPT_SS_ACCESS_TOKEN = 1256
conn = pyodbc.connect(connString, attrs_before={SQL_COPT_SS_ACCESS_TOKEN:tokenstruct})
cursor = conn.cursor()
cursor.execute("SELECT TOP 20 ID, Name FROM [Table1]")
row = cursor.fetchone()
print("######")
print("Using pyodbc directly - This works")
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
print("#####")
print("Connecting via sqlalchemy - This doesn't work")
SAconnString = "mssql+pyodbc://<server>.database.windows.net/<database>?driver=ODBC+Driver+17+for+SQL+Server"
db = create_engine(SAconnString, connect_args={'attrs_before': {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct}})
SAconn = db.connect()
result = SAconn.execute("SELECT TOP 20 ID, Name FROM [Table1]")
for row in result:
print(row['ID'] + " " + row['Name'])
As noted in the code, using pyodbc.connect()
method will work. However, using SQLAlchemy I get the error FA005] [Microsoft][ODBC Driver 17 for SQL Server]Cannot use Access Token with any of the following options: Authentication, Integrated Security, User, Password
. It appears to me the connect_args
option is passing the token through, but with other options too. How do I get SQLAlchemy to correctly pass the AD Token to pyodbc?
回答1:
Need to send PyODBC connection string explicitly with urllib
.
connString = driver + server + database
params = urllib.parse.quote(connString)
db = create_engine("mssql+pyodbc:///?odbc_connect={0}".format(params), connect_args={'attrs_before': {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct}})
回答2:
how about this code using SQLAlchemy :
import sqlalchemy
import urllib
import pyodbc
params = urllib.parse.quote_plus("Driver={ODBC Driver 13 for SQL Server};Server=tcp:***.database.windows.net,1433;Database=Mydatabase;Uid=ServerAdmin@***;Pwd=***;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params, connect_args={'attrs_before': {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct}})
conn=engine.connect()
print(conn)
result = conn.execute("select * from tb1")
for row in result:
print(str(row[0]) + " " + str(row[1]))
conn.close()
I get the connection string from portal:
Hope this helps.
来源:https://stackoverflow.com/questions/57193301/pass-azure-ad-token-for-azure-sql-db-in-pre-connection-arguments-to-sqlalchemy-c