简体   繁体   中英

How Store AccessTokens to Cookies and use them to call Graph API for Asp.net web application (non MVC)

I want to Call graph API to get OneDrive Data. I am able to obtain JWT which looks like this // The conte

nts of the JSON look like this:
        //  {
        //     "token_type":"Bearer",
        //      "scope": "Directory.Read.All Files.ReadWrite Group.ReadWrite.All Mail.ReadWrite Mail.Send User.ReadBasic.All",
        //      "expires_in":"3599",
        //      "ext_expires_in": "0",
        //      "expires_on":"1426551729",
        //      "not_before":"1426547829",
        //      "resource":"https://graph.microsoft.com/",
        //      "access_token":"eyJ0eXAiOiJKV1QiLCJhb...",
        //      "refresh_token":"AAABAAAAvPM1KaPlrEqd...",
        //      "id_token":"eyJ0eXAiOiJKV1QiLCJhbGci..."
        //  }

What are the correct steps to refresh the token, store in cookies and access them to call API. I went through a lot of documentation available still unsure what is the the right flow and way of doing it.

Please guide me to the correct way of doing it.

Thank you for reaching out. For your scenario, I would recommend using MSAL for .NET and implement the authorization code flow . In this flow, when users sign in to web apps, the app receives an authorization code that is redeemed to acquire a token to call web APIs. MSAL caches a token after it has been acquired and can refresh the token. Here's how you can acquire a token from the token cache :

AuthenticationResult result = null;
var accounts = await app.GetAccountsAsync();

try
{
 result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
        .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
 // A MsalUiRequiredException happened on AcquireTokenSilent.
 // This indicates you need to call AcquireTokenInteractive to acquire a token
 System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

 try
 {
    result = await app.AcquireTokenInteractive(scopes)
          .ExecuteAsync();
 }
 catch (MsalException msalex)
 {
    ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
 }
}
catch (Exception ex)
{
 ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
 return;
}

if (result != null)
{
 string accessToken = result.AccessToken;
 // Use the token
}

In the above example, the application first attempts to acquire a token from the token cache. If a MsalUiRequiredException exception is thrown, the application acquires a token interactively.

Please see additional docs on auth code flow

Let me know whether this helps and if you have further questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM