當前位置: 首頁>>代碼示例>>C#>>正文


C# Mvc.AuthorizationContext類代碼示例

本文整理匯總了C#中System.Web.Mvc.AuthorizationContext的典型用法代碼示例。如果您正苦於以下問題:C# AuthorizationContext類的具體用法?C# AuthorizationContext怎麽用?C# AuthorizationContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AuthorizationContext類屬於System.Web.Mvc命名空間,在下文中一共展示了AuthorizationContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");
            if (filterContext.IsChildAction)
                return;

            IUser currentUser = UserContext.CurrentUser;
            if (currentUser != null)
            {
                if (currentUser.IsBanned)
                {
                    IAuthenticationService authenticationService = DIContainer.ResolvePerHttpRequest<IAuthenticationService>();
                    authenticationService.SignOut();
                    filterContext.Result = new RedirectResult(SiteUrls.Instance().SystemMessage(filterContext.Controller.TempData, new SystemMessageViewModel
                    {
                        Title = "帳號被封禁!",
                        Body = "由於您的非法操作,您的帳號已被封禁,如有疑問,請聯係管理員",
                        StatusMessageType = StatusMessageType.Error
                    }));
                }
                return;
            }
            return;
        }
開發者ID:ClaytonWang,項目名稱:Dw3cSNS,代碼行數:25,代碼來源:IsBannedAttribute.cs

示例2: OnAuthorization

        public virtual void OnAuthorization(AuthorizationContext filterContext) {
            if (filterContext == null) {
                throw new ArgumentNullException("filterContext");
            }

            filterContext.Controller.ValidateRequest = EnableValidation;
        }
開發者ID:sanyaade-mobiledev,項目名稱:ASP.NET-Mvc-2,代碼行數:7,代碼來源:ValidateInputAttribute.cs

示例3: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated){
                var authorizedUsers = "2,3";
                var authorizedRoles = "Admin";

                Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

                if (!String.IsNullOrEmpty(Roles)){
                    if (!CurrentUser.IsInRole(Roles)){
                        filterContext.Result = new RedirectToRouteResult(new
                            RouteValueDictionary(new{controller = "Home", action = "AccessDenied"}));

                        // base.OnAuthorization(filterContext); //returns to login url
                    }
                }

                if (!String.IsNullOrEmpty(Users)){
                    if (!Users.Contains(CurrentUser.UserId.ToString())){
                        filterContext.Result =
                            new RedirectToRouteResult(new RouteValueDictionary(new{controller = "Home", action = "AccessDenied"}));

                        // base.OnAuthorization(filterContext); //returns to login url
                    }
                }
            }
            else{
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index" }));
            }
        }
開發者ID:Josimar,項目名稱:UpperCash,代碼行數:31,代碼來源:BaseController.cs

示例4: OnAuthorization

        //
        // GET: /Shared/
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var controller=RouteData.Values["controller"];
            string action = RouteData.Values["action"].ToString();
            //var id = Converter.ToInt (Session["ID"],0);
            //APIDataDataContext db = DBFactory.DB;
            //var sg = (from c in db.TAgents
            //          where c.ID == id
            //          select new
            //          {
            //              GroupName = (from d in db.TUserGroup where d.ID == c.GroupID select d.GroupName).FirstOrDefault()
            //          }).FirstOrDefault();
            //if (sg != null)
            //{
            //    var Name = Session["Name"];
            //    var Type = Session["Type"];
            //    ViewData["group"] = sg.GroupName;
                ViewData["controller"] = controller;
                ViewData["action"] = action;
            //}
            //else
            //{
            //    HttpContext.Server.TransferRequest("/login/Land", true);
            //}

            //沒登錄的話跳轉到登錄頁
            if (Session["ID"] == null)
            {
                //請求頁麵不是登錄頁的時候才跳轉
                if (action.ToLower() != "land")
                {
                    filterContext.Result = new RedirectResult("/Login/Land");
                }
            }
        }
