簡體   English   中英

如何將 AccessTokens 存儲到 Cookies 並使用它們為 Asp.net web 應用程序(非 MVC)調用圖 API

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

我想調用圖 API 來獲取 OneDrive 數據。 我能夠獲得看起來像這樣的 JWT // 故事

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..."
        //  }

刷新令牌、存儲在 cookies 中並訪問它們以調用 API 的正確步驟是什么。我瀏覽了很多可用的文檔,仍然不確定什么是正確的流程和方法。

請指導我正確的做法。

感謝您伸出援手。 對於您的方案,我建議對 .NET 使用MSAL並實施授權代碼流 在此流程中,當用戶登錄 web 應用程序時,該應用程序會收到一個授權代碼,該代碼將被兌換以獲取令牌以調用 web API。 MSAL 在獲取令牌后緩存令牌並可以刷新令牌。 以下是從令牌緩存中獲取令牌的方法:

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
}

在上面的示例中,應用程序首先嘗試從令牌緩存中獲取令牌。 如果拋出MsalUiRequiredException異常,應用程序將以交互方式獲取令牌。

請參閱有關授權代碼流程的其他文檔

如果您還有其他問題,請告訴我這是否有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM