如何为Microsoft Graph刷新令牌

Hug*_*rio 6 c# microsoft-graph

我正在使用以下方法连接到Microsoft Graph:

public GraphServiceClient GetAuthenticatedClient(string token)
{
    GraphServiceClient graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            async (requestMessage) =>
            {
                // Append the access token to the request.
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
            }));
    return graphClient;
}
Run Code Online (Sandbox Code Playgroud)

我正在服务器上运行此代码。我正在使用的令牌是由外部应用发送给我的。

在最初的一个小时内一切正常,然后令牌过期。

我的问题是:由于我也可以访问刷新令牌,因此如何获得新令牌?

Mar*_*eur 22

There are two pieces required to enable Refresh Tokens:

  1. You need to request the scope offline_access. This tells the endpoint to provide a refresh_token alongside the access_token and associated metadata.

  2. You need to request a new access_token (and refresh_token as they come together) by repeating the same POST to /common/oauth2/v2.0/token with a slightly different body - grant_type is set to refresh_token and instead of a code, you supply a refresh_token property and value:

    https://login.microsoftonline.com/common/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=refresh_token&
    refresh_token=[REFRESH TOKEN]&
    client_id=[APPLICATION ID]&
    client_secret=[PASSWORD]&
    scope=[SCOPE]&
    redirect_uri=[REDIRECT URI]
    
    Run Code Online (Sandbox Code Playgroud)

A while back I wrote up a show primer on the v2 Endpoint that you might find helpful as well.

  • 您是否碰巧有一些 C# 代码的链接,显示如何获取刷新令牌,或者这只能通过使用 http 客户端手动调用 API 来实现? (2认同)

Dha*_*ati 6

当我没有refreshToken时,这对我有帮助 https://learn.microsoft.com/en-gb/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow

POST /oauth2/v2.0/token HTTP/1.1 Host: login.microsoftonline.com 
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer  
&client_id=2846f71b-a7a4-4987-bab3-760f389 
&client_secret=BYyVnAt56JpLwUcyo47XODd 
&assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs...pa970UvdVfQ 
&scope=https://graph.microsoft.com/user.read+offline_access 
&requested_token_use=on_behalf_of
Run Code Online (Sandbox Code Playgroud)

响应示例:

{
    "token_type": "Bearer",
    "scope": "User.Read Mail.Read Mail.Send Calendars.Read",
    "expires_in": 3600,
    "ext_expires_in": 3600,
    "access_token": "EwCAA8l6BAAUO9chh8cJscQLmU+LSWpbnr0v...ZgNcrJkgI=",
    "refresh_token": "MCS3KUzqyCY6rQH*NXLSLQctqj47w...x3Oa4r"
}
Run Code Online (Sandbox Code Playgroud)

  • 这里的要点是将 `offline_access` 添加到范围中(在空格之后)。 (3认同)