開發者ID:BriseLee,項目名稱:test,代碼行數:37,代碼來源:SharedController.cs

示例5: HandleUnauthorizedRequest

        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NoPermission",
                        LogOnUrl = urlHelper.Action("index", "login")
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                context.Result = new RedirectToRouteResult(
                                       new RouteValueDictionary
                                   {
                                       { "action", "index" },

                                       { "controller", "error" },

                                       { "id", (int)ErrorType.NoPermission},

                                       {"returnurl",context.RequestContext.HttpContext.Request.Url}
                                   });
            }
        }
開發者ID:navy235,項目名稱:PadCrm,代碼行數:31,代碼來源:PermissionAuthorizeAttribute.cs

示例6: IsAdminPageRequested

 private bool IsAdminPageRequested(AuthorizationContext filterContext)
 {
     var adminAttributes = GetAdminAuthorizeAttributes(filterContext.ActionDescriptor);
     if (adminAttributes != null && adminAttributes.Any())
         return true;
     return false;
 }
開發者ID:KhangTranIt,項目名稱:Bluesky,代碼行數:7,代碼來源:AdminAuthorizeAttribute.cs

示例7: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.HttpContext.Request.IsSecureConnection)
            {
                return;
            }

            if (string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
                "https",
                StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (filterContext.HttpContext.Request.IsLocal)
            {
                return;
            }

            HandleNonHttpsRequest(filterContext);
        }
開發者ID:andyevans2000,項目名稱:Illuminate,代碼行數:26,代碼來源:RequireHttpsAttribute.cs

示例8: OnAuthorization

 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     var actionAttrs = filterContext.ActionDescriptor.GetCustomAttributes(true);
     if (actionAttrs.Any(x => x is AllowAnonymousAttribute))
     {
         return;
     }
     var actionAttr = actionAttrs.FirstOrDefault(x => x is MvcAuthorizeAttribute);
     if (actionAttr != null)
     {
         ((MvcAuthorizeAttribute)actionAttr).Authenticate(filterContext);
         return;
     }
     var controllerAttrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true);
     if (controllerAttrs.Any(x => x is AllowAnonymousAttribute))
     {
         return;
     }
     var controllerAttr = controllerAttrs.FirstOrDefault(x => x is MvcAuthorizeAttribute);
     if (controllerAttr != null)
     {
         ((MvcAuthorizeAttribute)controllerAttr).Authenticate(filterContext);
         return;
     }
     this.Authenticate(filterContext);
 }
開發者ID:yuandong618,項目名稱:mvcsolution,代碼行數:26,代碼來源:MvcAuthorizeAttribute.cs

示例9: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            long? userId = (null != FacebookWebContext.Current.Session) ? (long?)FacebookWebContext.Current.Session.UserId : null;

            if (null == userId || !AuthorizedUsers.Contains(userId.Value))
            {
                if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
                {
                    this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
                }
                else
                {
                    if (!AuthorizedUsers.Contains(FacebookWebContext.Current.Session.UserId))
                    {
                        AuthorizedUsers.Add(FacebookWebContext.Current.Session.UserId);
                    }
                }
            }
        }
開發者ID:nbclark,項目名稱:SportsLink,代碼行數:26,代碼來源:CanvasAuthorizeAttribute.cs

示例10: OnAuthorization

 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (!Common.IsLogedIn())
     {
         filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {{"Action","Index"},{"Controller","Landing"} });
     }
 }
開發者ID:changtraicantinh,項目名稱:testfsoft,代碼行數:7,代碼來源:LoginRequriedAttribute.cs

示例11: Authenticate

        public void Authenticate(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            var isAuthenticated = context.Request.IsAuthenticated;
            if (!string.IsNullOrEmpty(this.Roles))
            {
                isAuthenticated = isAuthenticated && this.Roles.Split(',').Any(r => context.User.IsInRole(r));
            }
            if (isAuthenticated)
            {
                return;
            }

            if (HttpContext.Current.Request["ajax"] == "true")
            {
                filterContext.Result = new StandardJsonResult()
                {
                    Message = context.Request.IsAuthenticated ? "Please login" : "You don't have sufficient permission"
                };
            }
            else
            {
                filterContext.Result = new RedirectResult("/login?returnUrl=" + HttpContext.Current.Request.RawUrl);
            }
        }
