如何使用中间件重定向到自定义403 -ASP.NET

发布于 2025-01-19 12:55:18 字数 2770 浏览 0 评论 0原文

如果身份验证失败了无效的自定义403页面,我正在尝试重定向。 仅当通过LDAP对用户进行身份验证(应属于特定组)时,才能访问网页,

这是我到目前为止所做的:

  1. 添加的授权中间件
  2. 添加了授权中间件扩展程序
  3. 将其配置为startup.cs
  4. 添加了错误控制器和视图
        public async Task Invoke(HttpContext context)
        {

            // create and search ldap
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            var userName = context.User.Identity.Name;
            userName = System.IO.Path.GetFileNameWithoutExtension(userName);
            // look for SAM account names in groups for the user
            mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
            SearchResult result = mySearcher.FindOne();
            var isAuthorized = false;
            foreach (string GroupPath in result.Properties["memberOf"])
            {
                if (GroupPath.Contains(AuthorisedGroup))
                {
                    isAuthorized = true;
                }
            }


            // Return error if the current user is not authorized
            if (!isAuthorized)
            {

                context.Response.StatusCode = 403;
                return;
            }
            // Jump to the next middleware if the user is authorized
             await NextRequest.Invoke(context);
       }

在startup.cs中配置方法

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
                //app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAdAuthorizationMiddleware();//<------- Middleware config

            app.UseAuthorization();

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

错误控制器

    public class ErrorController : Controller
    {

        [Route("Error/{statusCode}")]
        public IActionResult StatusCodeHandler(string statusCode)
        {
            return View($"{statusCode}");
        }
    }

我添加了2个视图

​因此,到达控制器,因此显示标准403页面而不是自定义页面。

感谢您的帮助

I'm trying to redirect if authentication fails to a custom 403 page which Is not working.
The web pages should only be accessible if the user is authenticated via LDAP(should belong to a particular group)

this is what i've done so far:

  1. Added Authorization middleware
  2. Added Authorization middleware extension
  3. Configure it in startup.cs
  4. Added Error controller and Views
        public async Task Invoke(HttpContext context)
        {

            // create and search ldap
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            var userName = context.User.Identity.Name;
            userName = System.IO.Path.GetFileNameWithoutExtension(userName);
            // look for SAM account names in groups for the user
            mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
            SearchResult result = mySearcher.FindOne();
            var isAuthorized = false;
            foreach (string GroupPath in result.Properties["memberOf"])
            {
                if (GroupPath.Contains(AuthorisedGroup))
                {
                    isAuthorized = true;
                }
            }


            // Return error if the current user is not authorized
            if (!isAuthorized)
            {

                context.Response.StatusCode = 403;
                return;
            }
            // Jump to the next middleware if the user is authorized
             await NextRequest.Invoke(context);
       }

Configure method in startup.cs

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
                //app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAdAuthorizationMiddleware();//<------- Middleware config

            app.UseAuthorization();

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

Error Controller

    public class ErrorController : Controller
    {

        [Route("Error/{statusCode}")]
        public IActionResult StatusCodeHandler(string statusCode)
        {
            return View(
quot;{statusCode}");
        }
    }

I've added 2 views

enter image description here

if I type an invalid url it does show custom 404, but if i set isAuthorized = false it doesn't get to the controller hence shows the standard 403 page instead of custom page.

Thanks for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文