如何刷新認證令牌 Microsoft Graph使用Microsoft Graph .NET Client Library或其他使用C#?使用C#刷新MS Graph的認證令牌
什麼我目前做的是保持令牌靜態類:
public class TokenKeeper
{
public static string token = null;
public static string AcquireToken()
{
if (token == null || token.IsEmpty())
{
throw new Exception("Authorization Required.");
}
return token;
}
public static void Clear()
{
token = null;
}
}
我填補了啓動類令牌:
public partial class Startup
{
private static string AppKey = CloudConfigurationManager.GetSetting("ida:Password");
private static string aadInstance = CloudConfigurationManager.GetSetting("ida:AADInstance");
private static string TenantName = CloudConfigurationManager.GetSetting("ida:Tenant");
private static string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, TenantName);
private static string graphResourceId = CloudConfigurationManager.GetSetting("ida:GraphUrl");
private BpContext db = new BpContext();
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
string ClientId = CloudConfigurationManager.GetSetting("ida:ClientID");
string Authority = "https://login.microsoftonline.com/common/";
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
Authority = Authority,
Scope = "User.ReadBasic.All",
//Details omitted
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
// Create a Client Credential Using an Application Key
ClientCredential credential = new ClientCredential(ClientId, AppKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
"http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
TokenKeeper.token = result.AccessToken;
return Task.FromResult(0);
}
//Details omitted
}
});
}
}
我也很清楚上登出令牌。
AcquireTokenByRefreshToken與AcquireSilentAccessToken一起不起作用。我得到了兩個例外。對於第一種情況:異常說明用戶是未知的(訪問令牌和刷新令牌現在被緩存並且正確,我證實了它),而後者僅引發AdalAuthenticationReqiredException。 –