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;
        }
Beispiel #2
0
        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();
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
                var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];

                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 = "Error", 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 = "Error", action = "AccessDenied" }));

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

        }
 //public override void OnAuthorization(AuthorizationContext filterContext)
 //{
 //   if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
 //   {
 //      filterContext.HttpContext.SkipAuthorization = true;
 //      filterContext.HttpContext.Response.Clear();
 //      filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
 //      filterContext.Result = new HttpUnauthorizedResult("Unauthorized");
 //      filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
 //      filterContext.HttpContext.Response.End();
 //      return;
 //   }
 //   //if (filterContext.HttpContext.Request.IsAjaxRequest()
 //   //       && (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0
 //   //       || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Count() > 0))
 //   //{
 //   //}
 //   //base.OnAuthorization(filterContext);
 //}
 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 {
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
      {
     filterContext.HttpContext.SkipAuthorization = true;
     filterContext.HttpContext.Response.Clear();
     filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
     filterContext.Result = new HttpUnauthorizedResult("Unauthorized");
     filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
     filterContext.HttpContext.Response.End();
     base.HandleUnauthorizedRequest(filterContext);
      }
      if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
      {
     // The user is not in any of the listed roles =>
     // show the unauthorized view
     filterContext.Result = new ViewResult
     {
        ViewName = "~/Views/Shared/Unauthorized.aspx"
     };
      }
      else {
     base.HandleUnauthorizedRequest(filterContext);
      }
 }
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            if (_ignore)
                return;

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
                return;

            //only POST requests
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
                return;

            if (!DataSettingsHelper.DatabaseIsInstalled())
                return;
            var securitySettings = EngineContext.Current.Resolve<SecuritySettings>();
            if (!securitySettings.EnableXsrfProtectionForPublicStore)
                return;

            var validator = new ValidateAntiForgeryTokenAttribute();
            validator.OnAuthorization(filterContext);
        }
        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);
        }
        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;
                    }

                }
            }
        }
 private bool IsAdminPageRequested(AuthorizationContext filterContext)
 {
     var adminAttributes = GetAdminAuthorizeAttributes(filterContext.ActionDescriptor);
     if (adminAttributes != null && adminAttributes.Any())
         return true;
     return false;
 }
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (!Common.IsLogedIn())
     {
         filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {{"Action","Index"},{"Controller","Landing"} });
     }
 }
 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 {
     var owinContext = filterContext.HttpContext.GetOwinContext();
     owinContext.Authentication.Challenge(AuthenticationTypes.ApiKey);
     owinContext.Response.StatusCode = 401;
     filterContext.Result = new HttpUnauthorizedResult();
 }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
                return;

            HttpRequestBase request = filterContext.HttpContext.Request;
            if (request == null)
                return;

            if (filterContext.IsChildAction)
                return;

            // only redirect for GET requests,
            // otherwise the browser might not propagate the verb and request body correctly.
            if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) == false)
                return;

            if (WebHelper.SslEnabled() == false)
                return;

            var currentConnectionSecured = request.IsSecureConnection;
            if (currentConnectionSecured == false)
            {
                RedirectToSsl(filterContext);
            }
            else
            {
                var secureSsl = _appSettings.SslUrl.Trim();
                if (request.Url.AbsoluteUri.Contains(secureSsl) == false)
                {
                    RedirectToSsl(filterContext);
                }
            }
        }
 public void OnAuthorization(AuthorizationContext filterContext)
 {
     //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
     //{
     //    filterContext.Result = new RedirectResult("/Account/Login");
     //}
 }
Beispiel #13
0
        //
        // 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");
                }
            }
        }
