简体   繁体   English

requests-oauthlib 自动刷新客户端凭据流中的 Bearer 令牌?

[英]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:所以我的问题是:

  1. Is there a way to make the requests-oauthlib refresh the token automatically in this use case or do I need to manually track the age of my token and explicitly refresh it as needed?有没有办法让 requests-oauthlib 在此用例中自动刷新令牌,或者我是否需要手动跟踪我的令牌的年龄并根据需要显式刷新它?
  2. I'm not wedded to requests-oauthlib so if there is a better library that accomplishes the auto-refreshing I'd be interested in using it.我对 requests-oauthlib 并不执着,所以如果有更好的库可以完成自动刷新,我会有兴趣使用它。

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 CodeResource 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 requested scope - 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.

相关问题 使用 Requests-OAuthlib 失败的 OAuth1 身份验证 - OAuth1 authentication using Requests-OAuthlib failing Azure DevOps 的客户端凭据流 - Client Credentials Flow for Azure DevOps authlib 是否支持在使用客户端凭据时刷新我的访问令牌? - Does authlib support refresh my access token when using client credentials? 如何启用requests_oauthlib的日志记录? - How to enable logging for requests_oauthlib? 我无法在python中使用OAUTH 2.0 SAML断言承载流获取访问令牌 - I am unable to obtain access token using OAUTH 2.0 SAML Assertion Bearer flow in python Google API 流程每次都需要同意刷新令牌 - Google API flow requires consent for refresh-token every time Kubernetes Python客户端:使用Autobahn Websocket连接到Pod /服务/使用承载令牌扭曲 - Kubernetes Python Client: connecting to a pod/service using Autobahn websocket/Twisted using bearer token 如何使用 get 应用不记名令牌? - How to apply bearer token with a get? Python Mocking 请求不记名令牌? - Python Mocking a request for a bearer token? Python 如何通过使用 oauthlib 的帐户身份验证获取 ID_Token 以与 Open ID Connect 一起使用 - Python how to obtain ID_Token to use with Open ID Connect from using account authentication with oauthlib
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM