[英]Identity Server 4 is not redirecting to Angular app after login
我在 angular 中使用oidc-client
。 遵循本教程
import { UserManager, UserManagerSettings, User } from 'oidc-client';
我的客戶:
export function getClientSettings(): UserManagerSettings {
return {
authority: 'https://localhost:44305/',
client_id: 'angular_spa',
redirect_uri: 'http://localhost:4200/auth-callback',
post_logout_redirect_uri: 'http://localhost:4200/',
response_type: 'id_token token',
scope: 'openid profile api1',
filterProtocolClaims: true,
loadUserInfo: true,
automaticSilentRenew: false
};
在身份服務器中,我使用的是Assembly Microsoft.AspNetCore.Identity.UI, Version=2.1.3.0
我正在添加這樣的默認身份:
[assembly:
HostingStartup(typeof(WebApp.Areas.Identity.IdentityHostingStartup))]
namespace WebApp.Areas.Identity
{
public class IdentityHostingStartup: IHostingStartup {
public void Configure(IWebHostBuilder builder) {
builder.ConfigureServices((context, services) => {
services.AddDbContext < WebAppContext > (options =>
options.UseSqlite(context.Configuration.GetConnectionString("WebAppContextConnection")));
services.AddDefaultIdentity < WebAppUser > ()
.AddEntityFrameworkStores < WebAppContext > ();
});
}
}
}
WebAppUser
派生自IdentityUser
啟動.cs:
public class Startup
{
private ILogger<DefaultCorsPolicyService> _logger;
private IHostingEnvironment _env;
public Startup(ILoggerFactory loggerFactory, IHostingEnvironment env)
{
_logger = loggerFactory.CreateLogger<DefaultCorsPolicyService>();
_env = env;
}
private static void SetupIdentityServer(IdentityServerOptions identityServerOptions)
{
identityServerOptions.UserInteraction.LoginUrl = new PathString("/Identity/Account/Login");
// identityServerOptions.Cors.CorsPolicyName = "CorsPolicy";
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.WithOrigins("https://localhost:44305")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// services.AddMvc();
var cors = new DefaultCorsPolicyService(_logger)
{
AllowAll = true
};
var cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "mycert.pfx"), "xxxxx");
services.AddIdentityServer(SetupIdentityServer)//SetupIdentityServer
.AddSigningCredential(cert)
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
// .AddTestUsers(TestUsers.Users)
.AddInMemoryIdentityResources(Config.GetIdentityResources());
services.AddSingleton<ICorsPolicyService>(cors);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//loggerFactory.AddConsole();
app.UseDeveloperExceptionPage();
app.Map("/api", api =>
{
api.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
api.UseAuthentication();
api.Run(async context =>
{
var result = await context.AuthenticateAsync("api");
if (!result.Succeeded)
{
context.Response.StatusCode = 401;
return;
}
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject("API Response!"));
});
});
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
//Run these PMC commands after this.
//Add - Migration CreateIdentitySchema
//Update - Database
}
}
在身份服務器 4 中,我啟用了https
。 所以問題是,如果我嘗試使用受保護的URL
我會從我的 Angular 應用程序導航到身份服務登錄頁面。 看起來它正在針對數據庫中的用戶正確進行身份驗證。 但隨后它只會刷新登錄頁面,不會重定向到回調URL
。
這里有一些日志可能會有所幫助
2019 - 03 - 07 01: 19: 30.553 - 06: 00[INF] 啟動 IdentityServer4 版本 2.3 .2 .0 2019 - 03 - 07 01: 19: 30.632 - 06: 00[INF] 你正在使用內存版本持久授權存儲。這將僅在內存中存儲同意決定、授權代碼、刷新和引用令牌。如果您在生產中使用這些功能中的任何一個,您希望切換到不同的存儲實現。 2019 - 03 - 07 01: 19: 30.643 - 06: 00[INF] 使用 IdentityServer 的默認身份驗證方案 idsrv 2019 - 03 - 07 01: 19: 30.644 - 06: 00[DBG] 默認使用 ids.NET Corerv身份驗證方案 2019 - 03 - 07 01: 19: 30.644 - 06: 00[DBG] 使用 Identity.External 作為默認 ASP.NET Core 方案進行登錄 - 2019 - 03 - 07 01: 19: 30.645 - 06: 00[ DBG] 使用 Identity.External 作為默認 ASP.NET Core 方案進行注銷 2019-03-07 01:19:30.645-06:00[DBG] 使用 idsrv 作為默認 ASP.NET Core 方案進行挑戰 2019-03-07 01: 19: 30.645 - 06: 00[DBG] 使用 idsrv 作為默認 ASP.NET Core 方案 forbid 2019 - 03 - 07 01: 19: 31.463 - 06: 00[DBG] CORS 請求為路徑:/.well-已知/openid - 來自 origin 的配置:http://localhost:4200 2019 - 03 - 07 01: 19: 31.468 - 06: 00[DBG] AllowAll true,所以 origin: http://localhost:4200 is allowed 2019 - 03 - 07 01:19:31.468 - 06:00[DBG] CorsPolicyService 允許來源:http://本地主機:4200 2019 - 03 - 07 01: 19: 31.482 - 06: 00[DBG] 登錄網址:/Identity/Account / Login 2019 - 03 - 07 01: 19: 31.482 - 06: 00[DBG] 登錄返回網址參數:Return19rl -03 07 01: 19: 31.482 - 06: 00[DBG] 注銷網址:/Account/Logout 2019 - 03 - 07 01: 19: 31.482 - 06: 00[DBG] ConsentUrl Url: /consent 19 - 03019 : 31.482 - 06: 00[DBG] 同意返回 URL 參數:returnUrl 2019 - 03 - 07 01: 19: 31.482 - 06: 00[DBG] 錯誤 URL:/home/error 2019 - 03 - 019:19:01 06: 00[DBG] 錯誤 ID 參數:errorId 2019 - 03 - 07 01: 19: 31.497 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票失敗 2019 - 03 - 07:01:1.59 06:00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01:19:31.553 - 06:00[DBG] 請求路徑/.well-known/openid-配置與端點類型發現匹配2019 - 03 - 07 01: 19: 31.569 - 06: 00[DBG] 端點啟用:發現,成功創建處理程序:IdentityServer4.Endpo ints.DiscoveryEndpoint 2019 - 03 - 07 01: 19: 31.569 - 06: 00[INF] 調用 IdentityServer 端點:IdentityServer4.Endpoints.DiscoveryEndpoint for / .well -known / openid - configuration 2019 - 03 - 019:073: - 06: 00[DBG] 開始發現請求 2019 - 03 - 07 01: 19: 31.885 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01:19:5 -306。 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票證失敗 2019-03-07 01:19:31.885-06:00[DBG] 請求路徑/連接/授權匹配端點類型授權 2019-03-07 01: 19:31.893 - 06:00[DBG] 端點啟用:授權,成功創建處理程序:IdentityServer4.Endpoints.AuthorizeEndpoint 2019 - 03 - 07 01:19:31.893 - 06:00[INF] 調用 IdentityEndpoints.AuthorizeEndpoint:IdentityServer4Endpoint for / connect / authorize 2019 - 03 - 07 01: 19: 31.904 - 06: 00[DBG] 開始授權請求 2019 - 03 - 07 01: 19: 31.919 - 06: 00[ INF] idsrv 未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01: 19: 31.935 - 06: 00[DBG]授權請求中沒有用戶2019 - 03 - 07 01: 19: 30.945 - 00 [DBG] 開始授權請求協議驗證 2019 - 03 - 07 01: 19: 31.983 - 06: 00 [DBG] 客戶端angular_spa 的客戶端配置驗證成功。 2019 - 03 - 07 01: 19: 32.069 - 06: 00[DBG] 調用自定義驗證器:IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator 2019 - 03 - 07 01: 19: 32.099 - 06: 06: 06: 驗證客戶端請求驗證"angular_spa", "ClientName": "Angular 4 Client", "RedirectUri": " http://localhost:4200/auth-callback ", "AllowedRedirectUris": [" http://localhost:4200/auth-callback " , " http://localhost:4200/silent- refresh.html "], "SubjectId": "anonymous", "ResponseType": "id_token token", "ResponseMode": "fragment", "GrantType": "implicit" , "RequestedScopes": "openid profile api1", "State": "cd6df66e397546d3aab62533de28a2d2", "UiLocales": null, "Nonce": "8b3af6331d784e9a9cad076555f16e397546d3aab62533de28a2d2", "Nonce": "8b3af6331d784e9a9cad076555f16176555f16176555f16174", "DisplayProfessential", "NULL , "MaxAge": null, "LoginHint": null, "SessionId": null, "Raw": { "client_id": "angular_spa", "redirect_uri": " http://localhost:4200/auth-callback ", "response_type": "id_token token", "scope": "openid profi le api1", "state": "cd6df66e397546d3aab62533de28a2d2", "nonce": "8b3af6331d784e9a9cad076555f16174" }, "$type": "AuthorizeRequestValidationLog: -019: -0301 登錄:061019:06120101用戶未通過身份驗證 2019 - 03 - 07 01: 19: 32.154 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票失敗 2019 - 03 - 07 01: 19: 32.155 - [INRF]0未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01:19:32.628 - 06:00[INF] AuthenticationScheme:Identity.External 已注銷。 2019 - 03 - 07 01: 19: 40.844 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票失敗 2019 - 03 - 07 01: 19: 40.844 - 06: 00.idsrv [INF 未通過身份驗證失敗消息:取消保護票證失敗 2019 - 03 - 07 01:19:41.517 - 06:00[INF] AuthenticationScheme:Identity.Application 已登錄。 2019 - 03 - 07 01: 19: 41.518 - 06: 00[INF] 用戶登錄。 2019 - 03 - 07 01: 19: 41.528 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01: 19: 41.528 - 06: 00.idsrv [INF 未通過身份驗證失敗消息:取消保護票失敗 2019 - 03 - 07 01: 19: 41.528 - 06: 00[DBG] 請求路徑/連接/授權/回調匹配端點類型授權 2019 - 03 - 07 01: 19: 41.529 - 06:0 [DBG] 端點啟用:授權,成功創建處理程序:IdentityServer4.Endpoints.AuthorizeCallbackEndpoint 2019 - 03 - 07 01:19:41.529 - 06:00[INF] 調用 IdentityServer 端點:IdentityServer4.Endpoints.AuthorizeCallbackEndpoint for / callback / authorize 2019 - 03 - 07 01: 19: 41.535 - 06: 00[DBG] 開始授權回調請求 2019 - 03 - 07 01: 19: 41.536 - 06: 00[INF] idsrv is not authentication.Un19ticket message - 03 - 07 01: 19: 41.541 - 06: 00[DBG] 沒有用戶出現在授權請求中 2019 - 03 - 07 01: 19: 41.541 - 06: 00[DBG] 開始作者 ize 請求協議驗證 2019-03-07 01:19:41.541-06:00[DBG] 客戶端 angular_spa 的客戶端配置驗證成功。 2019 - 03 - 07 01: 19: 41.541 - 06: 00[DBG] 調用自定義驗證器:IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator 2019 - 03 - 07 01: 19: 41.541 - 06: 06:{06} 驗證請求驗證[驗證客戶端] "angular_spa", "ClientName": "Angular 4 Client", "RedirectUri": " http://localhost:4200/auth-callback ", "AllowedRedirectUris": [" http://localhost:4200/auth-callback " , " http://localhost:4200/silent- refresh.html "], "SubjectId": "anonymous", "ResponseType": "id_token token", "ResponseMode": "fragment", "GrantType": "implicit" , "RequestedScopes": "openid profile api1", "State": "cd6df66e397546d3aab62533de28a2d2", "UiLocales": null, "Nonce": "8b3af6331d784e9a9cad076555f16e397546d3aab62533de28a2d2", "Nonce": "8b3af6331d784e9a9cad076555f16176555f16176555f16174", "DisplayProfessential", "NULL , "MaxAge": null, "LoginHint": null, "SessionId": null, "Raw": { "client_id": "angular_spa", "redirect_uri": " http://localhost:4200/auth-callback ", "response_type": "id_token token", "scope": "openid profi le api1", "state": "cd6df66e397546d3aab62533de28a2d2", "nonce": "8b3af6331d784e9a9cad076555f16174" }, "$type": "AuthorizeRequestValidationLog: -019" -0401 登錄:0704019:040101用戶未通過身份驗證 2019 - 03 - 07 01: 19: 41.552 - 06: 00[INF] idsrv 未通過身份驗證。失敗消息:取消保護票失敗 2019 - 03 - 07 01: 19: 41.553 - [INRF]0未通過身份驗證。失敗消息:取消保護票證失敗 2019 - 03 - 07 01:19:41.553 - 06:00[INF] AuthenticationScheme:Identity.External 已注銷。
抱歉,我試圖正確格式化日志,但沒有奏效。
更新
我的服務器端配置是這樣的
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientSecrets =
{
new Secret("superSecretPassword".Sha256())
},
ClientId = "angular_spa",
ClientName = "Angular 4 Client",
AllowedGrantTypes = GrantTypes.ImplicitAndClientCredentials , //implicit
AllowedScopes = new List<string> { "openid", "profile", "userInfo", "api1" },
//AllowedScopes = new List<string> { StandardScopes.OpenId, StandardScopes.Profile, StandardScopes.Email },
RedirectUris = new List<string> {"http://localhost:4200/auth-callback", "http://localhost:4200/silent-refresh.html"},
PostLogoutRedirectUris = new List<string> { "http://localhost:4200/" },
AllowedCorsOrigins = new List<string> { "http://localhost:4200" },
AllowAccessTokensViaBrowser = true,
Enabled = true,
AllowOfflineAccess = true
}
};
}
public static List<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile() // <-- usefull
};
}
}
我的項目結構是這樣的
它沒有任何控制器。 應該有嗎?
更新 2看起來我想出了什么問題。
returnUrl
在POST
方法上沒有正確解析。 它將作為完整的URL
。 如果我強制它使用正確的返回URL
它就可以工作
var redirect_uri = HttpUtility.ParseQueryString(returnUrl).Get("redirect_uri");
我如上所述並在重定向函數中使用了變量“redirect_uri”。 它有效,但它看起來像一個黑客。 它應該自動得到正確的東西嗎?
有了這個,我在 Angular 端出現“無響應狀態”錯誤,重定向后oidc-client
沒有用戶。
更新
看起來我正在使用一些不同的nuget
包。 HttpContext.SignInAsync
具有以下構造函數。
我的HttpContext
似乎定義在
Microsoft.AspNetCore.Mvc.RazorPages
看起來我有錯誤的 Nugets 或其他東西。 我也在嘗試提供適當的 ClaimsPrincipal 但不起作用。
我看到關於 returnUrl 和 redirect_uri 之間的區別有些混亂。 盡管最終目標是重定向到客戶端的 redirect_uri,但在身份驗證后,客戶端必須實際重定向到授權端點以進行進一步處理(因此 url 不同的原因)。 您根本不需要更改 returnUrl 並且可以保持原樣。
您現在面臨的問題是您在身份驗證成功后沒有調用HttpContext.SignInAsync
。 SignInAsync
方法用於管理帶有用戶信息的 cookie,該 cookie 告訴 returnUrl 處的端點用戶已成功通過身份驗證,並且可以將令牌返回給 redirect_uri。 SignInAsync
有很多重載,但我發現最容易使用的是HttpContext.SignInAsync(string subject, params Claim[] claims)
SignInAsync
HttpContext.SignInAsync(string subject, params Claim[] claims)
。 完成此操作后,您應該能夠完成身份驗證。
身份服務器配置
將 RedirectUris 設置為您的 Angular 應用程序托管 url。
角度應用
openIDImplicitFlowConfiguration.redirect_url = this.oidcConfigService.clientConfiguration.redirect_url;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.