在MVC6我怎么能阻止wwwroot中直接访问到文件夹?文件夹、直接、我怎么能、wwwroot

2023-09-13 04:44:43 作者:一笑泯千仇

我们正在开发的最新的MVC框架的应用程序,一切至今已经很大。在我们的应用,我们已经决定在嵌入wwwroot下/应用项目的角度应用。我创建了一个应用程序控制器和视图,并禁止访问该应用,除非用户授权。当未经授权的用户尝试到本地主机/应用这个伟大的工程 - 它踢回给C#应用程序的登录页面。

我想要把它更进一步,还禁止访问该文件夹直接的文件,如本地主机/应用/脚本/控制器/ name.js或部分HTML文件/app/partials/name-partial.html。在过去,我会去到web.config文件,并添加以下code,但我还没有找到最新的框架相同。理想情况下,我想这是startup.cs或者如果可能的条目appsettings.json

 <位置路径=应用程序>    <&的System.Web GT;      <授权>        <让角色=用户/>        &所述;拒绝角色=*/>      < /授权>    < /system.web>  < /地点> 

解决方案 Win8系统文件 拒绝访问 怎么办

下面是一个悦目不同的方法,即使用嵌入式中间件来阻止特定路径未认证的请求:

  app.Use((背景下,下一个)=> {    //忽略不指向静态文件的请求。    如果(!context.Request.Path.StartsWithSegments(/应用程序)){        返回下一个();    }    //如果用户已通过身份验证不返回401响应。    如果(context.User.Identities.Any(身份=> identity.IsAuthenticated)){        返回下一个();    }    //停止处理请求并返回一个响应401。    context.Response.Status code = 401;    返回Task.FromResult(0);}); 

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

  app.Use(异步(背景下,下一个)=> {    //忽略不指向静态文件的请求。    如果(!context.Request.Path.StartsWithSegments(/应用程序)){        接下来的等待();        返回;    }    //如果用户已通过身份验证不返回401响应。    VAR本金=等待context.Authentication.AuthenticateAsync(曲奇);    如果(本金= NULL&放大器;!&安培; principal.Identities.Any(身份=> identity.IsAuthenticated)){        接下来的等待();        返回;    }    //停止处理该请求,并触发一个挑战。    等待context.Authentication.ChallengeAsync(曲奇);}); 

请注意:如果你想prevent从更换由302重定向401响应饼干中间件,这里是你如何能做到:

的当使用标识(在 ConfigureServices ):的

  services.AddIdentity< ApplicationUser,IdentityRole>(选项=> {    options.Cookies.ApplicationCookie.Events =新CookieAuthenticationEvents {        OnValidatePrincipal = options.Cookies.ApplicationCookie.Events.ValidatePrincipal,        OnRedirectToLogin =背景=> {            //当请求不对应于一个静态文件路径,            //简单地套用一个302状态code重定向用户代理。            如果(!context.Request.Path.StartsWithSegments(/应用程序)){                context.Response.Redirect(context.RedirectUri);            }            返回Task.FromResult(0);        }    };}); 

的当使用无身份饼干中间件(在配置):的

  app.UseCookieAuthentication(选项=> {    options.Events =新CookieAuthenticationEvents {        OnRedirectToLogin =背景=> {            //当请求不对应于一个静态文件路径,            //简单地套用一个302状态code重定向用户代理。            如果(!context.Request.Path.StartsWithSegments(/应用程序)){                context.Response.Redirect(context.RedirectUri);            }            返回Task.FromResult(0);        }    };}); 

We're developing an application in the latest MVC framework and everything so far has been great. In our application we have decided to embed an angular application in the project under wwwroot/app. I created an app controller and view and prohibited access to the app unless users are authorized. This works great when unauthorized users try to go to localhost/app - it kicks them back to the C# application login page.

I want to take it a step further and also prohibit access to direct files in that folder such as localhost/app/scripts/controllers/name.js or partial html files /app/partials/name-partial.html. In the past I would go into web.config and add the following code but I haven't found the equivalent for the latest framework. Ideally I'd like this to be an entry in startup.cs or appsettings.json if possible

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

解决方案

Here's a sightly different approach, that uses an inline middleware to block unauthenticated requests for specific paths:

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

Make sure to register it after your authentication middleware (or context.User won't be populated) and before the other middleware (in your case, before the static files middleware). You'll also have to make sure you're using automatic authentication (AutomaticAuthenticate = true). If not, you'll have to use the authentication 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");
});

Note: if you want to prevent the cookies middleware from replacing the 401 response by a 302 redirect, here's how you can do:

When using Identity (in 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);
        }
    };
});

When using the cookies middleware without Identity (in 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);
        }
    };
});