gpt4 book ai didi

identityserver4 - IdentityServer 4 的自定义登录 UI

转载 作者:行者123 更新时间:2023-12-04 17:44:02 27 4
gpt4 key购买 nike

我正在做一个类似于 IdentityServer4.Quickstart.UI 的项目,但将登录 UI 和 IdentityServer 分开。更具体地说,IdentityServer 本身将是一个纯 WebApi,而登录 UI 可以是使用 Angualr 或 React 或...构建的任何 SPA。目前,我面临一个问题 Identity.Application 未通过身份验证。失败消息:取消保护票证失败

更详细的流程是:在SPA页面点击登录按钮后,代码如下

var result = await this._signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

将在 WebApi(IdentityServer) 中运行并且 result 成功(用户已登录,这可以在 IdentityServer 代码中的 UserSession 中看到)。

按照 IdentityServer4.Quickstart.UI 中的过程,UI 将被重定向到 /connect/authorize/callback 端点。但是,当我将 UI 重定向到 /connect/authorize/callback 时,用户不再登录。错误是 Identity.Application 未通过身份验证。失败消息:取消保护票证失败。请帮忙看看哪里出了问题。有人说这是因为身份验证 cookie,但我不知道该怎么做。

详细日志附后

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\Admin\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
dbug: IdentityServer4.Startup[0]
Custom IssuerUri set to http://localhost:5000
dbug: IdentityServer4.Startup[0]
Using Identity.Application as default ASP.NET Core scheme for authentication
dbug: IdentityServer4.Startup[0]
Using Identity.External as default ASP.NET Core scheme for sign-in
dbug: IdentityServer4.Startup[0]
Using Identity.External as default ASP.NET Core scheme for sign-out
dbug: IdentityServer4.Startup[0]
Using Identity.Application as default ASP.NET Core scheme for challenge
dbug: IdentityServer4.Startup[0]
Using Identity.Application as default ASP.NET Core scheme for forbid
Hosting environment: Development
Content root path: C:\Users\Admin\Downloads\Programming\IDS\Server
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 OPTIONS http://localhost:5000/Account/Login?returnUrl=http://localhost:5000/connect/authorize/callback?client_id=ce&redirect_uri=http%3A%2F%2Flocalhost%3A5050&response_type=id_token%20token&scope=openid%20profile%20CE&nonce=N0.90507026110735561540718014359&state=15407087903260.1454827167180146
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 20.8366ms 204
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 POST http://localhost:5000/Account/Login?returnUrl=http://localhost:5000/connect/authorize/callback?client_id=ce&redirect_uri=http%3A%2F%2Flocalhost%3A5050&response_type=id_token%20token&scope=openid%20profile%20CE&nonce=N0.90507026110735561540718014359&state=15407087903260.1454827167180146 application/json 61
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
dbug: IdentityServer4.Hosting.CorsPolicyProvider[0]
CORS request made for path: /Account/Login from origin: http://localhost:5001
dbug: IdentityServer4.Hosting.CorsPolicyProvider[0]
CorsPolicyService allowed origin: http://localhost:5001
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
Policy execution successful.
dbug: IdentityServer4.Startup[0]
Login Url: http://localhost:5001/login
dbug: IdentityServer4.Startup[0]
Login Return Url Parameter: ReturnUrl
dbug: IdentityServer4.Startup[0]
Logout Url: /Account/Logout
dbug: IdentityServer4.Startup[0]
ConsentUrl Url: /consent
dbug: IdentityServer4.Startup[0]
Consent Return Url Parameter: returnUrl
dbug: IdentityServer4.Startup[0]
Error Url: /home/error
dbug: IdentityServer4.Startup[0]
Error Id Parameter: errorId
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Route matched with {action = "Login", controller = "Account"}. Executing action Server.Controllers.AccountController.Login (Server)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method Server.Controllers.AccountController.Login (Server) with arguments (Server.Dto.Login) - Validation state: Valid
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.1.4-rtm-31024 initialized 'DbContext' using provider 'Pomelo.EntityFrameworkCore.MySql' with options: None
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (88ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
SELECT `u`.`Id`, `u`.`AccessFailedCount`, `u`.`ConcurrencyStamp`, `u`.`Email`, `u`.`EmailConfirmed`, `u`.`LockoutEnabled`, `u`.`LockoutEnd`, `u`.`NormalizedEmail`, `u`.`NormalizedUserName`, `u`.`PasswordHash`, `u`.`PhoneNumber`, `u`.`PhoneNumberConfirmed`, `u`.`SecurityStamp`, `u`.`TwoFactorEnabled`, `u`.`UserName`
FROM `AspNetUsers` AS `u`
WHERE `u`.`NormalizedUserName` = @__normalizedUserName_0
LIMIT 1
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (6ms) [Parameters=[@__user_Id_0='?' (Size = 255)], CommandType='Text', CommandTimeout='30']
SELECT `uc`.`Id`, `uc`.`ClaimType`, `uc`.`ClaimValue`, `uc`.`UserId`
FROM `AspNetUserClaims` AS `uc`
WHERE `uc`.`UserId` = @__user_Id_0
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (30ms) [Parameters=[@__userId_0='?' (Size = 255)], CommandType='Text', CommandTimeout='30']
SELECT `role`.`Name`
FROM `AspNetUserRoles` AS `userRole`
INNER JOIN `AspNetRoles` AS `role` ON `userRole`.`RoleId` = `role`.`Id`
WHERE `userRole`.`UserId` = @__userId_0
dbug: IdentityServer4.Hosting.IdentityServerAuthenticationService[0]
Augmenting SignInContext
dbug: IdentityServer4.Hosting.IdentityServerAuthenticationService[0]
Adding idp claim with value: local
dbug: IdentityServer4.Hosting.IdentityServerAuthenticationService[0]
Adding amr claim with value: pwd
dbug: IdentityServer4.Hosting.IdentityServerAuthenticationService[0]
Adding auth_time claim with value: 1540720363
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10]
AuthenticationScheme: Identity.Application signed in.
info: Server.Controllers.AccountController[0]
User logged in.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action method Server.Controllers.AccountController.Login (Server), returned result Microsoft.AspNetCore.Mvc.OkResult in 25685.0508ms.
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
Executing HttpStatusCodeResult, setting HTTP status code 200
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action Server.Controllers.AccountController.Login (Server) in 26016.4477ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 26239.7052ms 200
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/connect/authorize/callback?client_id=ce&redirect_uri=http%3A%2F%2Flocalhost%3A5050&response_type=id_token%20token&scope=openid%20profile%20CE&nonce=N0.90507026110735561540718014359&state=15407087903260.1454827167180146
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Request path /connect/authorize/callback matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint for /connect/authorize/callback
dbug: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint[0]
Start authorize callback request
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
Identity.Application was not authenticated. Failure message: Unprotect ticket failed
dbug: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint[0]
No user present in authorize request
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
Start authorize request protocol validation
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
client configuration validation for client ce succeeded.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
info: IdentityServer4.Endpoints.AuthorizeCallbackEndpoint[0]
ValidatedAuthorizeRequest
{
"ClientId": "ce",
"ClientName": "ce",
"RedirectUri": "http://localhost:5050",
"AllowedRedirectUris": [
"http://localhost:5050"
],
"SubjectId": "anonymous",
"ResponseType": "id_token token",
"ResponseMode": "fragment",
"GrantType": "implicit",
"RequestedScopes": "openid profile CE",
"State": "15407087903260.1454827167180146",
"Nonce": "N0.90507026110735561540718014359",
"Raw": {
"client_id": "ce",
"redirect_uri": "http://localhost:5050",
"response_type": "id_token token",
"scope": "openid profile CE",
"nonce": "N0.90507026110735561540718014359",
"state": "15407087903260.1454827167180146"
}
}
info: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
Showing login: User is not authenticated
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 970.0804ms 302

