問題描述
我正在嘗試使用 OAuth2 對用戶進行身份驗證并訪問資源.但是,我在這樣做時遇到了一些問題.以下是詳細信息.
- 我已在 Azure 門戶上將應用注冊為 Web Api
- 我想編寫一個 python 腳本,通過它我可以請求授權碼,然后是訪問令牌
挑戰(zhàn):
- 我沒有重定向網(wǎng)址.我不確定我可以在這里使用什么
- 當我使用鏈接在瀏覽器中獲取授權碼時,它要求我登錄 Azure.如何確保它也要求我通過 Python API 登錄?
這是我用來獲取身份驗證代碼的 python 腳本:
導入請求導入json'''請求授權碼模板https://login.microsoftonline.com/{tenant}/oauth2/authorize?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&response_type=代碼&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=查詢&resource=https%3A%2F%2Fservice.contoso.com%2F&狀態(tài)=12345'''有效載荷 = {'client_id': '***', 'response_type': 'code', 'response_mode': 'query',資源":***"}get_authorization_code = requests.get('https://login.microsoftonline.com/tenant/oauth2/authorize',參數(shù)=有效負載,驗證=假)打印 get_authorization_code
我得到的此代碼的響應是:響應 [200]
授權代碼授予流程 (response_type=code
) 期望您在用戶代理(即瀏覽器或瀏覽器控件)到該 URL.用戶將看到登錄過程(例如用戶名、密碼、多重身份驗證等),當所有這些都完成后,瀏覽器將被重定向到 redirect_uri
.p>
如果您將 Web 應用程序編碼為客戶端,這一切都非常簡單(您只需將用戶(在他們的瀏覽器中)發(fā)送到您構建的 URL,并在 redirect_uri
以在登錄完成后接收授權碼).但是,您似乎正在編寫控制臺應用程序(或其他將用戶發(fā)送到可以捕獲最終重定向的瀏覽器控件不切實際的應用程序)的腳本.您有幾個選項,具體取決于腳本是否在高度安全的環(huán)境中運行.
將 API 作為應用程序調用
這可能是最簡單的實現(xiàn)方式,但需要客戶端在高度信任的安全環(huán)境中運行.應用程序將以自身身份(而不是以用戶身份)進行身份驗證,獲取訪問令牌,并發(fā)出 API 請求.這是 OAuth 2.0 客戶端憑據(jù)授予流程.
您需要:
- 在 Azure AD 中將您的客戶端應用程序注冊為 Web 應用程序/Web API(這很重要,因為它告訴 Azure AD 這是一個機密客戶端,并允許您關聯(lián)憑據(jù)(密碼或證書).
- 聲明您的客戶端應用需要訪問您的 API(將注冊為不同的網(wǎng)絡應用/網(wǎng)絡 API).
對于 Python,最簡單的方法是使用 ADAL for Python.例如,在使用證書進行身份驗證時獲取訪問令牌:
導入adalcontext = adal.AuthenticationContext('https://login.microsoftonline.com/{tenant-id}')token = context.acquire_token_with_client_certificate(https://api.example.com",{client-id}",'{證書內容}','{證書指紋}')
請參閱 GitHub 上的其他詳細信息.
以用戶身份調用 API,使用設備代碼流
設備流程允許有限輸入體驗(例如電視或很少使用的控制臺應用程序)在用戶的上下文中獲取 OAuth 2.0 訪問令牌,同時允許用戶在具有更好輸入功能的不同設備上執(zhí)行實際登錄(例如在智能手機或臺式計算機上).
您需要:
- 在 Azure AD 中將您的客戶端應用程序注冊為本機客戶端應用程序(這很重要,因為它告訴 Azure AD 這是一個公共客戶端,它允許應用程序通過委托獲取訪問令牌未經(jīng)應用身份驗證的權限(因為公共客戶端無法對用戶保密).
- 聲明您的客戶端應用需要訪問您的 API(將注冊為單獨的網(wǎng)絡應用/網(wǎng)絡 API).
設備代碼流程包括:
- 客戶端應用向 Azure AD 發(fā)出請求以獲取設備代碼.此設備代碼會顯示給用戶(連同 URL).
- 在單獨的設備上(或者,例如,在同一設備上的成熟瀏覽器中),用戶訪問給定的 URL,并輸入給定的設備代碼.系統(tǒng)會提示用戶登錄,并在用戶登錄時顯示成功消息.
- 同時,客戶端應用會定期輪詢 Azure AD,以查看用戶是否已兌換設備代碼(并已登錄).如果是,則客戶端應用收到了訪問令牌.
對于 Python,將 ADAL 用于 Python 也很有用.獲取設備代碼的請求如下所示:
context = adal.AuthenticationContext('https://login.microsoftonline.com/{tenant-id}')code = context.acquire_user_code('https://api.example.com', '{client-id}')打印(代碼['消息'])
定期輪詢請求如下所示:
token = context.acquire_token_with_device_code('https://api.example.com', code, '{client-id}')
請參閱 GitHub 上的其他詳細信息.
I'm trying to get the user authenticated using OAuth2 and access resources. However, I'm having some issues doing so. Here are the details.
- I've registered the app as a Web Api on the Azure portal
- I want to write a python script through which I can request an authorization code and then the access token
Challenges:
- I don't have redirect url. I'm not sure what I can use here
- When I use the link to get the authorization code in the browser, it asks me to sign in to Azure. How can I make sure that it asks me to login through the Python API as well?
Here's the python script that I'm using just to get the authentication code:
import requests
import json
'''Request Authorization code template
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
'''
payload = {'client_id': '***', 'response_type': 'code', 'response_mode': 'query',
'resource': '***'}
get_authorization_code = requests.get('https://login.microsoftonline.com/tenant/oauth2/authorize',
params=payload, verify=False)
print get_authorization_code
Response for this code I get is : Response [200]
The Authorization Code Grant flow (response_type=code
) expects you to actually send the user, in a user-agent (i.e. a browser or a browser control) to that URL. The user will be presented with the sign-in process (e.g. username, password, multi-factor authentication, etc.) and when all that is done, the browser will be redirected to the redirect_uri
.
This is all very simple if you're coding a web app as the client (you just send the user (in their browser) to the URL you've constructed, and you host a page at the redirect_uri
to receive the authorization code after the sign-in completes). It seems, however, that you are maybe scripting a console app (or other app where it's impractical to send the user to a browser control where you can catch the eventual redirect). You have a few options, depending on whether or not the script is running in a highly-secure environment.
To call the API as an application
This is probably the simplest to implement, but requires the client to be running in a high-trust secure environment. The application will authenticate as itself (not as a user), obtain an access token, and make the API request. This is the OAuth 2.0 Client Credentials Grant flow.
You will need to:
- Register your client app in Azure AD as a web app/web API (this is important, as it tells Azure AD that this is a confidential client, and allows you to associate credentials (a password or a certificate) for the app.
- Declare that your client app requires access to your API (which would be registered as a different web app/web API).
With Python, the easiest way to do this is to use ADAL for Python. For example, to obtain an access token while authenticating with a certificate:
import adal
context = adal.AuthenticationContext('https://login.microsoftonline.com/{tenant-id}')
token = context.acquire_token_with_client_certificate(
"https://api.example.com",
"{client-id}",
'{certificate-content}',
'{certificate-thumbprint}')
See additional details on GitHub.
To call the API as a user, using the device code flow
The device flow allows limited-input experiences (e.g. think a TV, or a seldom-used console app) to obtain an OAuth 2.0 access token in the context of a user, while allowing the user to perform the actual sign-in on a different device with better input capabilities (e.g. on a smartphone or desktop computer).
You will need to:
- Register your client app in Azure AD as a native client app (this is important, as it tells Azure AD that this is a public client, which allows the app to get an access token with delegated permissions without the app authenticating (because public clients can't keep a secret from the user).
- Declare that your client app requires access to your API (which would be registered as a separate web app/web API).
The device code flow consists of:
- The client app makes a request to Azure AD to get an device code. This device code is displayed to the user (along with a URL).
- On a separate device (or, e.g. in full-fledged browser in the same device), the user visits the given URL, and inputs the given device code. The user is prompted to sign in and is shows a success message when they do so.
- Meanwhile, the client app periodically polls Azure AD to see if the user has redeemed the device code (and signed in). If yes, the client app received the access token.
With Python, it is again useful to use ADAL for Python. The request to get the device code would look like this:
context = adal.AuthenticationContext('https://login.microsoftonline.com/{tenant-id}')
code = context.acquire_user_code('https://api.example.com', '{client-id}')
print(code['message'])
The periodic polling requests look like this:
token = context.acquire_token_with_device_code('https://api.example.com', code, '{client-id}')
See additional details on GitHub.
這篇關于Azure AD 身份驗證 Python Web API的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!