用户 AD 身份验证失败时如何导航到自定义访问被拒绝页面(具有 OpenIDConnect Azure AD 身份验证的 .net 3.1 core)

2024-05-21

我有一个 .Net core 3.1 Web 应用程序,通过在 Azure 中设置应用服务注册并分配用户来实现 AD 身份验证。现在,当未经授权的用户尝试访问应用程序时,AD 身份验证会失败并转到 OPENIDConnect 异常页面。但我需要的只是将用户导航到我的应用程序中的自定义页面 AccessDenied 页面。

预期的:当用户未经过身份验证时。他应该导航到 /Home/AccessDeined 页面。

Actual:异常页面:Signin-Oidc 异常页面 https://i.stack.imgur.com/Uf9w4.png

启动.cs

    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.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
        {
            options.Authority = options.Authority + "/v2.0/";
            options.TokenValidationParameters.ValidateIssuer = false;
            //options.AccessDeniedPath = new PathString("/Home/AccessDenied");
            options.ResponseType = "id_token code";
            options.Events.OnAuthenticationFailed = context =>
            {

                context.Response.Redirect("/Home/AccessDenied");
                context.HandleResponse();

                return Task.FromResult(0);
            };                
        });

        services.AddControllersWithViews();
        services.AddHttpClient();


        services.AddSession();
        //services.Configure<CookieTempDataProviderOptions>(options =>
        //{
        //    options.Cookie.IsEssential = true;
        //});

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

        services.AddLogging();
        services.AddProgressiveWebApp();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        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.UseCookiePolicy();
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();
        app.UseSession();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
           

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

应用程序设置.Json

"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "XXXXXXXXX",
"TenantId": "XXXXXXXXXXXXXXXXXXXXX",
"ClientId": "XXXXXXXXXXXXXXXXXXXXXX",
"ClientSecret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"CallbackPath": "/signin-oidc"

},

HomeController.cs

[AllowAnonymous]
    public IActionResult AccessDenied()
    {
        return View();
    }

在 CookieAuthenticationOptions 中指定路径Startups.cs将工作。请使用下面的代码并在 PathString 中定义您的路径

services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options => {
    options.AccessDeniedPath = new PathString("/Home/CustomAccessDenied");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用户 AD 身份验证失败时如何导航到自定义访问被拒绝页面(具有 OpenIDConnect Azure AD 身份验证的 .net 3.1 core) 的相关文章

随机推荐