Example #1
0
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs)
 {
     this._verbs     = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute()
     {
     };
 }
        public void EnumToArray()
        {
            // Arrange
            IDictionary <string, HttpVerbs> enumValues = EnumToDictionary <HttpVerbs>();
            var allCombinations = EnumerableToCombinations(enumValues);

            // Act & assert
            foreach (var combination in allCombinations)
            {
                // generate all the names + values in this combination
                List <string> aggrNames  = new List <string>();
                HttpVerbs     aggrValues = (HttpVerbs)0;
                foreach (var entry in combination)
                {
                    aggrNames.Add(entry.Key);
                    aggrValues |= entry.Value;
                }

                // get the resulting array
                string[] array            = AcceptVerbsAttribute.EnumToArray(aggrValues);
                var      aggrNamesOrdered = aggrNames.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);
                var      arrayOrdered     = array.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);
                bool     match            = aggrNamesOrdered.SequenceEqual(arrayOrdered, StringComparer.OrdinalIgnoreCase);

                if (!match)
                {
                    string message = String.Format(_invalidEnumFormatString, aggrValues,
                                                   aggrNames.Aggregate((a, b) => a + ", " + b),
                                                   array.Aggregate((a, b) => a + ", " + b));
                    Assert.Fail(message);
                }
            }
        }
        public static MethodInfo ActionExists(Controller controller, string actionName, HttpVerbs expectedVerbs, params Type[] paramTypes)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }

            if (string.IsNullOrEmpty(actionName))
            {
                throw new ArgumentNullException("actionName");
            }

            int actualVerbs = 0;

            MethodInfo action = controller.GetType().GetMethod(actionName, paramTypes);

            Assert.IsNotNull(action, string.Format("The specified action '{0}' could not be found.", actionName));

            AcceptVerbsAttribute acceptVerb = Attribute.GetCustomAttribute(action, typeof(AcceptVerbsAttribute)) as AcceptVerbsAttribute;

            if (acceptVerb == null)
            {
                actualVerbs = (int)HttpVerbs.Get;
            }
            else
            {
                actualVerbs = (int)Enum.Parse(typeof(HttpVerbs), string.Join(", ", acceptVerb.Verbs.ToArray()), true);
            }

            Assert.AreEqual <int>(actualVerbs, (int)expectedVerbs);

            return(action);
        }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomValidateAntiForgeryTokenAttribute"/> class.
 /// </summary>
 /// <param name="verbs">The verbs.</param>
 /// <param name="salt">The salt.</param>
 public CustomValidateAntiForgeryTokenAttribute(HttpVerbs verbs, string salt)
 {
     _verbs     = new AcceptVerbsAttribute(verbs);
     _validator = new ValidateAntiForgeryTokenAttribute
     {
         Salt = salt
     };
 }
Example #5
0
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt)
 {
     this._verbs     = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute()
     {
         //  Salt = salt
     };
 }
        public void IsValidForRequestThrowsIfControllerContextIsNull()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { attr.IsValidForRequest(null, null); }, "controllerContext");
        }
        public void IsValidForRequestThrowsIfControllerContextIsNull()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { attr.IsValidForRequest(null, null); }, "controllerContext");
        }
