【问题标题】:IdentityServer4 ASP.NET Core Identity does not redirect back to clientIdentityServer4 ASP.NET Core Identity 不会重定向回客户端
【发布时间】:2019-01-12 00:09:53
【问题描述】:

我有带有 Asp.Net Core Identity 的基本 IdentityServer4。重定向到登录页面并登录后,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?}");
        });
    }

控制台有警告,但所有网址都正确Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3] Failed to determine the https port for redirect.

任何想法我做错了什么?

【问题讨论】:

  • 那么会发生什么?如,浏览器显示什么而不是重定向?
  • @KirkLarkin 填写有效的电子邮件和密码后,单击“登录”按钮并登录。但我停留在注册页面上,没有其他任何事情发生。这是控制台的输出:https://1drv.ms/t/s!AjecY1mAQaKShpU-11yR5k0_Go6ZBg
  • @Michal,你能解决这个问题吗?我在示例应用中得到了相同的响应。
  • @terryt 不幸的是,我使用了他们的示例模板
  • authorization_code 授权应该仍然有效。很难理解为什么重定向在使用 ASPNET 身份登录时不起作用,但重定向在 IS4 TestUser 登录中起作用。

标签: c# identityserver4 asp.net-core-identity


【解决方案1】:

请从您的代码中将 http 更改为 https 身份服务器仅适用于 https RedirectUris = { "http://localhost:50309/signin-oidc" },

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

而且在您的 MVC 客户端中,您也需要更改它。 options.Authority = "http://localhost:5000";

【讨论】:

  • 这似乎没有记录在任何地方,而且我整天都在寻找。谢谢!
  • 是的,我也相信,文档现在需要改进,很难遵循
【解决方案2】:

也许问题出在这里:

https://github.com/aspnet/Announcements/issues/301

您正在代码中设置 https 重定向,但未指定任何端口。

尝试添加或删除配置

app.UseHttpsRedirection();

【讨论】:

  • 配置或删除app.UseHttpsRedirection ();后警告消失,但重定向仍然不起作用。
  • 您是否在任何地方执行重定向?
  • 我不确定你的意思。何时何地重定向?
  • 我要去客户端 URL。我没有登录,我将被重定向到 IdentityServer。我登录并且 IdentityServer 必须将我重定向回来。这适用于我不使用 Asp.Net Identity 的示例。它必须以同样的方式工作。我应该在哪里进行手动重定向?
【解决方案3】:

我在登录后遇到了同样的重定向问题。就我而言,我在 IdentityServer 项目的 launchsettings.json 中删除了 SSL 端点。 IMO 在本地测试时不使用 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"
});

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

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2017-04-20
    • 2021-02-28
    • 2017-09-01
    • 2021-04-11
    • 2019-07-19
    • 1970-01-01
    • 2020-07-06
    • 2019-05-01
    相关资源
    最近更新 更多