[英]requests-oauthlib auto refresh Bearer token in client credentials flow?
I'm using the python requests-oauthlib package to connect to the Microsoft Graph.我正在使用 python requests-oauthlib package 连接到 Microsoft Graph。 I am using the OAuth 2.0 Client Credentials flow.
我正在使用 OAuth 2.0 客户端凭证流程。
The following simplified code works perfectly fine:下面的简化代码工作得很好:
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
client = BackendApplicationClient(client_id='myclientid')
token_url = "https://login.microsoftonline.com/mydomain.onmicrosoft.com/oauth2/v2.0/token"
msgraph = OAuth2Session(client=client)
msgraph.fetch_token(
token_url = token_url,
client_secret = 'myclientsecret',
scope='https://graph.microsoft.com/.default')
response = msgraph.get(
url="https://graph.microsoft.com/v1.0/users/user@mydomain.com/messages")
While this works, the Bearer access token in this case is only valid for 1 hour.虽然这有效,但本例中的 Bearer 访问令牌仅在 1 小时内有效。 The requests-oauthlib package has support for refreshing tokens but it seems limited to token types that come with separate refresh tokens.
requests-oauthlib package 支持刷新令牌,但它似乎仅限于带有单独刷新令牌的令牌类型。 The client credentials flow as used with the Microsoft Graph only issues an access_token.
与 Microsoft Graph 一起使用的客户端凭据流仅发出 access_token。
So my questions are:所以我的问题是:
This behavior is by design (and aligns with the OAuth spec).此行为是设计使然(并符合 OAuth 规范)。 The only OAuth grants that support Refresh Tokens are Authorization Code and Resource Owner Password Credentials .
支持刷新令牌的唯一 OAuth 授权是Authorization Code和Resource Owner Password Credentials 。 The Implicit and Client Credentials grants only return an Access Token.
隐式和客户端凭据授予仅返回访问令牌。
More importantly, since the Client Credentials flow isn't interactive, there is no need for Refresh Tokens.更重要的是,由于客户端凭据流不是交互式的,因此不需要刷新令牌。 You simply request a new token when the old one expires.
您只需在旧令牌过期时请求一个新令牌。
As far as I can tell, there is still no built-in way to do this automatically using requests-oauthlib.据我所知,仍然没有内置的方法可以使用 requests-oauthlib 自动执行此操作。 There is a ticket about it on their GitHub with a couple of different ideas on how to do it, but nothing out of the box: https://github.com/requests/requests-oauthlib/issues/260
在他们的 GitHub 上有一张关于它的票,其中有几个不同的想法,但没有开箱即用: https://github.com/requests/requests-oauthlib/issues/260
I know this is an old question, but it seems unanswered, so please allow me to give it a try.我知道这是一个老问题,但似乎没有答案,所以请允许我试一试。
My initial answer was:我最初的回答是:
I dare make the hypothesis, reading your mention of lack of refresh token, that you did not add
offline_access
in your requestedscope
- if you want it to be part of the answer from the Microsoft authentication service, you have to (please refer to https://learn.microsoft.com/en-us/graph/auth-v2-user#token-response and the various pages around for more details).我敢假设,阅读你提到的缺少刷新令牌,你没有在你请求的
scope
中添加offline_access
- 如果你希望它成为 Microsoft 身份验证服务的答案的一部分,你必须(请参考https ://learn.microsoft.com/en-us/graph/auth-v2-user#token-response和周围的各种页面以获取更多详细信息)。
which was indeed totally irrelevant for the scenario used, as commented by Mark, and also clearly stated in https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/resilience-daemon-app#cache-and-store-tokens :正如 Mark 评论的那样,这确实与所使用的场景完全无关,并且在https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/resilience-daemon-app#cache-中也有明确说明和存储令牌:
It is important that applications use the "expires_in" property to determine the lifespan of the token.
应用程序使用“expires_in”属性来确定令牌的生命周期很重要。
So as an answer to your question 2., the above link also suggests the use of MSAL (MS Authentication Library) :因此,作为问题 2 的答案,上面的链接还建议使用MSAL(MS 身份验证库) :
MSAL implements and follows [best practices for caching and storing tokens] automatically.
MSAL 自动实施并遵循 [缓存和存储令牌的最佳做法]。
what the why use MSAL wiki page seems to confirm: 为什么使用 MSAL 维基页面似乎证实了什么:
It also adds value by [...] maintaining a token cache and refreshes tokens for you when they are close to expire.
它还通过 [...] 维护令牌缓存并在令牌即将过期时为您刷新令牌来增加价值。 You don't need to handle expiration on your own.
您不需要自己处理过期。
For your question 1., I indeed did not find a standard way in requests-oauthlib
to do so, either.对于您的问题 1,我确实也没有在
requests-oauthlib
中找到这样做的标准方法。
In this kind of situation, I usually don't monitor the age of the token, but just catch the 401 return code and fetch a new token.在这种情况下,我通常不会监控令牌的年龄,而只是捕获 401 返回码并获取新令牌。
To do so, I found suitable to tweak the first example of the Requests-OAuthlib - OAuth 2 Workflow - refreshing tokens section, replacing their call to refresh_token(refresh_url, **extra)
by a new call to fetch_token()
.为此,我发现可以调整Requests-OAuthlib 的第一个示例 - OAuth 2 工作流 - 刷新令牌部分,将对
refresh_token(refresh_url, **extra)
的调用替换为对fetch_token()
的新调用。
What I usually use in order to avoid repeating the try...except...
code piece, is to put it in a wrapper decorator (got a good inspiration in https://realpython.com/primer-on-python-decorators/#a-few-real-world-examples ) around my API-calling functions / methods.为了避免重复
try...except...
代码片段,我通常使用的是将它放在包装器装饰器中(在https://realpython.com/primer-on-python-decorators中得到了很好的启发/#a-few-real-world-examples ) 围绕我的 API 调用函数/方法。
Hope this time it helps more...希望这次能帮到更多...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.