開發者ID:yuandong618,項目名稱:mvcsolution,代碼行數:25,代碼來源:MvcAuthorizeAttribute.cs

示例12: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var userId = filterContext.HttpContext.User.Identity.GetUserId();
                var userManager = filterContext.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var currentUser = userManager.FindById(userId);
                if (currentUser.EmailConfirmed == false)
                {

                    //取得 URLHelper
                    var urlHelper = new UrlHelper(filterContext.RequestContext);

                    //將路徑名稱組合
                    var currentControllerAndActionName =
                        string.Concat(filterContext.RouteData.Values["controller"],
                        "_",
                        filterContext.RouteData.Values["action"]);

                    //明確開放[登入][登出][EMAIL驗證]
                    var allowAction = new[] { "Account_Login", "Account_LogOff", "Account_VerifyMail" };

                    if (allowAction.Contains(currentControllerAndActionName) == false)
                    {
                        //所有沒有通過EMAIL驗證的都導向驗證頁麵(請視專案需求調整)
                        var redirect = new RedirectResult(urlHelper.Action("VerifyMail", "Account"));
                        filterContext.Result = redirect;
                    }

                }
            }
        }
開發者ID:chimpinano,項目名稱:MVC5Book,代碼行數:33,代碼來源:AuthorizePlusAttribute.cs

示例13: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (!String.IsNullOrEmpty(Roles))
                {
                    string[] roleNames = Roles.Split(',');

                    foreach (string role in roleNames)
                    {
                        if (filterContext.HttpContext.User.IsInRole(role))
                        {
                            //base.OnAuthorization(filterContext);
                            base.OnAuthorization(filterContext);
                            return;
                        }
                    }

                    filterContext.Controller.FlashError("You must be assigned one of the following roles" +
                                                        (String.IsNullOrEmpty(Task) ? "" : (" to " + Task)) + ": " +
                                                        Roles);
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                else
                {
                    // all cool. Go on ahead.
                }

            }
            else
                filterContext.Result = new HttpUnauthorizedResult();
        }
開發者ID:pate,項目名稱:blog,代碼行數:32,代碼來源:SiteAuthorizeAttribute.cs

示例14: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.HttpContext.Request.IsSecureConnection)
            {
                if (Redirect)
                {
                    var builder = new UriBuilder(filterContext.HttpContext.Request.Url);

                    builder.Scheme = Uri.UriSchemeHttps;

                    if (Port != 0 && Port != 443)
                    {
                        builder.Port = Port;
                    }

                    filterContext.Result = new RedirectResult(builder.ToString());
                }
                else
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
                }
            }
        }
開發者ID:pleb,項目名稱:Chillow,代碼行數:28,代碼來源:RequireHttpsAttribute.cs

示例15: OnAuthorization

        /// <summary>
        /// The on authorization act.
        /// </summary>
        /// <param name="filterContext">
        /// The filter context.
        /// </param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // user does not authenticated
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (filterContext.HttpContext.Session != null)
                {
                    filterContext.HttpContext.Session.Add("key", "Please login to view that page.");
                }

                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                    {                        
                        { "controller", "Account" },
                        { "action", "Login" },
                        { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                    });
                return;
            }

            base.OnAuthorization(filterContext);

            // user already authenticated, but have not permissions to make action
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                    {                            
                        { "controller", "Account" },
                        { "action", "PermissionError" },
                        { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                    });
            }
        }
開發者ID:nktssh,項目名稱:KSS.HorseRasing,代碼行數:40,代碼來源:KssAuthorize.cs


注:本文中的System.Web.Mvc.AuthorizationContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。