繁体   English   中英

在MVC6中如何阻止直接访问wwwroot中的文件夹?

[英]In MVC6 how can I block direct access to a folder in wwwroot?

我们正在开发一个最新的MVC框架中的应用程序,到目前为止一切都很棒。 在我们的应用程序中,我们决定在wwwroot / app下的项目中嵌入一个角度应用程序。 我创建了一个app控制器并查看和禁止访问该应用程序,除非用户获得授权。 当未经授权的用户尝试访问localhost / app时,这很有效 - 它将它们踢回C#应用程序登录页面。

我想更进一步,并禁止访问该文件夹中的直接文件,例如localhost / app / scripts / controllers / name.js或部分html文件/app/partials/name-partial.html。 在过去,我将进入web.config并添加以下代码,但我没有找到最新框架的等效项。 理想情况下,如果可能,我希望这是startup.cs或appsettings.json中的条目

  <location path="app">
    <system.web>
      <authorization>
        <allow roles="User" />
        <deny roles="*" />
      </authorization>
    </system.web>
  </location>

经过额外的研究,似乎最简单的方法就是在配置UseStaticFiles时实际使用OnPrepareResponse StaticFileOption。

以下内容将放在Startup.cs中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
{
    app.UseStaticFiles(new StaticFileOptions()
    {
        OnPrepareResponse = s =>
        {
            if (s.Context.Request.Path.StartsWithSegments(new PathString("/app")) && 
               !s.Context.User.Identity.IsAuthenticated)
            {
                s.Context.Response.StatusCode = 401;
                s.Context.Response.Body = Stream.Null;
                s.Context.Response.ContentLength = 0;
            }
        }
    });
}

上述代码仅在执行静态文件WITHIN wwwroot时运行,特别是在以“/ app”段开头的任何路径中运行。 如果未经过身份验证,则会重写响应,以便不会将正常内容以及相应的状态代码传递给客户端。

这是一种截然不同的方法,它使用内联中间件来阻止对特定路径的未经身份验证的请求:

app.Use((context, next) => {
    // Ignore requests that don't point to static files.
    if (!context.Request.Path.StartsWithSegments("/app")) {
        return next();
    }

    // Don't return a 401 response if the user is already authenticated.
    if (context.User.Identities.Any(identity => identity.IsAuthenticated)) {
        return next();
    }

    // Stop processing the request and return a 401 response.
    context.Response.StatusCode = 401;
    return Task.FromResult(0);
});

确保在您的身份验证中间件(或不会填充context.User )之后和其他中间件之前(在您的情况下,在静态文件中间件之前)注册它。 您还必须确保使用自动身份验证( AutomaticAuthenticate = true )。 如果没有,您将不得不使用身份验证API:

app.Use(async (context, next) => {
    // Ignore requests that don't point to static files.
    if (!context.Request.Path.StartsWithSegments("/app")) {
        await next();
        return;
    }

    // Don't return a 401 response if the user is already authenticated.
    var principal = await context.Authentication.AuthenticateAsync("Cookies");
    if (principal != null && principal.Identities.Any(identity => identity.IsAuthenticated)) {
        await next();
        return;
    }

    // Stop processing the request and trigger a challenge.
    await context.Authentication.ChallengeAsync("Cookies");
});

注意:如果您想阻止cookie中间件用302重定向替换401响应,请按以下步骤操作:

使用Identity时(在ConfigureServices ):

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
    options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents {
        OnValidatePrincipal = options.Cookies.ApplicationCookie.Events.ValidatePrincipal,
        OnRedirectToLogin = context => {
            // When the request doesn't correspond to a static files path,
            // simply apply a 302 status code to redirect the user agent.
            if (!context.Request.Path.StartsWithSegments("/app")) {
                context.Response.Redirect(context.RedirectUri);
            }

            return Task.FromResult(0);
        }
    };
});

使用不带身份的cookie中间件时(在Configure ):

app.UseCookieAuthentication(options => {
    options.Events = new CookieAuthenticationEvents {
        OnRedirectToLogin = context => {
            // When the request doesn't correspond to a static files path,
            // simply apply a 302 status code to redirect the user agent.
            if (!context.Request.Path.StartsWithSegments("/app")) {
                context.Response.Redirect(context.RedirectUri);
            }

            return Task.FromResult(0);
        }
    };
});

为防止用户直接访问文件夹,请尝试此代码

<security>
  <requestFiltering>
    <hiddenSegments>
      <add segment="folderName"/>
    </hiddenSegments>
  </requestFiltering>
</security>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM