MSAL 将查找缓存并返回与要求匹配的任何缓存令牌。如果此类访问令牌已过期或不存在合适的访问令牌,但存在关联的刷新令牌(需要 offline_access 范围),MSAL 将自动使用它来获取新的访问令牌并透明地返回。
例如,如果您使用 MSAL 将授权码兑换为 microsoft graph 的访问令牌,则在 openid 连接 owin 中间件:
AuthorizationCodeReceived = async (context) =>
{
var code = context.Code;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID,
context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
ConfidentialClientApplication cca =
new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache,null);
string[] scopes = { "Mail.Read" };
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
}
catch (Exception eee)
{
}
},
使用范围Mail.Read,您可以获得Microsoft Graph 的访问令牌,用于读取用户的邮箱。现在如果您想在控制器/操作中调用outlook mail rest api,您可以使用范围:@ 987654325@,MSAL 将使用缓存的刷新令牌获取 Outlook 邮件休息 api 的令牌:
// try to get token silently
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,new ClientCredential(appKey), userTokenCache, null);
if (cca.Users.Count() > 0)
{
string[] scopes = { "https://outlook.office.com/mail.read" };
try
{
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes,cca.Users.First());
}
catch (MsalUiRequiredException)
{
try
{// when failing, manufacture the URL and assign it
string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);
ViewBag.AuthorizationRequest = authReqUrl;
}
catch (Exception ee)
{
}
}
}
else
{
}
请参考代码示例:Integrate Microsoft identity and the Microsoft Graph into a web application using OpenID Connect。