【问题标题】:ASP.NET Core 5: OpenIDConnect breaking default/root routeASP.NET Core 5:OpenIDConnect 打破默认/根路由
【发布时间】:2021-10-17 06:03:29
【问题描述】:

我有一个 ASP.NET Core 5 MVC 应用程序,在 PageController 中设置了这样的默认/根路由:

[AllowAnonymous]
[Route("/")]
public IActionResult __Home(int? parent)
{
    return View();
}

在我添加 OpenIdConnect 身份验证之前,这一切正常。之后,根 (/) 页面不再路由到PageController 中的__Home,它只是返回一个空白页面。所有其他页面路由都很好。

当我注释掉这个时:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration, "AzureAdB2C");

然后/ 再次工作,所以我知道这与身份验证有关。如您所见,我在该操作中添加了[AllowAnonymous]

我的创业公司有这个:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}"
    );
});

关于如何解决这个问题的任何想法?我知道在这样一个奇怪的控制器/动作中使用默认/根路由是非常规的,但这是有原因的,所以我希望它仍然可以工作。

更多信息:

我发现如果我将app.UseEndpoints 移到app.UseAuthentication 上方,就会显示主页。然而,在登录(使用 B2C)后,它进入了一个无限循环(即身份验证令牌没有粘住?)。

编辑:我的 Startup.cs 类

using Blank.Models;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;

namespace Blank
{
    public class Startup
    {
        private readonly AppSettings appSettings = null;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            this.appSettings = new AppSettings();
            this.Configuration.Bind(this.appSettings);
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration, "AzureAdB2C");

            services.AddSession();

            services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C"));

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });


            services.Configure<AppSettings>(this.Configuration);

            services.AddEntityFrameworkSqlServer().AddDbContext<BlankDBContext>(
               Options => Options.UseSqlServer(Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(this.Configuration, "BlankDatabase"))
                );
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();


            app.UseSession();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Page}/{action=Index}/{id?}");
            });

        }
    }

}

编辑 2

我认为app.UseAuthentication() 正在破坏/返回空白页,因为当我将以下代码放在app.UseAuthentication() 之前时,我会在主页上看到一些东西,如果它在之后则为空白:

app.Use(async (context, next) =>
{
    var endpoint = context.GetEndpoint();

    if (endpoint != null)
    {
        await context.Response.WriteAsync("<html> Endpoint :" + endpoint.DisplayName + " <br>");

        if (endpoint is RouteEndpoint routeEndpoint)
        {
            await context.Response.WriteAsync("RoutePattern :" + routeEndpoint.RoutePattern.RawText + " <br>");
        }

    }
    else
    {
        await context.Response.WriteAsync("End point is null");
    }

    await context.Response.WriteAsync("</html>");
    await next();
});

所以也许这与我的身份验证有关?这是我的appsettings.json

"AzureAdB2C": {
    "Instance": "https://abc.b2clogin.com",
    "Domain": "abc.onmicrosoft.com",
    "ClientId": "62...f1",
    "TenantId": "7e...ae",
    "SignUpSignInPolicyId": "B2C_1_SUSI",
    "SignedOutCallbackPath": "/"
},

【问题讨论】:

  • CallbackPath 设置了什么?
  • 我已经添加了整个启动类...关于 CallbackPath,我在 B2C 中有 / 和 /signin-oidc 设置
  • 我问的是回调路径,因为您使用Configuration 配置了身份验证方案.AddMicrosoftIdentityWebApp(Configuration, ...)。这意味着这些值实际上位于appsettings.json(或任何其他来源)中。无论如何,如果你设置了错误的回调路径(或者它与端点冲突),AuthenticationMiddleware 将拦截请求并且请求永远不会到达控制器。这就是为什么您不应该将/ 设置为回调路径。
  • 啊,好的,对不起,我的意思是在 B2C 应用注册中重定向 url 设置为 / 和 /signin-oidc。我的appsettings,json除了Instance、Domain、ClientId、TenantId和SignUpSignInPolicyId之外只有SignedOutCallbackPath:"/"

标签: asp.net-core asp.net-core-mvc openid-connect asp.net-core-5.0 microsoft-identity-web


【解决方案1】:

原来问题出在我的appsettings.json

"SignedOutCallbackPath": "/"

删除此问题解决了问题,主页现在可以正确加载。

【讨论】:

    猜你喜欢
    • 2020-05-31
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2021-12-18
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多