【问题标题】:Is it possible to change query string arguments on AccessDeniedPath?是否可以更改 AccessDeniedPath 上的查询字符串参数?
【发布时间】:2020-12-07 14:41:24
【问题描述】:

在 ASP.NET Core 3.1 Web 应用程序中,我可以更改 Startup.cs 中未经授权请求的目标路由,如下所示:

services.ConfigureApplicationCookie(o =>
{
    o.AccessDeniedPath = "/Home/Error";
});

这将返回/Home/Error?ReturnUrl=...,其中... 是我试图访问的任何页面。

但我实际上只是希望它简单地返回“/Home/Error?code=401”

我试过了,例如

o.AccessDeniedPath = "/Home/Error?code=401"

但是这很简单

"/Home/Error?code=401?ReturnUrl=%2FAdmin"

然后我意识到选项中有一个ReturnUrlParameter,如下所示:

o.ReturnUrlParameter = "code";
o.AccessDeniedPath = "/Home/Error";

这让我在重定向中走到了这一步:

/Home/Error?code=%2FAdmin

但是我想指定keyvalue值(例如401),即替换请求来自的页面,所以最终结果会是

/Home/Error?code=401

【问题讨论】:

  • 您可能对服务器上的角色有疑问:docs.microsoft.com/en-us/aspnet/web-forms/overview/…
  • @jdweng 这与我想要实现的目标无关。我的授权工作正常,我只想更改它在用户未经授权时重定向到的页面。该链接也适用于 ASP.NET 3.5,而我使用的是 ASP.NET Core 3.1
  • 这似乎是一种默认行为,它的存在是有原因的。也许,如果您不在服务器上使用它,请忽略它。如果您仍想删除它,可以尝试使用this answerthis 之类的方法。如果没有自定义身份验证实现,这可能无法实现。 See discussion here
  • 我实际上有一个自定义的身份验证例程正在运行,但我刚刚意识到我基本上可以检查我的ReturnUrl 是否在我的Home/Error 请求中为空并在那里做我需要的事情,所以现在不再需要更改它。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

根据您的代码,您似乎正在使用cookie身份验证,我建议您可以尝试使用CookieAuthenticationEvents.OnRedirectToAccessDenied Property更改重定向URL,检查以下示例代码:

        services.AddAuthentication("CookieAuthentication")
            .AddCookie("CookieAuthentication", config =>
            {
                config.Cookie.Name = "UserLoginCookie"; // Name of cookie     
                config.LoginPath = "/Login/UserLogin"; // Path for the redirect to user login page    
                config.AccessDeniedPath = "/Login/UserAccessDenied";
                config.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents()
                {
                    OnRedirectToAccessDenied = ctx =>
                    {
                        var redirectPath = ctx.RedirectUri;
                        if (redirectPath.Contains("?ReturnUrl"))
                        {
                            //remove the ReturnURL
                            var url = redirectPath.Substring(0, redirectPath.LastIndexOf("?ReturnUrl"));

                            ctx.Response.Redirect(url + "?code=401");
                        }
                        // Or, directly using the following code:
                        //ctx.Response.Redirect("/Login/UserAccessDenied?code=401");
                        return Task.CompletedTask;
                    }
                };
            });

输出如下:

【讨论】:

  • 我正在根据我的 appsettings 使用 Windows 身份验证(我猜它使用 cookie?),我没有在启动时添加任何其他身份验证,我只是使用自定义 [Authorize] 属性在我的控制器上,但这会起作用,因为我仍在使用services.ConfigureApplicationCookie 线
猜你喜欢
  • 2015-02-26
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2011-05-14
  • 2013-06-22
  • 1970-01-01
  • 2013-02-06
  • 2014-01-28
相关资源
最近更新 更多