Beispiel #14
0
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);

                string realIP = new AllPay.ShareLib.Network().GetRemoteRealIP();

                if (ConfigService.BlockIp == true)
                {
                    if (!(realIP.StartsWith("172.16.30") || realIP.StartsWith("127.0.0.1")))
                    {
                        filterContext.Result = new HttpUnauthorizedResult();
                    }
                    else
                    {
                        filterContext.Result = null;
                    }

                }
                else {
                    filterContext.Result = null;
                }



            }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var actionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AccessAttribute), true);

            if (actionAttributes.Length > 0)
            {
                var notSkipAuthorization = actionAttributes.Any(x => this.GetType() == x.GetType());
                if (notSkipAuthorization)
                {
                    base.OnAuthorization(filterContext);

                    if (filterContext.Result is HttpUnauthorizedResult)
                    {
                        string returnUrl = string.Empty;
                        if (filterContext.HttpContext.Request.UrlReferrer != null)
                        {
                            returnUrl = filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;
                            returnUrl = filterContext.HttpContext.Server.UrlEncode(returnUrl);
                        }
                        filterContext.Result = new RedirectResult("~/Error/Authorization?t=NoPermission");
                    }
                }
            }
            else
            {
                base.OnAuthorization(filterContext);

                if (filterContext.Result is HttpUnauthorizedResult)
                    filterContext.Result = new RedirectResult("~/Error/Authorization?t=NoPermission");
            }
        }
        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);
                    }
                }
            }
        }
Beispiel #17
0
        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.");
                }
            }
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            var loginUrl = string.Format(CultureInfo.InvariantCulture, "~/Account/LogOn?returnUrl={0}", filterContext.HttpContext.Request.RawUrl);

            if (cookie == null)
            {
                filterContext.Result = new RedirectResult(loginUrl);
            }
            else
            {
                FormsAuthenticationTicket ticket = null;

                try
                {
                    ticket = FormsAuthentication.Decrypt(cookie.Value);
                }
                catch (ArgumentException)
                {
                    filterContext.Result = new RedirectResult(loginUrl);
                }

                if (ticket != null)
                {
                    var userId = Membership.GetUser(new FormsIdentity(ticket).Name).ProviderUserKey.ToString();
                    if (!this.UserPrivilegesRepository.HasUserPrivilege(userId, this.Roles))
                    {
                        filterContext.Result = new RedirectResult("~/Account/Unauthorized");
                    }
                }
            }
        }
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null) throw new ArgumentNullException("filterContext");

            // If a child action cache block is active, we need to fail immediately, even if authorization
            // would have succeeded. The reason is that there's no way to hook a callback to rerun
            // authorization before the fragment is served from the cache, so we can't guarantee that this
            // filter will be re-run on subsequent requests.
            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
                throw new CannotUseWithinChildActionCache();

            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(EzAllowAnonymousAttribute), inherit: true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(EzAllowAnonymousAttribute), inherit: true);

            if (skipAuthorization) return;

            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.
            if (AuthorizeCore(filterContext.HttpContext))
            {
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge(new TimeSpan(0));
                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
            }
            else
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
        public virtual void OnAuthorization(AuthorizationContext filterContext) {
            if (filterContext == null) {
                throw new ArgumentNullException("filterContext");
            }

            filterContext.Controller.ValidateRequest = EnableValidation;
        }
Beispiel #21
0
        /// <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 }
                    });
            }
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            // Grab and cast the controller to allow for Alerts
            var controller = (BaseController) filterContext.Controller;

            // If the user is authenticated and seeing this, they must not have the proper roles
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // Alert
                controller.Danger("You have attempted to access a portion of the website you do not have access to");
                // Redirect
                filterContext.Result = controller.RedirectToAction("Index", "Home");
            }
            // If the user is not authenticated all together, bring them to the login page
            else
            {
                // Build the Route values with the request URL for redirect
                var returnUrl = filterContext.HttpContext.Request.Url?.LocalPath;
                var routeValues = new RouteValueDictionary(new {returnUrl});
                // Alert
                controller.Danger("You must Login to access this portion of the Website");
                // Redirect
                filterContext.Result = controller.RedirectToAction("Login", "Account", routeValues);
            }

        }
