简体   繁体   中英

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. Now when an unauthorized user tries to access the application, AD authentication is failing and going to OPENIDConnect Exception page. But All I need is to navigate user to custom page AccessDenied page in my application.

Expected: When User is not Authenticated. He should be navigate to /Home/AccessDeined Page.

Actual: Exception Page: Signin-Oidc Exception Page

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

"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();
    }

Specifying the path on CookieAuthenticationOptions in Startups.cs will work. Please use the below code and define your path in the PathString

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM