我正在使用 Microsoft Graph C#.NET SDK 来访问用户的邮件收件箱。问题是,当我进行身份验证时,Microsoft 发回给我的令牌仅在 1 小时左右有效,而且过早过期。但是用户每 1 小时登录一次只是为了查看 Outlook 邮件收件箱,这太烦人了。我需要使这个登录持久化。
这是我使用的代码:
public static async Task Run()
{
string secret = "MyDamnPrivateSecret";
PublicClientApplication clientApp = new PublicClientApplication(secret);
GraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp));
}));
//Processing mailbox ...
}
private static async Task<string> GetTokenAsync(PublicClientApplication clientApp)
{
if (string.IsNullOrEmpty(Properties.Settings.Default.token) || string.IsNullOrWhiteSpace(Properties.Settings.Default.token))
{
//need to pass scope of activity to get token
string[] Scopes = { "User.Read", "Mail.ReadWrite" };
string token = null;
AuthenticationResult authResult = await clientApp.AcquireTokenAsync(Scopes);
token = authResult.AccessToken;
Properties.Settings.Default.token = token;
Properties.Settings.Default.Save();
return token;
}
else
{
return Properties.Settings.Default.token;
}
}
有什么办法可以延长过期时间吗?或者制作一个刷新令牌或其他东西来保持登录?