Beispiel #23
0
        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" }));
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {           
            var importer = new WindowsIdentityImporter();
            WindowsIdentityImporter.Import(filterContext);

            if (IsWindowsUserAuthenticated(filterContext))
            {
                return;
            }

            if (filterContext.HttpContext.User == null || !(filterContext.HttpContext.User.Identity is FormsIdentity) || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result =
                    new RedirectToRouteResult(new RouteValueDictionary
                    {
                        { "controller", "Home" },
                        { "action", "LogOn" },
                        { "returnUrl", filterContext.HttpContext.Request.Url.PathAndQuery }
                    });
            }
            else
            {
                base.OnAuthorization(filterContext);
                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    filterContext.Result = new RedirectResult("~/Home/Unauthorized");
                }
            }
        }
 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);
 }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var pre = filterContext.HttpContext.User;

            if (!(pre is DragonPrincipal))
            {
                var ctx = ObjectFactory.GetInstance<DragonContext>();

                if (ctx != null)
                {
                    var permissionStore = ObjectFactory.GetInstance<IPermissionStore>();

                    string[] rights = new string[0];

                    if (permissionStore.HasNode(Guid.Empty))
                    {
                        rights = permissionStore.GetRightsOnNodeWithInherited(Guid.Empty)
                                                    .Where(x => x.SubjectID.Equals(ctx.CurrentUserID))
                                                    .Select(x => x.Spec)
                                                    .ToArray();
                    }

                    filterContext.HttpContext.User = new DragonPrincipal(ctx, rights);
                }
            }
        }
        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);
            }
        }
		public override void OnAuthorization(AuthorizationContext filterContext)
		{
			if (!CheckAuthToken(filterContext.HttpContext.Request.Headers))
				HandleUnauthorizedRequest(filterContext);

				base.OnAuthorization(filterContext);
		}
        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}
                                   });
            }
        }
        public void AuthorizationAttribute_Test()
        {
            var sessionItems = new System.Web.SessionState.SessionStateItemCollection();
            var controllerContext = new FakeControllerContext(TestHelper.Resolve<TopicsController>(), "http://localhost", null, null, new System.Collections.Specialized.NameValueCollection(), new System.Collections.Specialized.NameValueCollection(), new System.Web.HttpCookieCollection(), sessionItems);
            var context = new AuthorizationContext(controllerContext, new FakeActionDescriptor());
            var att = new RequireAuthorizationAttribute(UserRole.Member);
            att.Routes.Add(new StrictRoute("login", new MvcRouteHandler())
            {
                Url = "login",
                Defaults = new System.Web.Routing.RouteValueDictionary(new
                {
                    controller = "Authentication",
                    action = "Login"
                })
            });
            context.Result = null;
            att.OnAuthorization(context);
            Assert.IsInstanceOfType(context.Result, typeof(RedirectResult));

            //Test with user
            User user = ServicesTests.GetTestUser();
            sessionItems["User"] = new UserState(user, AuthenticationProvider.Facebook);
            context.Result = null;
            att.OnAuthorization(context);
            Assert.IsNull(context.Result);
        }
 protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAuthenticated)
     {
         filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
     }
     else
     {
         base.HandleUnauthorizedRequest(filterContext);
     }
 }
 protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
 {
     if (filterContext.HttpContext.User.Identity.IsAuthenticated)
     {
         string[] acceptedTypes = filterContext.HttpContext.Request.AcceptTypes;
         foreach (string type in acceptedTypes)
         {
             if (type.Contains("html"))
             {
                 if (filterContext.HttpContext.Request.IsAjaxRequest())
                 {
                     filterContext.Result = new ViewResult {
                         ViewName = "~/Views/Account/AccessDeniedAjax.cshtml"
                     }
                 }
                 ;
                 else
                 {
                     filterContext.Result = new ViewResult {
                         ViewName = "~/Views/Account/AccessDeniedHtml.cshtml"
                     }
                 };
                 break;
             }
             else if (type.Contains("javascript"))
             {
                 filterContext.Result = new ViewResult {
                     ViewName = "~/Views/Account/AccessDeniedJavaScript.cshtml"
                 };
                 break;
             }
             else if (type.Contains("xml"))
             {
                 //this will redirect to login page with forms auth you could instead serialize a custom xml payload and return here.
                 filterContext.Result = new HttpUnauthorizedResult();
             }
         }
     }
     else
     {
         base.HandleUnauthorizedRequest(filterContext);
     }
 }
Beispiel #33
0
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                this.AuthorizeUser(filterContext);
            }
            else
            {
                if (!lockdownEnabled.HasValue)
                {
                    lockdownEnabled = GlobalAuthFilterConfig.LockdownEnabled();
                }

                if (lockdownEnabled.Value)
                {
                    base.OnAuthorization(filterContext);
                }
            }
        }
 protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAuthenticated)
     {
         var viewResult = new ViewResult
         {
             ViewName = "~/Views/Account/Unauthorized.cshtml"
         };
         filterContext.Result = viewResult;
     }
     else
     {
         var viewResult = new ViewResult
         {
             ViewName = "~/Views/Account/Login.cshtml"
         };
         filterContext.Result = viewResult;
     }
 }
        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //Intercept results where person is authenticated but still doesn't have permissions
            if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (IsAPI)
                {
                    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    filterContext.HttpContext.Response.End();
                    return;

                    //filterContext.Result = new JsonResult
                    //{
                    //    Data = new { Message = "Your session has died a terrible and gruesome death" },
                    //    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    //};
                    //filterContext.HttpContext.Response.StatusCode = 401;
                    //filterContext.HttpContext.Response.StatusDescription = "Humans and robots must authenticate";
                    //filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

                    //    filterContext.RequestContext.HttpContext.Response.ClearContent();
                    //    filterContext.Result = new HttpStatusCodeResult(401);
                    //    return;
                }

                filterContext.Result = new RedirectResult("/Home");
                return;
            }

            //context.Result = new RedirectToRouteResult(
            //                       new RouteValueDictionary
            //                       {
            //                           { "action", "Contact" },
            //                           { "controller", "Home" }
            //                       });

            base.HandleUnauthorizedRequest(filterContext);
        }
 public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
 {
     returnUrl      = string.Empty;
     controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
     actionName     = filterContext.ActionDescriptor.ActionName.ToLower();
     base.OnAuthorization(filterContext);
     if (!string.IsNullOrEmpty(returnUrl))
     {
         if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
         {
             filterContext.Result = new JsonResult {
                 Data = "<h3 class='red'>错误提示:没有权限访问</h3>", JsonRequestBehavior = JsonRequestBehavior.AllowGet
             };
         }
         else
         {
             filterContext.Result = new RedirectResult(returnUrl);
         }
     }
 }
Beispiel #37
0
 protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAuthenticated)
     {
         filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
         if (NotifyUrl != null)
         {
             filterContext.Result = new RedirectResult(NotifyUrl);
         }
         else
         {
             // Redirect to Login page.
             HandleUnauthorizedRequest(filterContext);
         }
     }
     else
     {
         base.HandleUnauthorizedRequest(filterContext);
     }
 }
        public void OnBeAuthorizationShouldNotThrowOnMultipleCalls()
        {
            var options    = new AuthorizationOptions();
            var controller = Repository.Create <ControllerBase>();

            controller.As <IAuthorizationController>().Setup(x => x.AuthorizationOptions).Returns(options);

            var authorizationContext = new System.Web.Mvc.AuthorizationContext
            {
                HttpContext      = SetupHttpContextBase().Object,
                ActionDescriptor = SetupAllowAnonymous(false).Object,
                Controller       = controller.Object
            };

            var attribute = new ResourceAuthorizeAttribute();

            attribute.OnAuthorization(authorizationContext);
            // the next line should not throw
            attribute.OnAuthorization(authorizationContext);
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // If the user has a discontinued login claim or should enable 2FA, redirect them to the homepage
            var identity           = filterContext.HttpContext.User.Identity as ClaimsIdentity;
            var askUserToEnable2FA = filterContext.Controller?.TempData?.ContainsKey(GalleryConstants.AskUserToEnable2FA);

            if ((!AllowDiscontinuedLogins && ClaimsExtensions.HasDiscontinuedLoginClaims(identity)) ||
                (askUserToEnable2FA.HasValue && askUserToEnable2FA.Value))
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                {
                    area       = "",
                    controller = "Pages",
                    action     = "Home"
                }));
            }

            base.OnAuthorization(filterContext);
        }
