ASP.net-core 3.0 - Is it possible to return custom error page when user is not in a policy?

北城以北 提交于 2020-05-16 07:51:50

问题


I'm creating an intranet website and I'm having some trouble with the authentication part. I would like to limit the access for a controller to users in a specific Active Directory Roles. If the user is not in the specified Roles, then it should redirect him to a custom error page.

Windows authentication is enabled. I've tried the following solutions :

I created a custom policy in my ConfigureServices method inside my Startup.cs :

 ...
 services.AddAuthorization(options =>
        {
            options.AddPolicy("ADRoleOnly", policy =>
            {
                policy.RequireAuthenticatedUser();
policy.RequireRole(Configuration["SecuritySettings:ADGroup"], Configuration["SecuritySettings:AdminGroup"]);
            });
        });
services.AddAuthentication(IISDefaults.AuthenticationScheme);

 ....

with inside my appsettings.json my active directory groups (not the one i'm really using of course) :

   "SecuritySettings": {
      "ADGroup": "MyDomain\\MyADGroup",
      "AdminGroup": "MyDomain\\MyAdminGroup"
 }}

and inside my Configure method :

...
 app.UseAuthorization();
 app.UseAuthentication();
 app.UseStatusCodePagesWithReExecute("/Home/ErrorCode/{0}");
...

I have the following controller :

 [Area("CRUD")]
 [Authorize(Policy = "ADRoleOnly")]
 public class MyController : Controller

I have a HomeController with the following method :

    [AllowAnonymous]
    public IActionResult ErrorCode(string id)
    {
        return View();
    }

but when I debug my site, this method is never reached.

If I'm a user inside one of the specified roles of my policy, it's all working as expected.

But if I'm not a member of the roles, I'm redirected to the default navigator page.

I would like to redirect to a custom error page. I thought that was the purpose of

   app.UseStatusCodePagesWithReExecute("/Home/ErrorCode/{0}");

回答1:


It will generate a 403 statuscode when the policy fails,app.UseStatusCodePagesWithReExecute does not detect 403:

UseStatusCodePagesWithReExecute is not working for forbidden (403)

You could write a custom middleware to deal with it :

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.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 403)
            {

                var newPath = new PathString("/Home/ErrorCode/403");
                var originalPath = context.Request.Path;
                var originalQueryString = context.Request.QueryString;
                context.Features.Set<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
                {
                    OriginalPathBase = context.Request.PathBase.Value,
                    OriginalPath = originalPath.Value,
                    OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
                });

                // An endpoint may have already been set. Since we're going to re-invoke the middleware pipeline we need to reset
                // the endpoint and route values to ensure things are re-calculated.
                context.SetEndpoint(endpoint: null);
                var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
                routeValuesFeature?.RouteValues?.Clear();

                context.Request.Path = newPath;
                try
                {
                    await next();
                }
                finally
                {
                    context.Request.QueryString = originalQueryString;
                    context.Request.Path = originalPath;
                    context.Features.Set<IStatusCodeReExecuteFeature>(null);
                }

                // which policy failed? need to inform consumer which requirement was not met
                //await next();
             }

        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();



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


来源:https://stackoverflow.com/questions/58629209/asp-net-core-3-0-is-it-possible-to-return-custom-error-page-when-user-is-not-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!