Beispiel #1
0
        public void LocatesCookie(string cookieFormat, string cookieName, string cookieValue)
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");

            request.Headers.Add("Cookie", string.Format(cookieFormat, cookieName, cookieValue));
            request.Headers.Add("RequestVerificationToken", "anything_is_fine");
            var config            = new HttpConfiguration();
            var controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            var actionContext     = new HttpActionContext(controllerContext, new Mock <HttpActionDescriptor>().Object);
            var authFilterContext = new AuthFilterContext(actionContext, string.Empty);
            var mockAntiForgery   = new Mock <IAntiForgery>();

            mockAntiForgery.Setup(x => x.CookieName).Returns(cookieName);
            AntiForgery.SetTestableInstance(mockAntiForgery.Object);

            // Act
            var vaft = new ValidateAntiForgeryTokenAttribute();

            // Assert.IsTrue(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext));
            Assert.DoesNotThrow(() => { vaft.OnActionExecuting(authFilterContext.ActionContext); });

            // Assert
            mockAntiForgery.Verify(x => x.Validate(cookieValue, It.IsAny <string>()), Times.Once());
        }
Beispiel #2
0
        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;
            }

            // TODO: Do research on this.
            //var securitySettings = EngineContext.Current.Resolve<SecuritySettings>();
            //if (!securitySettings.EnableXsrfProtectionForPublicStore)
            //   return;

            var validator = new ValidateAntiForgeryTokenAttribute();

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

            if (_ignore)
            {
                return;
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            var validator = new ValidateAntiForgeryTokenAttribute();

            validator.OnAuthorization(filterContext);
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (_görmezdenGel)
            {
                return;
            }
            if (filterContext.IsChildAction)
            {
                return;
            }
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            if (!DataAyarlarıYardımcısı.DatabaseYüklendi())
            {
                return;
            }
            var güvenlikAyarları = EngineContext.Current.Resolve <GüvenlikAyarları>();

            if (!güvenlikAyarları.YöneticiAlanıiçinXsrfKorumasınıEtkinleştir)
            {
                return;
            }
            var doğrulayıcı = new ValidateAntiForgeryTokenAttribute();

            doğrulayıcı.OnAuthorization(filterContext);
        }
        public void OnAuthorization_ForwardsAttributes()
        {
            // Arrange
            HttpContextBase             context = new Mock <HttpContextBase>().Object;
            Mock <AuthorizationContext> authorizationContextMock = new Mock <AuthorizationContext>();

            authorizationContextMock.SetupGet(ac => ac.HttpContext).Returns(context);
            bool validateCalled = false;
            Action <HttpContextBase, string> validateMethod = (c, s) =>
            {
                Assert.Same(context, c);
                Assert.Equal("some salt", s);
                validateCalled = true;
            };
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute(validateMethod)
            {
                Salt = "some salt"
            };

            // Act
            attribute.OnAuthorization(authorizationContextMock.Object);

            // Assert
            Assert.True(validateCalled);
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if ((filterContext.HttpContext.Request.HttpMethod != "POST" ||
                 _authenticationService.GetAuthenticatedUser() == null) && !ShouldValidateGet(filterContext))
            {
                return;
            }

            if (!IsAntiForgeryProtectionEnabled(filterContext))
            {
                return;
            }

            var siteSalt  = _siteService.GetSiteSettings().SiteSalt;
            var validator = new ValidateAntiForgeryTokenAttribute {
                Salt = siteSalt
            };

            validator.OnAuthorization(filterContext);

            if (filterContext.HttpContext is HackHttpContext)
            {
                filterContext.HttpContext = ((HackHttpContext)filterContext.HttpContext).OriginalHttpContextBase;
            }
        }
Beispiel #7
0
        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;
            }
            var validator = new ValidateAntiForgeryTokenAttribute();

            validator.OnAuthorization(filterContext);
        }
Beispiel #8
0
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs)
 {
     this._verbs     = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute()
     {
     };
 }
        public void ValidateThunk_DefaultsToAntiForgeryMethod()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            Assert.Equal(AntiForgery.Validate, attribute.ValidateAction);
        }
        public void SaltProperty()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            MemberHelper.TestStringProperty(attribute, "Salt", String.Empty);
        }