Beispiel #40
0
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var user  = filterContext.HttpContext.User as ClaimsPrincipal;
                var token = user.FindFirst("access_token").Value;

                var request  = new GatewayAPI.HttpRequestWrapper("http://localhost:18115/api/users", Method.GET);
                var response = request.Execute(token);

                if (!((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299))
                {
                    filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
                }
            }
            else
            {
                // 401 who are you? go login and then try again
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
Beispiel #41
0
        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var user       = filterContext.HttpContext.User;
            var controller = filterContext.Controller as BaseController;

            if (!user.Identity.IsAuthenticated && (filterContext.HttpContext.Request.IsAjaxRequest() || (controller != null && controller.IsAjaxRequest)))
            {
                filterContext.Result = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        Message = "UnauthorizedAccessException: You don't have access. Please log in."
                    }
                };
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
Beispiel #42
0
 /// <summary>
 /// Processes HTTP requests that fail authorization and handles AJAX requests
 /// appropriately.
 /// </summary>
 /// <param name="filterContext">The filterContext object contains the controller, HTTP context,
 /// request context, action result, and route data.</param>
 protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
 {
     if (filterContext.HttpContext.Request.IsAjaxRequest())
     {
         filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
         filterContext.Result = new JsonResult()
         {
             JsonRequestBehavior = JsonRequestBehavior.AllowGet,
             Data = new
             {
                 ErrorType = this.GetType().Name,
                 Action    = filterContext.ActionDescriptor.ActionName,
                 Message   = _errorMsg
             }
         };
     }
     else
     {
         base.HandleUnauthorizedRequest(filterContext);
     }
 }
Beispiel #43
0
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext == null)
            {
                throw new Exception("此特性只适合于Web应用程序使用!");
            }
            if (filterContext.HttpContext.Session == null)
            {
                throw new Exception("服务器Session不可用!");
            }
            List <int> lRoleId        = (List <int>)filterContext.HttpContext.Session["Roles"];
            string     controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string     actionName     = filterContext.ActionDescriptor.ActionName;

            if (!GetRoleAction(lRoleId, controllerName, actionName))
            {
                JavaScriptResult result = new JavaScriptResult();
                result.Script        = "很抱歉,您没有操作该菜单的权限,请与管理员联系。";
                filterContext.Result = result;
            }
        }
Beispiel #44
0
        public string[] AuthorizeRoleAry = new string[] { "HomeCare.User", "HomeCare.Vip", "HomeCare.Administrator" };//本系统允许的角色 普通用户 会员 超级管理员
        /// <summary>
        /// 自定义 MVC 控制前访问权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            string Role           = string.Empty;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName     = filterContext.ActionDescriptor.ActionName;

            //数据库验证当前Controller及Action允许访问的权限
            //简单模拟 读取数据库
            if (controllerName == "Manger" && actionName == "Index")
            {
                //得到允许访问 Manger/Index 的权限值
                Role = "HomeCare.Administrator,HomeCare.Vip";
            }

            //
            string     cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[cookieName];
            FormsAuthenticationTicket authTicket = null;

            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch (Exception ex)
            {
                return;
            }
            string[] roles   = authTicket.UserData.Split(',');
            string   NowRole = string.Empty;

            foreach (var item in roles)
            {
                NowRole += item;
            }
            if (!Role.Contains(NowRole)) //没有权限访问当前控制器 ACtion
            {
                System.Web.HttpContext.Current.Response.Redirect("/Home/Login");
            }
            base.OnAuthorization(filterContext);
        }
Beispiel #45
0
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            string Role           = string.Empty;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName     = filterContext.ActionDescriptor.ActionName;
            //数据库验证当前Controller及Action允许访问的权限
            //简单模拟 读取数据库
            string MenuPath    = "/" + controllerName.ToLower() + "/" + actionName.ToLower();
            string CurrentRole = string.Empty;
            //
            string     cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[cookieName];
            FormsAuthenticationTicket authTicket = null;

            try
            {
                authTicket  = FormsAuthentication.Decrypt(authCookie.Value);
                CurrentRole = authTicket.UserData;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Redirect("/Home/Logins");
            }
            if (authTicket == null)
            {
                System.Web.HttpContext.Current.Response.Redirect("/Home/Logins");
            }
            else
            {
                //数据库验证菜单
                if (MenuPath.ToLower() != "/manger/index")
                {
                    if (!service.CheckRole(MenuPath, CurrentRole))
                    {
                        System.Web.HttpContext.Current.Response.Redirect("/Home/Logins");
                    }
                }
            }
            base.OnAuthorization(filterContext);
        }
Beispiel #46
0
        public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var attribute = GetAuthorizeAppAttribute(filterContext.ActionDescriptor);

            if (attribute != null)
            {
                var context = filterContext.HttpContext;

                string[] values = context.Request.Headers.GetValues("ClientId");

                if (values != null && values.Count() > 0)
                {
                    string clientId = values.FirstOrDefault();

                    //var app = _service.GetApp(clientId);
                    //if (app == null)
                    //{
                    filterContext.Result = new HttpUnauthorizedResult();
                    //}
                }
            }
        }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            HttpContextBase httpContext = filterContext.HttpContext;

            if (httpContext.Request.IsAuthenticated && httpContext.User != null && httpContext.User.Identity is System.Security.Claims.ClaimsIdentity)
            {
                return;
            }

            // Add header to prevent redirection to login page (see IAuthenticationProvider.Configure)
            httpContext.Request.Headers.Add("AuthNoRedirect", "1");
            string auth = httpContext.Request.Headers["Authorization"];

            if (String.IsNullOrEmpty(auth))
            {
                httpContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"Bonobo Git\"");
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                return;
            }

            byte[] encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", String.Empty));
            string value    = Encoding.ASCII.GetString(encodedDataAsBytes);
            string username = Uri.UnescapeDataString(value.Substring(0, value.IndexOf(':')));
            string password = Uri.UnescapeDataString(value.Substring(value.IndexOf(':') + 1));

            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password) && MembershipService.ValidateUser(username, password) == ValidationResult.Success)
            {
                httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(AuthenticationProvider.GetClaimsForUser(username)));
            }
            else
            {
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
            }
        }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var user    = filterContext.RequestContext.HttpContext.User.Identity as ClaimsIdentity;
            var storeId = filterContext.RouteData.Values[_storeIdKey] as string;

            if (user != null && storeId != null)
            {
                var userToken  = AuthenticationHelper.GetAuthenticatedUserToken(user);
                var repo       = AccountsRepositoryFactory.GetAccountsRepository();
                var userAccess = repo.GetUserAccessKey(userToken, storeId);
                if (userAccess != null)
                {
                    if ((userAccess.Access & _requiredAccessLevel) > 0)
                    {
                        filterContext.RequestContext.RouteData.Values.Add("_accessLevel", userAccess.Access);
                        filterContext.RequestContext.RouteData.Values.Add("_access", userAccess);
                        return;
                    }
                }
            }
            filterContext.Result = new HttpUnauthorizedResult();
        }
        private static void RedirectInternalUser(AuthorizationContext filterContext, ClaimsIdentity identity)
        {
            var statusClaim = identity.FindFirst(Core.Shared.ClaimTypes.InternalUserStatus);

            if (statusClaim == null)
            {
                return;
            }

            var status = statusClaim.Value;

            if (status == InternalUserStatus.Pending.ToString() && filterContext.ActionDescriptor.ActionName != PendingAction)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(new { controller = Controller, action = PendingAction, area = Area }));
            }
            else if (status == InternalUserStatus.Rejected.ToString() && filterContext.ActionDescriptor.ActionName != RejectedAction)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(new { controller = Controller, action = RejectedAction, area = Area }));
            }
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // Add a warning header if the API key is about to expire (or has expired)
            var identity   = filterContext.HttpContext.User.Identity as ClaimsIdentity;
            var controller = filterContext.Controller as AppController;

            if (identity != null && identity.IsAuthenticated && identity.AuthenticationType == AuthenticationTypes.ApiKey && controller != null)
            {
                var apiKey = identity.GetClaimOrDefault(NuGetClaims.ApiKey);

                var user = controller.GetCurrentUser();

                var apiKeyCredential = user.Credentials.FirstOrDefault(c => c.Value == apiKey);
                if (apiKeyCredential != null && apiKeyCredential.Expires.HasValue)
                {
                    var accountUrl = controller.NuGetContext.Config.GetSiteRoot(
                        controller.NuGetContext.Config.Current.RequireSSL).TrimEnd('/') + "/account";

                    var expirationPeriod = apiKeyCredential.Expires.Value - DateTime.UtcNow;
                    if (apiKeyCredential.HasExpired)
                    {
                        // expired warning
                        filterContext.HttpContext.Response.Headers.Add(
                            Constants.WarningHeaderName,
                            string.Format(CultureInfo.InvariantCulture, Strings.WarningApiKeyExpired, accountUrl));
                    }
                    else if (expirationPeriod.TotalDays <= controller.NuGetContext.Config.Current.WarnAboutExpirationInDaysForApiKeyV1)
                    {
                        // about to expire warning
                        filterContext.HttpContext.Response.Headers.Add(
                            Constants.WarningHeaderName,
                            string.Format(CultureInfo.InvariantCulture, Strings.WarningApiKeyAboutToExpire, expirationPeriod.TotalDays, accountUrl));
                    }
                }
            }

            base.OnAuthorization(filterContext);
        }
        async void IAuthorizationFilter.OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            IAuthorizationService service;
            var controller = filterContext.Controller as IControllerAuthorizationService;

            if (controller != null)
            {
                service = controller.AuthorizationService;
            }
            else
            {
                service = (IAuthorizationService)filterContext.HttpContext.GetOwinContext().Environment["MVC5AuthZPolicy"];
            }

            var execute = await service.AuthorizeAsync((ClaimsPrincipal)filterContext.HttpContext.User, Policy);

            if (!execute)
            {
                filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
            }

            return;
        }
