简体   繁体   English

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

[英]How to Navigate to Custom Access Denied Page when AD Authentication failed for user (.net 3.1 core with OpenIDConnect Azure AD Authentication)

I have an .Net core 3.1 web application where I implemented AD Authentication by setting up the App Services registration in Azure and also assigned users.我有一个 .Net 核心 3.1 Web 应用程序,我通过在 Azure 中设置应用服务注册并分配用户来实现 AD 身份验证。 Now when an unauthorized user tries to access the application, AD authentication is failing and going to OPENIDConnect Exception page.现在,当未经授权的用户尝试访问应用程序时,AD 身份验证失败并转到 OPENIDConnect 异常页面。 But All I need is to navigate user to custom page AccessDenied page in my application.但我所需要的只是将用户导航到我的应用程序中的自定义页面 AccessDenied 页面。

Expected: When User is not Authenticated.预期:当用户未通过身份验证时。 He should be navigate to /Home/AccessDeined Page.他应该导航到 /Home/AccessDeined Page。

Actual: Exception Page: Signin-Oidc Exception Page实际:异常页面: Signin-Oidc 异常页面

Startup.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?}");
        });
    }

Appsettings.Json Appsettings.Json

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

}, },

HomeController.cs家庭控制器.cs

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

Specifying the path on CookieAuthenticationOptions in Startups.cs will work.Startups.cs CookieAuthenticationOptions 上指定路径将起作用。 Please use the below code and define your path in the PathString请使用以下代码并在 PathString 中定义您的路径

services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options => {
    options.AccessDeniedPath = new PathString("/Home/CustomAccessDenied");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC Core 3.1 中的自定义用户数据与 Azure AD 身份验证? - Custom User data in ASP.NET MVC Core 3.1 with Azure AD Authentication? 使用Azure AD OpenIdConnect和自定义中间件的ASP NET Core身份验证中的Cookie到期 - Cookie expiry in ASP NET Core Authentication using Azure AD OpenIdConnect and custom middleware ASP.NET Core 3.1 Azure AD 身份验证抛出 OptionsValidationException - ASP.NET Core 3.1 Azure AD Authentication throws OptionsValidationException ASP.NET CORE 3.1:Azure AD 身份验证在 EDGE 中失败。 身份验证期间无限重定向循环和页面重新加载 - ASP.NET CORE 3.1: Azure AD Authentication fails in EDGE. Infinite redirect loops and page reloads during authentication 如何在使用 .NET Core 3.1 通过 Visual Studio 2019 开发 Azure 函数时使用 AD 身份验证 - How to use AD authentication while developing Azure Functions through Visual Studio 2019 using .NET Core 3.1 如何在 .NET Core 3.1 中使用 Azure AD Saml2 身份验证进行 SSO - How to use Azure AD Saml2 authentication for SSO in .NET Core 3.1 如何在 .NET Core 3.1 中检索 Azure AD 用户信息? - How to retrieve Azure AD user information in .NET Core 3.1? Azure AD中的自定义身份验证 - Custom authentication in Azure AD .Net Core Azure AD单租户认证 - .Net Core Azure AD single tenant Authentication Azure AD 认证与 .NET 核心 Web ZDB974238714CA8DE634A7CE1D083A14 - Azure AD Authentication with .NET Core Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM