【问题标题】:Disable/Remove '?ReturnUrl=' from Url's in netcore 2从网络核心 2 中的 Url 禁用/删除 '?ReturnUrl='
【发布时间】:2018-04-02 10:06:19
【问题描述】:

我试图找到一种方法来阻止我的 aspnetcore 应用程序将“?ReturnUrl =”添加到 URL。有谁知道怎么做,使用某种中间件。

我尝试像下面那样做,但没有任何效果:

public class RequestHandlerMiddleware
{
    private readonly RequestDelegate _next;

    public RequestHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if(context.Request.QueryString.HasValue && context.Request.QueryString.Value.Contains("?ReturnUrl="))
        {
            context.Request.QueryString = new QueryString(string.Empty);
        }
        await _next.Invoke(context);
    }
}

public static class RequestHandlerMiddlewareExtension
{
    public static IApplicationBuilder UseRequestHandlerMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestHandlerMiddleware>();
    }
}

startup.cs注册:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/error");
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseAuthentication();
    app.UseRequestHandlerMiddleware();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}

最后,我还尝试了旧帖子中关于 .NET 框架 here (on stackoverflow) 的相同问题的一些(调整过的)方法,但也失败了

编辑: 除了“标准”[Authorize] 属性之外,我没有使用任何其他 AuthorizationAttribute / Handler。仅:

services.AddAuthorization();

编辑 2:我完全忘记了我还在应用程序的其他地方注册了一部分启动,因为它是共享的:

    public static IServiceCollection Load(IServiceCollection services, IConfiguration config)
    {

        services.AddDbContext<SqlContext>(options =>
        {
            options.UseSqlServer(config.GetConnectionString("DefaultConnection"));
        });

        services.AddIdentity<User, Role>(options =>
        {
            options.Lockout = new LockoutOptions
            {
                AllowedForNewUsers = true,
                DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30),
                MaxFailedAccessAttempts = 5
            };
        })
        .AddEntityFrameworkStores<SqlContext>()
        .AddDefaultTokenProviders()
        .AddUserStore<UserStore<User, Role, SqlContext, Guid>>()
        .AddRoleStore<RoleStore<Role, SqlContext, Guid>>()
        .AddUserManager<ApplicationUserManager>();

        services.Configure<IdentityOptions>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 5;
            options.Password.RequireLowercase = true;
            options.Password.RequireUppercase = false;
            options.Password.RequireNonAlphanumeric = true;

        });

        services.ConfigureApplicationCookie(options =>
        options.Events = new CookieAuthenticationEvents
        {
            OnRedirectToLogin = ctx =>
            {
                if (ctx.Request.Path.StartsWithSegments("/api") &&
                    ctx.Response.StatusCode == (int)HttpStatusCode.OK)
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                }
                else if (ctx.Response.StatusCode == (int)HttpStatusCode.Forbidden)
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                }
                else
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }
                return Task.FromResult(0);
            }
        });
        return services;
   }

【问题讨论】:

  • 听起来您想在程序生成的 URL 中删除 ReturnUri。但是您在进入程序的过程中将其删除。如果您想在退出时删除它们,则需要查看响应。如果您举例说明您所看到的以及您希望它看起来像什么,这可能会有所帮助。
  • 请问您为什么要阻止它?它提供建议。
  • 所以当转到 localhost:3000 时,应用程序将重定向到 ...Account/Login?ReturnUrl=%2F,但我只想要 Account/Login。原因是我总是重定向到 /Index,不管用户在什么时候被重定向(在大多数情况下未经授权)。而且这样看起来更干净。
  • 您能分享您的身份验证处理程序吗?
  • 我添加了一个更新:我没有使用除 [Authorize] 之外的任何(自定义)处理程序,这是标准处理程序。此外,我还没有要求额外的中间件处理程序。 ( services.AddAuthorization();)

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


【解决方案1】:

首先想到的是:

[HttpGet]
public IActionResult LogIn()
{
    if (!string.IsNullOrEmpty(Request.QueryString.Value))
        return RedirectToAction("Login");
    return View();
}

这将从 URL 中删除 QueryString 部分,以便“ReturnUrl”不会长时间停留在用户地址栏上,并且会拒绝任何 QueryString。

更好的解决方法是创建您自己的 AuthorizeAttribute 版本,它不会在 QueryString 中放置 ReturnUrl,但似乎随着新的基于策略的授权方法的出现,不鼓励自定义 AuthorizeAttribute。 more

也可以使用基于策略的方法并创建自定义 AuthorizationHandler

(我会在试用后立即发布更新)

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多