【发布时间】:2017-08-17 15:16:27
【问题描述】:
我创建了一个 b2c-dotnet-webapp-and-webapi 类型的应用程序。但是 20 分钟后或某个时间后(近 30 分钟不确定)我的 WebApp 在 Ajax 调用期间抛出异常,说 401(未授权)。当 ajax 调用命中 WebApp 控制器时出现此异常所以此错误来自 OWIN 中间件不确定原因。
我的 Startup.cs 设置是
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CPasswordResetPolicy));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CSignInPolicy));
}
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
if (context.Exception is OpenIdConnectProtocolInvalidNonceException &&
context.Exception.Message.Contains("IDX10316"))
{
// Redirect to the originally requested URL
context.Response.Redirect(context.Request.Uri.PathAndQuery);
}
else
{
var trackingId = Guid.NewGuid().ToString("N");
_telemetry.TrackException(
context.Exception,
new Dictionary<string, string> {{"SignInErrorTrackingId", trackingId}});
context.Response.Redirect($"/Home/SignInError?trackingId={trackingId}");
}
return Task.FromResult(0);
}
private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
{
return new OpenIdConnectAuthenticationOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = string.Format(_aadInstance, _tenant, policy),
AuthenticationType = policy,
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = _clientId,
RedirectUri = _redirectUri,
PostLogoutRedirectUri = _redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
},
Scope = "openid",
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
SaveSigninToken = true,
},
};
}
}
如果我要修改代码
app.UseCookieAuthentication(new CookieAuthenticationOptions { SlidingExpiration = true, ExpireTimeSpan = TimeSpan.FromMinutes(60) });,
并在 OpenIdConnectAuthenticationOptions 中添加以下设置
UseTokenLifetime = false,
然后我的 WebApp 工作了 1 小时,之后我再次面临 401 Unauthorized。这次我的 WEAPI 给出了这个错误,因为我猜默认令牌的有效期为 1 小时。
问题:如果令牌在 ajax 调用期间 1 小时后过期,我该如何管理令牌问题?以及我应该拥有的最佳设置是什么,以便我的中间件在 20 分钟或随机时间后不会给我 401?
如果我做错了什么,请忽略。我对此很陌生,没有太多想法。
【问题讨论】:
标签: c# oauth asp.net-web-api2 owin azure-ad-b2c