gpt4 book ai didi

angular - IdentityServer4:缺少 auth_time

转载 作者:行者123 更新时间:2023-12-04 15:45:15 32 4
gpt4 key购买 nike

我有一个使用 identityserver4 服务器进行身份验证的 Angular (asp.net core) 应用程序。

在登录时,一切正常,显示登录表单并返回 id_token 和 access_token。

但是,一小时后,当 spa 应用再次尝试登录时(生命周期为 3600s = 1h),我收到内部服务器错误 500:identityserver4 上的“auth_time is missing”边

我发现恢复状态的唯一方法是访问 identityserver4 网站并注销。

完整的错误是:

System.InvalidOperationException: auth_time is missing.
at IdentityServer4.Extensions.PrincipalExtensions.GetAuthenticationTimeEpoch(IIdentity identity)
at IdentityServer4.Services.DefaultClaimsService.GetStandardSubjectClaims(ClaimsPrincipal subject)
at IdentityServer4.Services.DefaultClaimsService.GetAccessTokenClaimsAsync(ClaimsPrincipal subject, Resources resources, ValidatedRequest request)
at IdentityServer4.Services.DefaultTokenService.CreateAccessTokenAsync(TokenCreationRequest request)
at IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, String authorizationCode)
at IdentityServer4.ResponseHandling.AuthorizeResponseGenerator.CreateResponseAsync(ValidatedAuthorizeRequest request)
at IdentityServer4.Endpoints.AuthorizeEndpointBase.ProcessAuthorizeRequestAsync(NameValueCollection parameters, ClaimsPrincipal user, ConsentResponse consent)
at IdentityServer4.Endpoints.AuthorizeEndpoint.ProcessAsync(HttpContext context)
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events)
at IdentityServer4.Hosting.MutualTlsTokenEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

关于配置的一些数据:

identityserver4 上的客户端配置如下:

new Client
{
ClientId = "site.spa",
ClientName = "SPA Client",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
IdentityTokenLifetime = 3600,
AccessTokenLifetime = 3600,
RedirectUris = { "http://mywebsitespa.azurewebsites.net/signin-oidc" },
PostLogoutRedirectUris = { "http://mywebsitespa.azurewebsites.net/signout-callback-oidc" },
AllowedCorsOrigins = { "http://mywebsitespa.azurewebsites.net" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
JwtClaimTypes.AuthenticationTime,
"api1"
},
AlwaysIncludeUserClaimsInIdToken = true,
RequireConsent = false,
},

第一次登录时的 Jwt token (已解密)显示以下信息:

{
"nbf": 1557750961,
"exp": 1557751261,
"iss": "http://mywebsite.azurewebsites.net",
"aud": "site.spa",
"nonce": "N0.92260399539729281557750948716",
"iat": 1557750961,
"at_hash": "-ir-JDkxDre1YkrV-Nt5Ag",
"sid": "58f3f7ed9786043bb5634129dff8882b",
"sub": "1",
"auth_time": 1557750961,
"idp": "local",
"name": "user",
"given_name": "user",
"family_name": "family_name",
"website": "http://mywebsite.azurewebsites.com",
"amr": [
"pwd"
]
}

登录 Razor 页面有这段代码:

public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}

returnUrl = returnUrl ?? Url.Content("~/");

// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");

if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberMe, lockoutOnFailure: true);

if (result.Succeeded)
{
_logger.LogInformation("User logged in. Redirecting to: " + returnUrl);
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}

// If we got this far, something failed, redisplay form
return Page();
}

这是 ConfigureServices()

public void ConfigureServices(IServiceCollection services)
{
IdentityModelEventSource.ShowPII = true;

services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddDbContext<MyIdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));

// Identity Server
services.AddIdentityServer(options =>
{
options.UserInteraction = new IdentityServer4.Configuration.UserInteractionOptions
{
LoginUrl = "/Identity/Account/Login",
LogoutUrl = "/Identity/Account/Logout",
};
})
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(IS4Config.GetApiResources())
.AddInMemoryClients(IS4Config.GetClients())
.AddInMemoryIdentityResources(IS4Config.GetIdentityResources());

// Identity management
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<MyIdentityDbContext>()
.AddDefaultTokenProviders();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddAuthentication();

services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
});

services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
}

和 Configure()

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseIdentityServer();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseAuthentication();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

知道是什么导致了 identityserver4 上的这个错误吗?

最佳答案

将 AddAspNetIdentity() 添加到 services.AddIdentityServer() 问题消失了。

// Identity Server configuration
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;

options.UserInteraction = new IdentityServer4.Configuration.UserInteractionOptions
{
LoginUrl = "/Identity/Account/Login",
LogoutUrl = "/Identity/Account/Logout",
};
})
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(IS4Config.GetApiResources())
.AddInMemoryClients(IS4Config.GetClients())
.AddInMemoryIdentityResources(IS4Config.GetIdentityResources())
.AddAspNetIdentity<IdentityUser>();

关于angular - IdentityServer4:缺少 auth_time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56114271/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com