Example #8
0
        public override bool IsValidForRequest(ControllerContext cc, MethodInfo mi)
        {
            var result = true;

            if (AcceptVerbs.HasValue)
            {
                result = new AcceptVerbsAttribute(AcceptVerbs.Value).IsValidForRequest(cc, mi);
            }

            return(result);
        }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomValidateAntiForgeryTokenAttribute"/> class.
        /// </summary>
        /// <param name="verbs">The verbs.</param>
        /// <param name="salt">The salt.</param>
        public CustomValidateAntiForgeryTokenAttribute(HttpVerbs verbs, string salt)
        {
            Verbs = verbs;
            Salt  = salt;

            AcceptVerbsAttribute = new AcceptVerbsAttribute(Verbs);
            Validator            = new ValidateAntiForgeryTokenAttribute
            {
                Salt = Salt
            };
        }
        public void IsValidForRequestReturnsTrueIfHttpVerbIsOverridden()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("put");
            ControllerContext context = GetControllerContextWithHttpVerb("POST", "PUT", null, null);

            // Act
            bool result = attr.IsValidForRequest(context, null);

            // Assert
            Assert.True(result);
        }
        public void IsValidForRequestReturnsTrueIfHttpVerbIsInVerbsCollection()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");
            ControllerContext context = GetControllerContextWithHttpVerb("POST");

            // Act
            bool result = attr.IsValidForRequest(context, null);

            // Assert
            Assert.True(result);
        }
        public void IsValidForRequestReturnsTrueIfHttpVerbIsOverridden()
        {
            // Arrange
            AcceptVerbsAttribute attr    = new AcceptVerbsAttribute("put");
            ControllerContext    context = GetControllerContextWithHttpVerb("POST", "PUT", null, null);

            // Act
            bool result = attr.IsValidForRequest(context, null);

            // Assert
            Assert.IsTrue(result);
        }
        public void IsValidForRequestReturnsTrueIfHttpVerbIsInVerbsCollection()
        {
            // Arrange
            AcceptVerbsAttribute attr    = new AcceptVerbsAttribute("get", "post");
            ControllerContext    context = GetControllerContextWithHttpVerb("POST");

            // Act
            bool result = attr.IsValidForRequest(context, null);

            // Assert
            Assert.IsTrue(result);
        }
        /// <summary>
        /// More advanced configuration: allows to provide actions to be ignored from the check.
        /// </summary>
        /// <param name="verbs">HTTP request type for which anti forgery checks will be performed. Typically a POST.</param>
        /// <param name="actionsToNotValidate">A list of case insensitive strings carrying action names for which anti forgery checks should not be performed.
        /// Typically you might want to exclude POSTs which don't submit any [important] data and hence data tampering risk does not exist.</param>
        public ValidateAntiForgeryTokenControllerLevelAttribute(HttpVerbs verbs, params string[] actionsToNotValidate)
        {
            // use custom order to make sure this filter runs after any authorization filters
            // otherwise the principal on the thread/request will not be set and the anti forgery check will fail
            Order = 100;

            _verbs = new AcceptVerbsAttribute(verbs);

            if (actionsToNotValidate != null)
            {
                _actionsToNotValidate = actionsToNotValidate.Select(x => x.ToLower()).ToArray();
            }
        }
Example #15
0
        public void VerbsPropertyFromEnumConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(HttpVerbs.Get | HttpVerbs.Post);

            // Act
            ReadOnlyCollection <string> collection = attr.Verbs as ReadOnlyCollection <string>;

            // Assert
            Assert.NotNull(collection);
            Assert.Equal(2, collection.Count);
            Assert.Equal("GET", collection[0]);
            Assert.Equal("POST", collection[1]);
        }
Example #16
0
            protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
            {
                if (actionName == restActionToken)
                {
                    // cleanup the restActionToken we set earlier
                    controllerContext.RequestContext.RouteData.Values["action"] = null;

                    List <ActionDescriptor> matches = new List <ActionDescriptor>();
                    foreach (ActionDescriptor ad in controllerDescriptor.GetCanonicalActions())
                    {
                        object[] acceptVerbs = ad.GetCustomAttributes(typeof(AcceptVerbsAttribute), false);
                        if (acceptVerbs.Length > 0)
                        {
                            foreach (object o in acceptVerbs)
                            {
                                AcceptVerbsAttribute ava = o as AcceptVerbsAttribute;
                                if (ava != null)
                                {
                                    if (ava.Verbs.Contains(controllerContext.HttpContext.Request.GetHttpMethodOverride().ToUpperInvariant()))
                                    {
                                        matches.Add(ad);
                                    }
                                }
                            }
                        }
                    }
                    switch (matches.Count)
                    {
                    case 0:
                        break;

                    case 1:
                        ActionDescriptor ad = matches[0];
                        actionName = ad.ActionName;
                        controllerContext.RequestContext.RouteData.Values["action"] = actionName;
                        return(ad);

                    default:
                        StringBuilder matchesString = new StringBuilder(matches[0].ActionName);
                        for (int index = 1; index < matches.Count; index++)
                        {
                            matchesString.Append(", ");
                            matchesString.Append(matches[index].ActionName);
                        }
                        return(new ResourceErrorActionDescriptor(controllerDescriptor, HttpStatusCode.Conflict, string.Format(CultureInfo.CurrentCulture, "Error dispatching on controller {0}, conflicting actions matched: (1)", controllerDescriptor.ControllerName, matchesString.ToString())));
                    }
                }
                return(base.FindAction(controllerContext, controllerDescriptor, actionName) ??
                       new ResourceErrorActionDescriptor(controllerDescriptor, HttpStatusCode.NotFound, string.Format(CultureInfo.CurrentCulture, "Error dispatching on controller {0}, no actions matched", controllerDescriptor.ControllerName)));
            }
