【发布时间】:2020-03-17 16:33:26
【问题描述】:
我正在使用带有 OpenIdConnect 的 Azure AD B2C 对 Web 应用程序进行身份验证。我已经让它主要工作了,除了一个小时后身份验证超时,即使用户正在积极使用该应用程序。
这是一个主要使用 ASPX 页面构建的旧 Web 应用程序。我只是在使用身份令牌,并且正在使用 cookie。我的应用程序中根本没有使用访问令牌。访问是根据用户声明以预先存在的方式完成的。我在 Microsoft.Identity.Client 中使用 MSAL.Net 库。登录工作正常。我得到一个代码,然后用它交换身份令牌
AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();
一切正常,除了令牌将在 1 小时后过期,无论我做什么。即使我正在使用该应用程序,一个小时后的第一个请求也将未经身份验证。我尝试添加一个调用以静默获取令牌以查看是否会刷新它,但它没有。使用 OpenIdConnect,offline_access 范围始终包括在内。如果我试图明确地包含它,它会抛出一个错误。但我从未见过任何证据表明存在刷新令牌,即使在幕后也是如此。
我在 StackOverflow 上找到了这个问题 - Azure AD B2C OpenID Connect Refresh token - 第一个答案引用了一个名为 UseTokenLifetime 的 OpenIdConnect 属性。如果我将其设置为 false,那么我不会在一个小时后失去身份验证,但现在它太远了。令牌/cookie 似乎永远不会过期,我可以永远保持登录状态。
我的愿望是,只要用户正在积极使用该应用程序,他们就会保持登录状态,但如果他们停止使用一段时间(一个小时),他们必须重新进行身份验证。我通过数小时的反复试验找到了实现这一目标的方法,我只是不确定它是否有意义和/或是否安全。我现在正在做的是,在每个经过身份验证的请求上,我更新用户的“exp”声明(不确定这是否重要),然后生成一个新的 AuthenticationResponseGrant,将 ExpiresUtc 设置为新时间。在我的测试中,如果我在不到一小时的时间内点击此代码,它会保持我的登录状态,然后如果我等待超过一小时,我将不再通过身份验证。
HttpContext.Current.User.SetExpirationClaim(DateTime.Now.AddMinutes(60.0));
public static void SetExpirationClaim(this IPrincipal currentPrincipal, DateTime expiration)
{
System.Diagnostics.Debug.WriteLine("Setting claims expiration to {0}", expiration);
int seconds = (int)expiration.Subtract(epoch).TotalSeconds;
currentPrincipal.AddUpdateClaim("exp", seconds.ToString(), expiration);
}
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value, DateTime expiration)
{
var identity = currentPrincipal.Identity as ClaimsIdentity;
if (identity == null)
return;
// check for existing claim and remove it
var existingClaim = identity.FindFirst(key);
if (existingClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
identity.AddClaim(new Claim(key, value));
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity),
new AuthenticationProperties() {
IsPersistent = true,
ExpiresUtc = new DateTimeOffset(expiration).UtcDateTime,
IssuedUtc = new DateTimeOffset(DateTime.Now).UtcDateTime
});
}
我的问题是,这有意义吗?有什么缺点吗?我从未见过任何建议这样做,但这是我发现唯一有效的方法。如果有更好的方法,我想知道它是什么。我考虑将我当前的代码作为“答案”而不是将其包含在问题中,但我不确定它是否正确。
【问题讨论】:
标签: azure azure-ad-b2c