我正在与多个用户一起使用一个租户MVC Web应用程序。此应用程序针对不同的客户进行了多种部署,有些客户希望通过Outlook 365发送邮件。该应用程序对存储在数据库中的用户使用表单身份验证。
我已尝试根据以下示例-https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect使某项工作正常,但是它与表单身份验证冲突,因为即使登录成功,我也会循环回到表单登录页面。
成功登录后,我可以通过将用户定向到Azure AD登录来成功检索访问令牌:
var url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?" +
"client_id=" + AuthenticationConfig.ClientId +
"&response_type=code" +
"&redirect_uri=" + AuthenticationConfig.RedirectUri +
"&response_mode=query" +
"&scope=" + AuthenticationConfig.BasicSignInScopes +
"&state=12345";
然后在回调中使用以下命令获取访问令牌:
public static async Task<string> GetAccessToken(string code)
{
var app = ConfidentialClientApplicationBuilder
.Create(AuthenticationConfig.ClientId)
.WithClientSecret(AuthenticationConfig.ClientSecret)
.WithRedirectUri(AuthenticationConfig.RedirectUri)
.WithAuthority(AuthenticationConfig.Authority)
.Build();
var scopes = new List<string> { "offline_access", "user.read", "mail.read", "mail.send" };
var authenticationResult = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
return authenticationResult.AccessToken;
}
但是,认证结果中没有返回刷新令牌。我希望获取访问令牌/到期并刷新令牌/到期并存储它们,以便用户可以通过Azure AD进行一次身份验证,然后将来可以使用刷新令牌以静默方式更新访问令牌。
我已经读了很多书,但是我能找到的大多数信息都是基于对应用程序使用Azure AD登录的。我只需要保留登录名和身份验证表单即可,仅用于发送电子邮件。这可能吗?
更新以尝试针对用户缓存令牌并读回令牌:
public static async Task OnAuthorisationCodeReceived(string code)
{
var app = ConfidentialClientApplicationBuilder
.Create(AuthenticationConfig.ClientId)
.WithClientSecret(AuthenticationConfig.ClientSecret)
.WithRedirectUri(AuthenticationConfig.RedirectUri)
.WithAuthority(AuthenticationConfig.Authority)
.Build();
var scopes = new List<string> { "offline_access", "user.read", "mail.read", "mail.send" };
var authenticationResult = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
var account = authenticationResult.Account;
var identity = new ClaimsIdentity();
identity.AddClaim(new System.Security.Claims.Claim(ClaimConstants.ObjectId, account.HomeAccountId.ObjectId));
identity.AddClaim(new System.Security.Claims.Claim(ClaimConstants.TenantId, account.HomeAccountId.TenantId));
identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Upn, account.Username));
var claimsPrincipal = new ClaimsPrincipal(identity);
// as per example store the cache
var userTokenCache = new MSALPerUserMemoryTokenCache(app.UserTokenCache, claimsPrincipal);
// no accounts returned
var accounts = await app.GetAccountsAsync();
var newres = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);
}
没有帐户退回,我看到缓存令牌的唯一方法是保留默认令牌,这样就不会针对用户存储令牌。
答案 0 :(得分:0)
不幸的是,MSAL.NET(和一般的MSAL)没有公开刷新令牌。
您可以看到AuthenticationResult中没有“ refreshToken”。
您可以通过调用AcquireTokenSilent自动处理刷新令牌。