这是验证的代码,用于 Microsoft Graph 与 Outlook :
public async Task AquireToken()
{
try
{
if (_AuthResult == null)
{
_AuthResult = await Program.PublicClientApp.AcquireTokenSilentAsync(
_scopes, Program.PublicClientApp.Users.FirstOrDefault());
}
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilentAsync.
// This indicates you need to call AcquireTokenAsync to acquire a token.
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
_AuthResult = await Program.PublicClientApp.AcquireTokenAsync(_scopes);
}
catch (MsalException msalex)
{
_ResultsText = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
_ResultsText = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
}
if (_AuthResult != null)
{
_ResultsText = await GetHttpContentWithToken(_graphAPIEndpoint, _AuthResult.AccessToken);
}
}
它基于Microsoft提供的samples。在控制台输出中,它说:
Token Expires:04/09/2017 14:18:06 +01:00
该代码显示于:
$"Token Expires: {_AuthResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine;
因此,这意味着令牌对一小时有效。因此,如果我再次运行我的实用程序,我希望它使用相同的令牌,直到它需要请求新的。但事实并非如此。 始终会显示提示。
我错过了哪一步?
根据评论中的请求,这是例外的详细信息:
MsalUiRequiredException:在AcquiretokenSilent API中传递了空用户。传入用户对象或调用acquireToken身份验证。
我需要查看提供的答案:
您需要实现令牌缓存并使用AcquireTokenSilentAsync。 https://docs.microsoft.com/en-us/outlook/rest/dotnet-tutorial有一个网络应用示例。
答案 0 :(得分:1)
桌面上的MSAL .NET不提供持久缓存,因为它没有明显的存储空间可以依赖开箱即用(而MSAL确实在UWP,Xamarin iOS和Android上提供持久存储,其中app隔离存储可用)。开箱即用,桌面上的MSAL .NET使用内存缓存,一旦进程结束就会消失。 请参阅https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-desktop-msgraph-v2/以获取演示如何提供基于文件的简单缓存的示例,该缓存将在执行期间保留令牌。
答案 1 :(得分:1)
我使用了注册表。成功登录后保存令牌,然后在每次需要使用 GraphServiceClient 时调用令牌。如果令牌已过期或出现错误,您可以调用登录过程并保存新令牌。
public static async Task<GraphServiceClient> GetAuthenticatedClientAsync()
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string appID = ConfigurationManager.AppSettings["ida:AppId"];
PublicClientApplication PublicClientApp = new PublicClientApplication(appID);
string[] _scopes = new string[] { "Calendars.read", "Calendars.readwrite", "Mail.read", "User.read" };
AuthenticationResult authResult = null;
string keyName = @"Software\xxx\Security";
string valueName = "Status";
string token = "";
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(keyName, false);
if (regKey != null)
{
token = (string)regKey.GetValue(valueName);
}
if (regKey == null || string.IsNullOrEmpty(token))
{
authResult = await PublicClientApp.AcquireTokenAsync(_scopes); //Opens Microsoft Login Screen
//code if key Not Exist
RegistryKey key;
key = Registry.CurrentUser.CreateSubKey(@"Software\xxx\Security");
key.OpenSubKey(@"Software\xxx\Security", true);
key.SetValue("Status", authResult.AccessToken);
key.SetValue("Expire", authResult.ExpiresOn.ToString());
key.Close();
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
else
{
//code if key Exists
RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"Software\xxx\Login", true);
// set value of "abc" to "efd"
token = (string)regKey.GetValue(valueName);
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
}));
try
{
Microsoft.Graph.User me = await graphClient.Me.Request().GetAsync();
}
catch(Exception e)
{
if (e.ToString().Contains("Access token validation failure") || e.ToString().Contains("Access token has expired"))
{
string keyName = @"Software\xxx\Security";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
if (key != null)
{
key.DeleteValue("Status");
key.DeleteValue("Expire");
}
else
{
MessageBox.Show("Error! Something went wrong. Please contact your administrator.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
await GetAuthenticatedClientAsync();
}
}
return graphClient;
}