Beispiel #11
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
     };
 }
Beispiel #12
0
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt)
 {
     this._verbs     = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute()
     {
         //  Salt = salt
     };
 }
        public void SaltProperty()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            MemberHelper.TestStringProperty(attribute, "Salt", String.Empty, false /* testDefaultValue */, true /* allowNullAndEmpty */);
        }
        public void SaltProperty()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            MemberHelper.TestStringProperty(attribute, "Salt", String.Empty);
        }
        public void ValidateThunk_DefaultsToAntiForgeryMethod()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            Assert.Equal(AntiForgery.Validate, attribute.ValidateAction);
        }
        public void SerializerProperty()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute     = new ValidateAntiForgeryTokenAttribute();
            AntiForgeryDataSerializer         newSerializer = new AntiForgeryDataSerializer();

            // Act & Assert
            MemberHelper.TestPropertyWithDefaultInstance(attribute, "Serializer", newSerializer);
        }
        public void OnAuthorization_ThrowsIfFilterContextIsNull()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { attribute.OnAuthorization(null); }, "filterContext");
        }
Beispiel #18
0
        protected void ValidateAntiForgeryToken(params string[] salts)
        {
            var validator = new ValidateAntiForgeryTokenAttribute()
            {
                Salt = string.Join(AntiForgeryTokenHelper.Separator, salts)
            };

            validator.OnAuthorization(new AuthorizationContext(ControllerContext, new DummyActionDescriptor()));
        }
        public void OnAuthorization_ThrowsIfFilterContextIsNull()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { attribute.OnAuthorization(null); }, "filterContext");
        }
        private static void RegisterAuthenticationHandlers()
        {
            // authentication message handlers from web.config file
            var authSvcCfg = AuthServicesConfiguration.GetConfig();

            if (authSvcCfg?.MessageHandlers == null || authSvcCfg.MessageHandlers.Count <= 0)
            {
                return;
            }

            var registeredSchemes = new List <string>();

            foreach (var handlerEntry in authSvcCfg.MessageHandlers.Cast <MessageHandlerEntry>())
            {
                if (!handlerEntry.Enabled)
                {
                    Logger.Trace("The following handler is disabled " + handlerEntry.ClassName);
                    continue;
                }

                try
                {
                    var type    = Reflection.CreateType(handlerEntry.ClassName, false);
                    var handler = Activator.CreateInstance(type, handlerEntry.DefaultInclude, handlerEntry.ForceSsl) as AuthMessageHandlerBase;
                    if (handler == null)
                    {
                        throw new Exception("The handler is not a descendant of AuthMessageHandlerBase abstract class");
                    }

                    var schemeName = handler.AuthScheme.ToUpperInvariant();
                    if (registeredSchemes.Contains(schemeName))
                    {
                        Logger.Trace($"The following handler scheme '{handlerEntry.ClassName}' is already added and will be skipped");
                        continue;
                    }

                    GlobalConfiguration.Configuration.MessageHandlers.Add(handler);
                    registeredSchemes.Add(schemeName);
                    Logger.Trace($"Instantiated/Activated instance of {handler.AuthScheme}, class: {handler.GetType().FullName}");

                    if (handlerEntry.DefaultInclude)
                    {
                        DnnAuthorizeAttribute.AppendToDefaultAuthTypes(handler.AuthScheme);
                    }

                    if (handler.BypassAntiForgeryToken)
                    {
                        ValidateAntiForgeryTokenAttribute.AppendToBypassAuthTypes(handler.AuthScheme);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Cannot instantiate/activate instance of " + handlerEntry.ClassName + Environment.NewLine + ex);
                }
            }
        }
Beispiel #21
0
        public BaseController(IAuthenticationService authenticationService)
        {
            if (authenticationService == null)
            {
                throw new ArgumentNullException("authenticationService", new Exception("The dependency injection for authenticationService has failed for some reason."));
            }

            _antiForgeryValidator  = new ValidateAntiForgeryTokenAttribute();
            _authenticationService = authenticationService;
        }
Beispiel #22
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 OnAuthorizationThrowsIfFilterContextIsNull()
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                attribute.OnAuthorization(null);
            }, "filterContext");
        }
        private static void ExpectValidationException(string cookieValue, string formValue)
        {
            // Arrange
            ValidateAntiForgeryTokenAttribute attribute = GetAttribute();
            AuthorizationContext authContext            = GetAuthorizationContext(cookieValue, formValue);

            // Act & Assert
            ExceptionHelper.ExpectException <HttpAntiForgeryException>(
                delegate {
                attribute.OnAuthorization(authContext);
            }, "A required anti-forgery token was not supplied or was invalid.");
        }
        public void OnAuthorizationDoesNothingIfTokensAreValid()
        {
            // Arrange
            AuthorizationContext authContext            = GetAuthorizationContext("2001-01-01:some value:", "2001-01-02:some value:the real salt");
            ValidateAntiForgeryTokenAttribute attribute = GetAttribute();

            // Act
            attribute.OnAuthorization(authContext);

            // Assert
            // If we got to this point, no exception was thrown, so success.
        }
