簡體   English   中英

向ASP.Net MVC 4中的ASP.Net Web窗體添加身份驗證

[英]Add authentication to ASP.Net Web Forms inside ASP.Net MVC 4

我創建了一個MVC應用程序。 我在每個控制器上創建了身份驗證,並且它可以正常工作。 如果我不是授權用戶,我將重定向到登錄頁面。 我對控制器的授權(sitemapnode角色)沒有任何問題。

現在,我在ASP.Net MVC項目中創建了一個ASP.NET Web窗體。 我在網絡表單上放置了一個reportviewer。 我在MVC上創建了一個View,將asp.net Web表單放在iFrame標記中,這也可以工作。 我可以在調用正確的控制器時查看reportviewer。

但是,如果我沒有獲得授權,只需鍵入ASP.NET Web窗體的位置,我仍然可以查看或訪問ASP.NET Web窗體(帶有reportviewer)。

如何在我的Web表單上應用授權? 與MVC上的授權類似。 如果我不是授權用戶(假設為“ admin”),則必須將我重定向到“登錄”頁面,否則我將無法訪問Web表單。 我怎么做?

更大的問題是為什么您需要混合使用MVC和WebForms,但是無論如何...

MS文檔可能是您最大的幫助:

http://www.asp.net/web-forms/tutorials/security/roles/role-based-authorization-cs

您可以像下面這樣鎖定web.config:

  <location path="YourPage.aspx">    
      <system.web>    
           <authorization>    
               <allow roles="sitemapnode" /> 
           </authorization>    
      </system.web>    
 </location>

或在具有屬性的頁面方法級別:

[PrincipalPermission(SecurityAction.Demand, Role = "sitemapnode")]

使用MVC過濾器:

    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.Security;
    using PortalAPI.SPModels;
    using SICommon.Enums;
    using SICommon.LoggingOperations;

    namespace SupplierPortal.Security {
        public class AuthorizedUser : AuthorizeAttribute {
            public bool IsAuthorized { get; set; }

            protected override bool AuthorizeCore(HttpContextBase httpContext) {

                if (Authenticated())
                  return this.IsAuthorized = true;
            }

            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
                if (filterContext.HttpContext.Request.IsAjaxRequest()) {
                    filterContext.HttpContext.Response.StatusCode = 403;
                    filterContext.Result = new JsonResult {
                        Data = new {
                            Error = "SessionTimeOut"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                    filterContext.HttpContext.Response.End();
                } else {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new {
                                controller = "Account",
                                action = "Login"
                            }
                        )
                    );
                }
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }

    [AuthorizedUser(IsAuthorized = true)]
    public class myformclass(){
        //some code in here for form
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM