ibis icon indicating copy to clipboard operation
ibis copied to clipboard

docs: document mssql Azure Active Directory authentication

Open inigohidalgo opened this issue 1 year ago • 2 comments

Please describe the issue

https://github.com/ibis-project/ibis/issues/7381#issuecomment-1766582531

Some additional configuration/munging is needed to enable authentication to azure SQL services. We should add a section to the documentation explaining how this is done

import struct
from azure import identity
import sqlalchemy as sa


SQL_COPT_SS_ACCESS_TOKEN = 1256  # Connection option for access tokens, as defined in msodbcsql.h
TOKEN_URL = "https://database.windows.net/"  # The token URL for any Azure SQL database


azure_credentials = identity.DefaultAzureCredential()

def provide_token(dialect, conn_rec, cargs, cparams):
    """sqlalchemy.event.listens_for(ibis_conn.con, "do_connect")(provide_token)
    """
    # remove the "Trusted_Connection" parameter that SQLAlchemy adds
    cargs[0] = cargs[0].replace(";Trusted_Connection=Yes", "")

    # create token credential
    raw_token = azure_credentials.get_token(TOKEN_URL).token.encode("utf-16-le")
    token_struct = struct.pack(f"<I{len(raw_token)}s", len(raw_token), raw_token)

    # apply it to keyword arguments
    cparams["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: token_struct}

def make_ibis_connection_login_ad_interactive(conn):
    sa.event.listens_for(conn.con, "do_connect")(provide_token)
raw_conn = ibis.connect(
    f"mssql://{os.environ['SERVER_NAME_ENV']}/{os.environ['DB_NAME_ENV']}",
    query = {
        "driver": "ODBC Driver 17 for SQL Server",
    }
)
make_ibis_connection_login_ad_interactive(raw_conn)

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

inigohidalgo avatar Jun 27 '24 15:06 inigohidalgo

@cpcloud I can't assign issues, could you assign me? thx

inigohidalgo avatar Jun 27 '24 15:06 inigohidalgo

Done

cpcloud avatar Jun 27 '24 15:06 cpcloud