这里是StartUp.cs的关键部分

services.AddDbContext<DbContext>(options =>
options.UseMySql("server=10.1.1.228;database=IdentityService;user=admin;password=admin"));

services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});

services.AddIdentity<SsoUser, IdentityRole>(options =>
{
options.Tokens.ChangePhoneNumberTokenProvider = "Phone";

options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<DbContext>()
.AddDefaultTokenProviders();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddIdentityServer(x =>
{
x.IssuerUri = "http://localhost:5000";
x.UserInteraction.LoginUrl = "http://localhost:5001/login";
x.Cors.CorsPaths.Add(new PathString("/Account/Login"));
}
).AddDeveloperSigningCredential()
.AddAspNetIdentity<SsoUser>()
.AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources())
.AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
.AddInMemoryClients(InMemoryConfiguration.Clients())
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddCorsPolicyService<CorsPolicyService>();

services.AddAuthentication().AddCookie();

最佳答案

主要原因是Angular没有给IdentityServer发送cookie。

在 UI 中,将 withCredentials: true 添加到 httpClient 选项。

在IdentityServer的Startup.cs中,添加:

services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins("UI Domain")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});

(答案从问题中移出到 CW 帖子中)

关于identityserver4 - IdentityServer 4 的自定义登录 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53030506/

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