Beispiel #26
0
        /// <summary>
        /// 校验CSRF Token
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //根据Area分区Name将移动端的请求直接返回
            var routeDataDictionary = filterContext.RequestContext.RouteData.DataTokens;

            if (routeDataDictionary.ContainsKey("area"))
            {
                string areaName = routeDataDictionary["area"].ToString();
                if (areaName.ToLower().Contains("mobileclient"))
                {
                    return;
                }
            }

            if (!filterContext.HttpContext.Request.IsAjaxRequest() && string.Equals("post", filterContext.HttpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))
            {
                string token = string.Empty;

                token = filterContext.HttpContext.Request.Form.Get <string>("CurrentUserIdToken", string.Empty);

                if (string.IsNullOrEmpty(token))
                {
                    token = filterContext.HttpContext.Request.QueryString.Get <string>("CurrentUserIdToken", string.Empty);
                }

                if (!string.IsNullOrEmpty(token))
                {
                    token = Tunynet.Utilities.WebUtility.UrlDecode(token);
                    bool isTimeOut = false;
                    long userId    = Utility.DecryptTokenForUploadfile(token.ToString(), out isTimeOut);
                    if (userId > 0)
                    {
                        return;
                    }
                }

                ValidateAntiForgeryTokenAttribute _validator = new ValidateAntiForgeryTokenAttribute();
                try
                {
                    _validator.OnAuthorization(filterContext);
                }
                catch (Exception ex)
                {
                    LoggerFactory.GetLogger().Error(ex, "安全校验过滤器,校验CSRF Token时失败。");
                    filterContext.HttpContext.Response.Redirect(SiteUrls.Instance().SystemMessage(filterContext.Controller.TempData, new SystemMessageViewModel
                    {
                        StatusMessageType = StatusMessageType.Error,
                        Title             = "安全校验失败",
                        Body = "安全校验失败!"
                    }));
                }
            }
        }
Beispiel #27
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.HttpContext.Request.RequestType == "POST")
            {
                ValidateAntiForgeryTokenAttribute token = new ValidateAntiForgeryTokenAttribute();
                token.OnAuthorization(_filterAuthorizationContext);
            }
        }
        public void ValidationAttribute_ForwardsCallToValidateAntiForgeryTokenAuthorizationFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<AntiForgery>(GetAntiForgeryInstance());
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var attribute = new ValidateAntiForgeryTokenAttribute();

            // Act
            var filter = attribute.CreateInstance(serviceProvider);

            // Assert
            var validationFilter = filter as ValidateAntiForgeryTokenAuthorizationFilter;
            Assert.NotNull(validationFilter);
        }