Example #17
0
        public void VerbsPropertyFromStringArrayConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");

            // Act
            ReadOnlyCollection <string> collection = attr.Verbs as ReadOnlyCollection <string>;

            // Assert
            Assert.NotNull(collection);
            Assert.Equal(2, collection.Count);
            Assert.Equal("get", collection[0]);
            Assert.Equal("post", collection[1]);
        }
        /// <summary>
        /// More advanced configuration: allows to provide actions to be ignored from the check.
        /// </summary>
        /// <param name="verbs">HTTP request type for which anti forgery checks will be performed. Typically a POST.</param>
        /// <param name="actionsToNotValidate">A list of case insensitive strings carrying action names for which anti forgery checks should not be performed.
        /// Typically you might want to exclude POSTs which don't submit any [important] data and hence data tampering risk does not exist.</param>
        public ValidateAntiForgeryTokenOnControllerAttribute(HttpVerbs verbs, params string[] actionsToNotValidate)
        {
            // n o t e: must use custom order to make sure this filter runs after our CommunispaceAuthorize filter
            // otherwise the principal on the thread/request will not be set and the anti forgery check will fail
            // because of the mismatched user names in the token vs. current
            Order = 100;

            _verbs = new AcceptVerbsAttribute(verbs);

            if (actionsToNotValidate != null)
            {
                _actionsToNotValidate = actionsToNotValidate.Select(x => x.ToLower()).ToArray();
            }
        }
        public void VerbsPropertyFromStringArrayConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");

            // Act
            ReadOnlyCollection <string> collection = attr.Verbs as ReadOnlyCollection <string>;

            // Assert
            Assert.IsNotNull(collection, "Verbs property should have returned read-only collection.");
            Assert.AreEqual(2, collection.Count);
            Assert.AreEqual("get", collection[0]);
            Assert.AreEqual("post", collection[1]);
        }
        public void VerbsPropertyFromEnumConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(HttpVerbs.Get | HttpVerbs.Post);

            // Act
            ReadOnlyCollection <string> collection = attr.Verbs as ReadOnlyCollection <string>;

            // Assert
            Assert.IsNotNull(collection, "Verbs property should have returned read-only collection.");
            Assert.AreEqual(2, collection.Count);
            Assert.AreEqual("GET", collection[0]);
            Assert.AreEqual("POST", collection[1]);
        }
 protected SecurityControllerBase(IUserIdentity userIdentity, IAppSensor appSensor)
 {
     if (appSensor == null)
     {
         throw new ArgumentNullException("appSensor");
     }
     if (userIdentity == null)
     {
         throw new ArgumentNullException("userIdentity");
     }
     _verbs        = new AcceptVerbsAttribute(HttpVerbs.Post);
     _validator    = new ValidateAntiForgeryTokenAttribute();
     Logger        = Log.Logger;
     _userIdentity = userIdentity;
     _appSensor    = appSensor;
 }
        public override bool IsValidForRequest(ControllerContext cc, MethodInfo mi)
        {
            bool result = true;

            if (AcceptVerbs.HasValue)
                result = new AcceptVerbsAttribute(AcceptVerbs.Value).IsValidForRequest(cc, mi);

            if (result && EnsureXSRFSafe)
            {
                if (!AcceptVerbs.HasValue || (AcceptVerbs.Value & HttpVerbs.Post) == 0)
                    throw new ArgumentException(
                        "When this.XSRFSafe is true, this.AcceptVerbs must include HttpVerbs.Post");

                result = new XSRFSafeAttribute().IsValidForRequest(cc, mi);
            }

            return result;
        }
        public void VerbsPropertyFromEnumConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(HttpVerbs.Get | HttpVerbs.Post);

            // Act
            ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;

            // Assert
            Assert.NotNull(collection);
            Assert.Equal(2, collection.Count);
            Assert.Equal("GET", collection[0]);
            Assert.Equal("POST", collection[1]);
        }
 public AntiForgeryTokenFilter(HttpVerbs verbs)
 {
     _verbs = new AcceptVerbsAttribute(verbs);
 }
Example #25
0
 public UnsealedAcceptVerbsAttribute(HttpVerbs verbs)
 {
     _Verbs = new AcceptVerbsAttribute(verbs);
 }
 public GlobalValidateAntiForgeryToken(HttpVerbs verbs)
 {
     this._verbs     = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute();
 }
 protected AntiForgeryControllerBase(HttpVerbs verbs)
 {
     _verbs     = new AcceptVerbsAttribute(verbs);
     _validator = new ValidateAntiForgeryTokenAttribute();
 }
 public ValidateAntiForgeryTokenOnVerbsAttribute(HttpVerbs verbs)
 {
     _validator = new ValidateAntiForgeryTokenAttribute();
     _verbs     = new AcceptVerbsAttribute(verbs);
 }
        public void VerbsPropertyFromStringArrayConstructor()
        {
            // Arrange
            AcceptVerbsAttribute attr = new AcceptVerbsAttribute("get", "post");

            // Act
            ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;

            // Assert
            Assert.NotNull(collection);
            Assert.Equal(2, collection.Count);
            Assert.Equal("get", collection[0]);
            Assert.Equal("post", collection[1]);
        }