Beispiel #52
0
        public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            fmpEntities fmp = new fmpEntities();

            try
            {
                string username = filterContext.RequestContext.HttpContext.Request.Headers.Get("logusr");
                string token    = filterContext.RequestContext.HttpContext.Request.Headers.Get("token");

                string password = (from u in fmp.users
                                   where u.username == username
                                   select u.password).FirstOrDefault();

                if (!utilities.Security.isValidToken(username, password, token))
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
            }
            catch (Exception e)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
Beispiel #53
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.IsChildAction || filterContext.SkipAuthorisation())
            {
                return;
            }

            var principal = (ClaimsPrincipal)filterContext.HttpContext.User;
            var identity  = (ClaimsIdentity)principal.Identity;

            var hasEmailVerifiedClaim = identity.HasClaim(c => c.Type.Equals(JwtClaimTypes.EmailVerified));

            if (hasEmailVerifiedClaim && identity.Claims.Any(c =>
                                                             c.Type.Equals(JwtClaimTypes.EmailVerified) &&
                                                             c.Value.Equals("false", StringComparison.InvariantCultureIgnoreCase)))
            {
                var redirectAddress = principal.IsInternalUser()
                    ? new RouteValueDictionary(new { controller = "Registration", action = "AdminEmailVerificationRequired", area = "Admin" })
                    : new RouteValueDictionary(new { controller = "Account", action = "EmailVerificationRequired", area = string.Empty });

                filterContext.Result = new RedirectToRouteResult(redirectAddress);
            }
        }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var user = filterContext.RequestContext.HttpContext.User.Identity as ClaimsIdentity;

            if (user != null)
            {
                var userToken = AuthenticationHelper.GetAuthenticatedUserToken(user);
                if (userToken != null)
                {
                    var repo    = AccountsRepositoryFactory.GetAccountsRepository();
                    var account = repo.GetAccountDetailsForUser(userToken);
                    if (account != null)
                    {
                        if (account.IsAdmin)
                        {
                            filterContext.RequestContext.RouteData.Values.Add("_userAccount", account);
                            return;
                        }
                    }
                }
            }
            filterContext.Result = new HttpUnauthorizedResult();
        }
Beispiel #55
0
        /// <summary>
        /// 跳去登录页(ActionVIew)
        /// </summary>
        /// <param name="filterContext"></param>
        private void JumptoLogin(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var          result = getActionResultType(filterContext);
            ActionResult ar     = null;

            switch (result.Name)
            {
            case "JavaScriptResult":
            case "JsonResult":
                ar = JsontoLogin(filterContext);
                break;

            case "PartialViewResult":
            case "ActionResult":
            case "RedirectToRouteResult":
            case "RedirectResult":
            case "ViewResult":
            default:
                ar = ViewtoLogin(filterContext);
                break;
            }
            filterContext.Result = ar;
        }
