在Netcore 2中从Url禁用/删除'?ReturnUrl =' [英] Disable/Remove '?ReturnUrl=' from Url's in netcore 2

查看:87
本文介绍了在Netcore 2中从Url禁用/删除'?ReturnUrl ='的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种方法来阻止我的aspnetcore应用程序将?ReturnUrl ="添加到URL.有谁知道如何使用某种中间件来做到这一点.

I am trying to find a way to prevent my aspnetcore application to add "?ReturnUrl=" to the URL. Does anyone know how to do it, using some kind of middleware.

我尝试按照以下方式进行操作,但没有任何效果:

I tried doing it like below but it did not have any effect:

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框架的同一问题

Lastly, I have also tried some (tweaked) approaches from the older post regarding the same issue for .NET frameworks here (on stackoverflow) but also failed

除了标准" [Authorize]属性外,我没有使用任何其他AuthorizationAttribute/Handler.仅限:

I am not using any additional AuthorizationAttribute / Handler other then the 'standard' [Authorize] attribute. Only:

services.AddAuthorization();

我完全忘记了我也将启动的一部分注册到了应用程序的其他位置,因为它是共享的:

Edit 2: I totally forgot that I also register a portion of the startup elsewhere in the application since it is shared:

    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;
   }

推荐答案

首先想到的是:

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

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

Which will remove QueryString part from the URL so that "ReturnUrl" will not stay on user address-bar for long and will reject any QueryString.

更好的解决方法是创建自己的AuthorizeAttribute版本,该版本不会在QueryString中放入ReturnUrl,但是似乎出现了基于新策略的授权方法,

Better workaround would be creating your own version of AuthorizeAttribute which will not put a ReturnUrl in QueryString but it seems with new policy based authorization approach coming around, customizing AuthorizeAttribute is discouraged.

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

It might be also possible with policy based approach and creating a custom AuthorizationHandler.

(尝试后,我会立即发布更新)

(I will post an update as soon as I try it out)

这篇关于在Netcore 2中从Url禁用/删除'?ReturnUrl ='的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