Shankar
Shankar

Reputation: 8967

how to pass AAD AccessToken to authenticate SQL Server using aioodbc library?

I'm using aioodbc to connect to Azure SQL Server.

I wanted to pass accessToken to authenticate SQL server instead of admin user/pass.

I see some links that PyOdbc supports passing accessToken when creating connection. Is there similar one for aioodbc as well?

Upvotes: 0

Views: 147

Answers (1)

Shankar
Shankar

Reputation: 8967

I have followed this article ( if you wanted to pass accessToken ) - check it out https://techcommunity.microsoft.com/t5/apps-on-azure-blog/how-to-connect-azure-sql-database-from-python-function-app-using/ba-p/3035595

Create Access Token using msal:

authority = f'https://login.microsoftonline.com/{APP_TENANT_ID}'
scope = ['https://database.windows.net//.default']    
app = msal.ConfidentialClientApplication(APP_CLIENT_ID, authority=authority, client_credential=client_secret)
            token_response = app.acquire_token_for_client(scopes=scope)
            access_token = token_response.get('access_token')

Convert that access token to be usable inside Pyodbc connect

exptoken = b''
for i in bytes(access_token, "UTF-8"):
    exptoken += bytes({i})
    exptoken += bytes(1)

    tokenstruct = struct.pack("=i", len(exptoken)) + exptoken

    async with aioodbc.connect(dsn=conn_str, attrs_before={ SQL_COPT_SS_ACCESS_TOKEN:tokenstruct }) as conn:

Upvotes: 1

Related Questions