Beispiel #56
0
        public override void OnAuthorization(AuthorizationContext context)
        {
            base.OnAuthorization(context);

            if (context.Result is HttpUnauthorizedResult)
            {
                var cookie = context.RequestContext.HttpContext.Request.Cookies["Google"];

                if (cookie != null)
                {
                    context.RequestContext.HttpContext.User = new ClaimsPrincipal(

                        new MyClaimsIdentity(DecodeClaims(cookie))
                        );

                    context.Result = null;

                    return;
                }

                context.Result = new RedirectResult("/Login");
            }
        }
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
            var allow = false;

            if (_roles.Count > 0)
            {
                allow = SecurityHelper.UserHasRoles(_isAnd, _roles.ToArray());
            }
            else if (string.IsNullOrWhiteSpace(_claimType))
            {
                allow = SecurityHelper.CurrentPrincipal.Identity.IsAuthenticated;
            }
            else
            {
                allow = SecurityHelper.UserHasClaim(_claimType, _claimValue);
            }

            if (allow)
            {
                base.OnAuthorization(filterContext);
            }
            else if (string.IsNullOrWhiteSpace(RedirectAction))
            {
                var url = Properties.Settings.Default.UnauthorizedAccessUrl;
                filterContext.HttpContext.Response.Redirect(url);
            }
            else if (string.IsNullOrWhiteSpace(RedirectController))
            {
                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = controllerName, action = RedirectAction }));
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = RedirectController, action = RedirectAction }));
            }
        }
Beispiel #58
0
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string[] configs    = filterContext.HttpContext.Request.QueryString.GetValues("config");
            string[] views      = filterContext.HttpContext.Request.QueryString.GetValues("view");
            string   configName = null;
            string   view       = null;

            if (configs != null)
            {
                configName = configs[0];
            }
            if (views != null)
            {
                view = views[0];
            }

            string returnUrl = "/";

            if (!string.IsNullOrEmpty(configName) || !string.IsNullOrEmpty(view))
            {
                returnUrl += "?";
                if (!string.IsNullOrEmpty(configName))
                {
                    returnUrl += "config=" + configName;
                }
                if (!string.IsNullOrEmpty(view))
                {
                    if (!string.IsNullOrEmpty(configName))
                    {
                        returnUrl += "&";
                    }
                    returnUrl += "view=" + view;
                }
            }

            filterContext.Result = new RedirectResult("/AuthServices/SignIn?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl));
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any())
            {
                // The MVC "AllowAnonymous" attribute should overrule any authorization checks.
                return;
            }

            var claimsIdentity = filterContext.HttpContext.User.Identity as ClaimsIdentity;

            if (claimsIdentity != null)
            {
                if (claims.All(c => claimsIdentity.Claims
                               .Where(cl => cl.Type == ClaimTypes.Role).Select(cl => cl.Value).Contains(c)))
                {
                    return; // User claims are authorized
                }
            }

            // User claims are not authorized
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            //returns 401 result
            if (!filterContext.HttpContext.User.IsRegistered())
            {
                filterContext.Controller.TempData.AddUserMessage("Log in required", "Please log in to access this page", UserMessageType.Warning);
            }
            else
            {
                filterContext.Controller.TempData.AddUserMessage("No Access", "Sorry, you do not have access to the System Admin area of the site."
                                                                 + "<br/> Action: " + filterContext.RouteData.ToSourceString()
                                                                 + "<br/> Url: " + filterContext.HttpContext.Request.Url.ToString().ToHtml(), UserMessageType.Danger);
            }

            if (!filterContext.HttpContext.User.IsRegistered())
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
            else
            {
                RouteValueDictionary routeValues = new RouteValueDictionary(new { controller = "Account", action = "Unauthorized", area = "" });
                filterContext.Result = new RedirectToRouteResult(routeValues);
            }
        }