Azure SQL Server数据库AD令牌-Django [英] Azure SQL Server Database AD token - Django
问题描述
我已经使用 pyodbc 中的 AccessToken
成功连接了Azure SQL Server.在这里,我没有使用 username
或 password
来连接数据库.取而代之的是,我使用 attrs_before
传递通行证 token
.在这里,我会自动生成令牌.
I have successfully connected the Azure SQL Server using AccessToken
in the pyodbc. Here I didn't use username
or password
to connect the database. Instead of that, I used attrs_before
for pass token
. Here I am generating the token automatically.
令牌生成:
identity_endpoint = os.environ["IDENTITY_ENDPOINT"]
identity_header = os.environ["IDENTITY_HEADER"]
def get_bearer_token(resource_uri): #Automattically token will generate
token_auth_uri = f"{identity_endpoint}?resource={resource_uri}&api-version=2019-08-01"
head_msi = {'X-IDENTITY-HEADER': identity_header}
resp = requests.get(token_auth_uri, headers=head_msi)
access_token = resp.json()['access_token']
return access_token
Pyodbc连接:
accessToken = bytes(get_bearer_token("https://database.windows.net/"), 'utf-8');
exptoken = b"";
for i in accessToken:
exptoken += bytes({i});
exptoken += bytes(1);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;
conn = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};Server=yoursqlserver.database.windows.net,1433;Database=dbName",
attrs_before={1256: bytearray(tokenstruct)});
现在的问题是如何在Django框架中使用它来连接数据库?使用天蓝色令牌时,我们没有用户名
或密码
来连接数据库.
Now the problem is how to use this in the Django framework to connecting DB? We can't have a username
or password
to connect the database when using azure token.
请帮帮我.
推荐答案
我创建了一个新程序包来处理此功能.
I have created a new package to handle this feature.
pip install django-mssql-azure-backend
然后配置 settings.py
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'mydb',
'HOST': 'myserver.database.windows.net',
'PORT': '',
'IS_AZURE_BASED_TOKEN': True
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
如果您使用的是本地SQL服务器,请使用此配置.
If you are using a local SQL server, use this configuration.
DATABASES = {
'default': {
'ENGINE': 'sql_server.pyodbc',
'NAME': 'mydb',
'USER': 'user@myserver',
'PASSWORD': 'password',
'HOST': 'myserver.database.windows.net',
'PORT': '',
'IS_AZURE_BASED_TOKEN': False
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
Git链接: https://github.com/shakthifuture/django-mssql-天蓝色后端
如果遇到任何问题,请在此处提出错误
If you faced any issue, please raise your bug here.
这篇关于Azure SQL Server数据库AD令牌-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!