Beispiel #29
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!(filterContext.RouteData.Values["validateAntiForgeryToken"] is bool &&
                  (bool)filterContext.RouteData.Values["validateAntiForgeryToken"] &&
                  filterContext.HttpContext.Request.HttpMethod == "POST" &&
                  filterContext.RequestContext.HttpContext.Request.IsAuthenticated))
            {
                return;
            }

            string host = filterContext.HttpContext.Request.Url.DnsSafeHost;

            ValidateAntiForgeryTokenAttribute validator = new ValidateAntiForgeryTokenAttribute();

            validator.OnAuthorization(filterContext);
        }
 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 void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!(filterContext.RouteData.Values["validateAntiForgeryToken"] is bool &&
                  (bool)filterContext.RouteData.Values["validateAntiForgeryToken"] &&
                  filterContext.HttpContext.Request.HttpMethod == "POST" &&
                  filterContext.RequestContext.HttpContext.Request.IsAuthenticated))
            {
                return;
            }

            ValidateAntiForgeryTokenAttribute validator = new ValidateAntiForgeryTokenAttribute {
                Salt = context.Site.ID.ToString()
            };

            validator.OnAuthorization(filterContext);
        }
        public void ValidationAttribute_ForwardsCallToValidateAntiForgeryTokenAuthorizationFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance <AntiForgery>(GetAntiForgeryInstance());
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var attribute       = new ValidateAntiForgeryTokenAttribute();

            // Act
            var filter = attribute.CreateInstance(serviceProvider);

            // Assert
            var validationFilter = filter as ValidateAntiForgeryTokenAuthorizationFilter;

            Assert.NotNull(validationFilter);
        }
        public void OnAuthorization_ForwardsAttributes()
        {
            // Arrange
            HttpContextBase context = new Mock<HttpContextBase>().Object;
            Mock<AuthorizationContext> authorizationContextMock = new Mock<AuthorizationContext>();
            authorizationContextMock.SetupGet(ac => ac.HttpContext).Returns(context);
            bool validateCalled = false;
            Action validateMethod = () =>
            {
                validateCalled = true;
            };
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute(validateMethod);

            // Act
            attribute.OnAuthorization(authorizationContextMock.Object);

            // Assert
            Assert.True(validateCalled);
        }
Beispiel #34
0
        public void MissingTokenDoesnotPassValidationTest(string cookieFormat, string cookieName, string cookieValue)
        {
            //Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");

            request.Headers.Add("Cookie", string.Format(cookieFormat, cookieName, cookieValue));
            var config            = new HttpConfiguration();
            var controllerContext = new HttpControllerContext(config, new HttpRouteData(new HttpRoute()), request);
            var actionContext     = new HttpActionContext(controllerContext, new Mock <HttpActionDescriptor>().Object);
            var authFilterContext = new AuthFilterContext(actionContext, "");
            var mockAntiForgery   = new Mock <IAntiForgery>();

            mockAntiForgery.Setup(x => x.CookieName).Returns(cookieName);
            AntiForgery.SetTestableInstance(mockAntiForgery.Object);

            //Act, Assert
            var vaft = new ValidateAntiForgeryTokenAttribute();

            Assert.IsFalse(vaft.IsAuthorized(authFilterContext));
        }
        public void OnAuthorization_ForwardsAttributes()
        {
            // Arrange
            HttpContextBase             context = new Mock <HttpContextBase>().Object;
            Mock <AuthorizationContext> authorizationContextMock = new Mock <AuthorizationContext>();

            authorizationContextMock.SetupGet(ac => ac.HttpContext).Returns(context);
            bool   validateCalled = false;
            Action validateMethod = () =>
            {
                validateCalled = true;
            };
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute(validateMethod);

            // Act
            attribute.OnAuthorization(authorizationContextMock.Object);

            // Assert
            Assert.True(validateCalled);
        }
        public void OnAuthorization_ForwardsAttributes()
        {
            // Arrange
            HttpContextBase context = new Mock<HttpContextBase>().Object;
            Mock<AuthorizationContext> authorizationContextMock = new Mock<AuthorizationContext>();
            authorizationContextMock.SetupGet(ac => ac.HttpContext).Returns(context);
            bool validateCalled = false;
            Action<HttpContextBase, string> validateMethod = (c, s) =>
            {
                Assert.Same(context, c);
                Assert.Equal("some salt", s);
                validateCalled = true;
            };
            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute(validateMethod)
            {
                Salt = "some salt"
            };

            // Act
            attribute.OnAuthorization(authorizationContextMock.Object);

            // Assert
            Assert.True(validateCalled);
        }