IdentityServer4 ASP.NET Core Identity无法将客户端重定向回去。

7

我有一个基本的IdentityServer4和Asp.Net Core Identity。在重定向到登录页面并登录后,IdentityServer没有将我重定向回客户端。

IdentityServer配置:

 new Client
            {
                ClientId = "mvc",
                ClientName = "MVC Client",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },

                RedirectUris = { "http://localhost:50309/signin-oidc" },
                PostLogoutRedirectUris = { "http://localhost:50309/signout-callback-oidc" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api1"
                },
                AllowOfflineAccess = true
            }

IdentityServer 启动:

public void ConfigureServices(IServiceCollection services)
    {
        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<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddDefaultUI();

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

        services.Configure<IISOptions>(iis =>
        {
            iis.AuthenticationDisplayName = "Windows";
            iis.AutomaticAuthentication = false;
        });

        var builder = services.AddIdentityServer(options =>
        {
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;
            options.UserInteraction.LoginUrl = "/Identity/Account/Login";
            options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
        })
            .AddSigningCredential("CN=tst")
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<IdentityUser>();
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseIdentityServer();
        app.UseCookiePolicy();
        //app.UseAuthentication();

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

MVC客户端启动:

  public void ConfigureServices(IServiceCollection services)
    {
        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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";

                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Add("api1");
                options.Scope.Add("offline_access");
            });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseAuthentication();

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

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

控制台中出现了一个警告,但所有的URL都是正确的 Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] 无法确定重定向的https端口。

你有什么想法是我做错了什么吗?


那么到底发生了什么?也就是说,浏览器显示什么而不是重定向? - Kirk Larkin
@KirkLarkin 在填写有效的电子邮件和密码后,点击“登录”按钮并登录。但我仍停留在注册页面,没有发生任何其他情况。这是控制台输出的结果: https://1drv.ms/t/s!AjecY1mAQaKShpU-11yR5k0_Go6ZBg - Michal
@Michal,你解决了吗?我在我的示例应用程序中得到了相同的响应。 - terryt
很遗憾,我没有这样做。我使用了他们的示例模板。 - Michal
授权码授权应该仍然有效。只是很难理解为什么在使用ASPNET Identity登录时重定向不起作用,但在IS4 TestUser登录中重定向可以正常工作。 - Ronald Abellano
3个回答

2

这似乎在任何地方都没有记录,并且是我整天搜寻的东西。谢谢! - jmgardn2
是的,我也认为,文档需要改进,现在很难遵循。 - Dheeraj Kumar

0

在配置或删除 app.UseHttpsRedirection(); 后,警告消失了,但重定向仍然无法正常工作。 - Michal
你是否在任何地方执行重定向? - Noel Santos
我不确定你的意思。重定向到哪里和何时? - Michal
我要前往客户端 URL。我没有登录,将被重定向到 IdentityServer。我登录并且 IdentityServer 必须将我重定向回来。此功能在我不使用 Asp.Net Identity 的示例中有效。它必须与其一样工作。我应该在哪里进行手动重定向? - Michal

0

我在登录后重定向方面遇到了同样的问题。在我的情况下,我从IdentityServer项目的launchsettings.json中删除了SSL端点。在本地测试时不使用SSL应该是可以的。但这正是导致我的问题的原因。重新添加SSL端点解决了这个问题。

即:

{
  "profiles": {
    "SelfHost": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001"
    },
    "<YOUR-PROJECT-NAME>": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001"
    }
  }
}

我还需要在Startup类中更新issuerUri。

services.AddIdentityServer(options => 
{
    options.IssuerUri = "https://localhost:5001"
});

我在文档中也找不到任何关于这个的信息。我花了几个小时来解决这个问题,但是当这种情况发生时,日志中没有错误,即使配置了详细日志记录,也无法追踪导致它发生的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接