我试图强制使用带有ASP.Net Identity的Identity Server 4(v 2.1.1)在一段时间后重定向到Login页面。我已将每个令牌生存期/超时设置为1分钟,甚至可以解决5分钟的偏差。身份服务器会自动重新验证用户身份(即不需要登录页面)。
以下是相关代码
IdentityServer Startup.cs:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer(options =>
{
options.Authentication.CookieLifetime = TimeSpan.FromSeconds(60);
options.Authentication.CookieSlidingExpiration = false;
})
.AddSigningCredential(certificate)
.AddInMemoryClients(Clients.GetClients())
.AddInMemoryApiResources(Resources.GetApiResources())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddAspNetIdentity<ApplicationUser>()
.AddJwtBearerClientAuthentication();
Config.GetGlients():
// WebForms Client
new Client
{
...
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AllowAccessTokensViaBrowser = true,
AuthorizationCodeLifetime = 60,
AccessTokenLifetime = 60,
IdentityTokenLifetime = 60,
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 60,
SlidingRefreshTokenLifetime = 60
},
Web表单客户端中间件层:
public void AuthSetup(IAppBuilder app)
{
// Use Cookies to Store JWT Token for Web Browsers
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
ExpireTimeSpan = TimeSpan.FromMinutes(1),
SlidingExpiration = true
});
JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
// Authenticate to Auth Server
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
SignInAsAuthenticationType = "Cookies",
Authority = "http://localhost:5002/",
ClientId = "client",
RedirectUri = "http://localhost:8888/",
PostLogoutRedirectUri = "http://localhost:8888/",
ResponseType = "code id_token token",
Scope = "openid profile AuthApi",
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = async n =>
{
var claimsToExclude = new[] { "aud", "iss", "nbf", "exp", "nonce", "iat", "at_hash", "c_hash", "idp", "amr" };
var claimsToKeep = n.AuthenticationTicket.Identity.Claims.Where(x => false == claimsToExclude.Contains(x.Type)).ToList();
claimsToKeep.Add(new Claim("id_token", n.ProtocolMessage.IdToken));
if (n.ProtocolMessage.AccessToken != null)
{
// Add access_token so we don't need to request it when calling APIs
claimsToKeep.Add(new Claim("access_token", n.ProtocolMessage.AccessToken));
var userInfoClient = new UserInfoClient(new Uri(n.Options.Authority + "connect/userinfo").ToString());
var userInfoResponse = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
var userInfoClaims = userInfoResponse.Claims
.Where(x => x.Type != "sub") // filter sub since we're already getting it from id_token
.Select(x => new Claim(x.Type, x.Value));
claimsToKeep.AddRange(userInfoClaims);
}
var ci = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType, "name", "role");
ci.AddClaims(claimsToKeep);
n.AuthenticationTicket = new AuthenticationTicket(ci, n.AuthenticationTicket.Properties);
},
RedirectToIdentityProvider = n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
n.ProtocolMessage.IdTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token")?.Value;
return Task.FromResult(0);
}
}
});
app.UseStageMarker(PipelineStage.Authenticate);
}
我遗漏了哪些其他设置以强制服务器要求用户在令牌过期后登录?
答案 0 :(得分:2)
Identity Server会创建自己的身份验证Cookie“idsrv”,默认情况下为lifetime of 10 hours。 10个小时后,它会自动重新验证您。要更改此默认值,您可以在配置Identity Server时更改CookieLifetime
属性,例如
services.AddIdentityServer(options =>
{
options.Authentication.CookieLifetime = TimeSpan.FromSeconds(60);
})
.AddSigningCredential(certificate)
.AddInMemoryClients(Clients.GetClients())
.AddInMemoryApiResources(Resources.GetApiResources())
.AddInMemoryIdentityResources(Resources.GetIdentityResources())
.AddAspNetIdentity<ApplicationUser>()
.AddJwtBearerClientAuthentication();
此外,在您的WebForms客户端OpenIdConnectAuthenticationOptions
中,您可能希望将UseTokenLifetime
属性设置为true
。