在混合的 MVC/WebForms Web 应用程序中配置授权

Configuring Authorization in a mixed MVC / WebForms Web app(在混合的 MVC/WebForms Web 应用程序中配置授权)
本文介绍了在混合的 MVC/WebForms Web 应用程序中配置授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将 WebForms/MVP 应用程序的一些组件迁移到 MVC.到目前为止,除授权外,一切正常.无论如何,当我导航到登录页面的 MVC 版本时,我被重定向到在 Web.config 中设置的 aspx 页面:

I'm currently migrating some components of a WebForms / MVP application into MVC. So far, everything is working except for authorization. No matter what, when I navigate to the MVC version of the Login page, I get redirected to the aspx page that is set in the Web.config:

    <authentication mode="Forms">
      <forms name=".MyWebSite" enableCrossAppRedirects="true" loginUrl="Login.aspx" timeout="60" path="/" defaultUrl="~/Pages/Landing.aspx"></forms>
    </authentication>

我试过使用 AllowAnonymous 但似乎 webforms 配置优先.这是我的登录控制器:

I've tried using AllowAnonymous but it appears that the webforms config are taking precedence. Here's my Login controller:

[RouteArea("User", AreaPrefix = "")]
public class AuthenticationController : Controller {
    [Route("Login")]
    [AllowAnonymous]
    public ActionResult Login() {
        return View();
    }
}

我的目录结构是这样的:

And my Directory structure looks like this:

> Web Project
   > Areas
      > User 
          > Controllers
              > AuthController
          > Views
              > Login.cshtml

在我的 web.config 中,我看到以下内容以允许匿名访问错误页面:

In my web.config, I see the following to allow anonymous access to the Error pages:

  <location path="Error">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

但是,为 Areas 路径复制它不起作用(大概是因为 cshtml 文件实际上并不像 aspx 页面那样位于那里?).

However duplicating this for the Areas path isn't working (presumably because the cshtml files are not actually located there as aspx pages are?).

现在,如果我已登录(通过 aspx 版本的登录)并且我的用户已通过身份验证,我就可以很好地访问 MVC 实现.路由和渲染工作得非常好.它只是允许未经身份验证的用户访问 MVC 页面(不重定向到 aspx 实现),这似乎是一个挑战.我究竟做错了什么?

Now, if I am logged in (via the aspx version of login) and my user is authenticated, I can access the MVC implementation just fine. Routing and rendering are working wonderfully. It's just allowing unauthenticated users to access the MVC page (without redirecting to the aspx implementation) that seems to be a challenge. What am I doing wrong?

编辑我发现了一个非常hacky的部分解决方案(基于为一个子目录关闭 ASP.Net WebForms 身份验证)如下:

EDIT A really hacky partial solution I've found (based on Turning off ASP.Net WebForms authentication for one sub-directory) is the following:

    protected void Application_BeginRequest(object sender, EventArgs e) {
        // lots of existing web.config controls for which webforms folders can be accessed
        // read the config and skip checks for pages that authorise anon users by having
        // <allow users="?" /> as the top rule.
        // https://stackoverflow.com/questions/4616524/turning-off-asp-net-webforms-authentication-for-one-sub-directory

        // check local config
        var localAuthSection = ConfigurationManager.GetSection("system.web/authorization") as AuthorizationSection;

        // this assumes that the first rule will be <allow users="?" />
        var localRule = localAuthSection.Rules[0];
        if (localRule.Action == AuthorizationRuleAction.Allow && localRule.Users.Contains("?")) {
            // then skip the rest
            return;
        }

        // get the web.config and check locations
        var conf = WebConfigurationManager.OpenWebConfiguration("~");
        foreach (ConfigurationLocation loc in conf.Locations) {
            // find whether we're in a location with overridden config

            // get page name
            var currentPath = Path.GetFileName(this.Request.Path);
            if (currentPath.Equals(loc.Path, StringComparison.OrdinalIgnoreCase)) {
                // get the location's config
                var locConf = loc.OpenConfiguration();
                var authSection = locConf.GetSection("system.web/authorization") as AuthorizationSection;
                if (authSection != null) {
                    // this assumes that the first rule will be <allow users="?" />
                    var rule = authSection.Rules[0];
                    if (rule.Action == AuthorizationRuleAction.Allow && rule.Users.Contains("?")) {
                        // then skip the rest
                        return;
                    }
                }
            }
        }
    }

这意味着我可以像这样指定登录":

Which means I can specify "Login" like this:

  <location path="Login">
    <system.web>
      <authorization>
        <allow users="?" />
      </authorization>
    </system.web>
  </location>

但是所有相关的 CSS/JS 都不会被渲染,除非我通过并为这些文件类型添加规则.必须对此进行更优雅的修复.

But then all of the associated CSS/JS do not get rendered, unless I go through and add rules for those filetypes. There's got to be a more elegant fix to this.

推荐答案

我找到了我认为正确的解决方案.在我的 web.config 中,我将 loginUrl 设置为我的 MVC 页面:

I found what I think is the proper solution. In my web.config, I set the loginUrl to my MVC page:

    <authentication mode="Forms">
      <forms name=".MyWebSite" enableCrossAppRedirects="true" loginUrl="Login" timeout="60" path="/" defaultUrl="~/Pages/Landing.aspx"></forms>
    </authentication>

然后我必须从我的 authController 中设置 cookie,以便当我重定向到 aspx 页面时,HttpContext.CurrentUser 被定义为登录用户:

I then have to set the cookie from within my authController so that when I redirect to an aspx page, HttpContext.CurrentUser is defined as the logged-in user:

FormsAuthentication.SetAuthCookie(model.Username, true);

我不知道这是否确实是解决此问题的正确方法,但到目前为止它似乎有效.如果有人有任何反馈,我会保持开放状态.

I don't know if this is indeed the correct way to go about this, but so far it seems to be working. I'll leave this open in case anyone has any feedback.

这篇关于在混合的 MVC/WebForms Web 应用程序中配置授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)