public void GenerateRequestToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
        {
            // Arrange
            var cookieToken = new AntiforgeryToken()
            {
                IsCookieToken = true
            };

            var httpContext = new DefaultHttpContext();
            httpContext.User = new ClaimsPrincipal(new MyAuthenticatedIdentityWithoutUsername());

            var options = new AntiforgeryOptions();
            var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;

            var tokenProvider = new DefaultAntiforgeryTokenGenerator(
                claimUidExtractor: claimUidExtractor,
                additionalDataProvider: null);

            // Act & assert
            var exception = Assert.Throws<InvalidOperationException>(
                    () => tokenProvider.GenerateRequestToken(httpContext, cookieToken));
            Assert.Equal(
                "The provided identity of type " +
                $"'{typeof(MyAuthenticatedIdentityWithoutUsername).FullName}' " +
                "is marked IsAuthenticated = true but does not have a value for Name. " +
                "By default, the antiforgery system requires that all authenticated identities have a unique Name. " +
                "If it is not possible to provide a unique Name for this identity, " +
                "consider extending IAntiforgeryAdditionalDataProvider by overriding the " +
                "DefaultAntiforgeryAdditionalDataProvider " +
                "or a custom type that can provide some form of unique identifier for the current user.",
                exception.Message);
        }
        public SiteAntiforgeryTokenStore(IOptions<AntiforgeryOptions> optionsAccessor)
        {
            if (optionsAccessor == null)
            {
                throw new ArgumentNullException(nameof(optionsAccessor));
            }

            _options = optionsAccessor.Value;
        }
 public DefaultAntiforgery(
     IOptions<AntiforgeryOptions> antiforgeryOptionsAccessor,
     IAntiforgeryTokenGenerator tokenGenerator,
     IAntiforgeryTokenSerializer tokenSerializer,
     IAntiforgeryTokenStore tokenStore,
     ILoggerFactory loggerFactory)
 {
     _options = antiforgeryOptionsAccessor.Value;
     _tokenGenerator = tokenGenerator;
     _tokenSerializer = tokenSerializer;
     _tokenStore = tokenStore;
     _logger = loggerFactory.CreateLogger<DefaultAntiforgery>();
 }
        public void GetCookieToken_CookieIsEmpty_ReturnsNull()
        {
            // Arrange
            var httpContext = GetHttpContext(_cookieName, string.Empty);
            var options = new AntiforgeryOptions()
            {
                CookieName = _cookieName
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var token = tokenStore.GetCookieToken(httpContext);

            // Assert
            Assert.Null(token);
        }
        public void GetCookieToken_CookieDoesNotExist_ReturnsNull()
        {
            // Arrange
            var httpContext = GetHttpContext(new RequestCookieCollection());
            var options = new AntiforgeryOptions()
            {
                CookieName = _cookieName
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var token = tokenStore.GetCookieToken(httpContext);

            // Assert
            Assert.Null(token);
        }
        public void GetCookieToken_CookieIsNotEmpty_ReturnsToken()
        {
            // Arrange
            var expectedToken = "valid-value";
            var httpContext = GetHttpContext(_cookieName, expectedToken);

            var options = new AntiforgeryOptions()
            {
                CookieName = _cookieName
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var token = tokenStore.GetCookieToken(httpContext);

            // Assert
            Assert.Equal(expectedToken, token);
        }
Example #7
0
        public async Task GetRequestTokens_CookieIsEmpty_ReturnsNullTokens()
        {
            // Arrange
            var httpContext = GetHttpContext();

            httpContext.Request.Form = FormCollection.Empty;

            var options = new AntiforgeryOptions
            {
                Cookie        = { Name = "cookie-name" },
                FormFieldName = "form-field-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Null(tokenSet.CookieToken);
            Assert.Null(tokenSet.RequestToken);
        }
Example #8
0
        public void SaveCookieToken_NonNullAntiforgeryOptionsConfigureCookieOptionsDomain_UsesCookieOptionsDomain()
        {
            // Arrange
            var expectedCookieDomain = "microsoft.com";
            var token       = "serialized-value";
            var cookies     = new MockResponseCookieCollection();
            var httpContext = new Mock <HttpContext>();

            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(cookies);
            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/vdir1");
            httpContext
            .SetupGet(hc => hc.Request.Path)
            .Returns("/index.html");
            var options = new AntiforgeryOptions
            {
                Cookie =
                {
                    Name   = _cookieName,
                    Domain = expectedCookieDomain
                }
            };
            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            tokenStore.SaveCookieToken(httpContext.Object, token);

            // Assert
            Assert.Equal(1, cookies.Count);
            Assert.NotNull(cookies);
            Assert.Equal(_cookieName, cookies.Key);
            Assert.Equal("serialized-value", cookies.Value);
            Assert.True(cookies.Options !.HttpOnly);
            Assert.Equal("/vdir1", cookies.Options.Path);
            Assert.Equal(expectedCookieDomain, cookies.Options.Domain);
        }
        private DefaultAntiforgery GetAntiforgery(
            HttpContext httpContext,
            AntiforgeryOptions options = null,
            IAntiforgeryTokenGenerator tokenGenerator   = null,
            IAntiforgeryTokenSerializer tokenSerializer = null,
            IAntiforgeryTokenStore tokenStore           = null)
        {
            var optionsManager = new TestOptionsManager();

            if (options != null)
            {
                optionsManager.Value = options;
            }

            var loggerFactory = httpContext.RequestServices.GetRequiredService <ILoggerFactory>();

            return(new DefaultAntiforgery(
                       antiforgeryOptionsAccessor: optionsManager,
                       tokenGenerator: tokenGenerator,
                       tokenSerializer: tokenSerializer,
                       tokenStore: tokenStore,
                       loggerFactory: loggerFactory));
        }
Example #10
0
        public async Task GetRequestTokens_ReadFormAsyncThrowsInvalidDataException_ThrowsAntiforgeryValidationException()
        {
            // Arrange
            var exception   = new InvalidDataException();
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(r => r.Request.Cookies).Returns(Mock.Of <IRequestCookieCollection>());
            httpContext.SetupGet(r => r.Request.HasFormContentType).Returns(true);
            httpContext.Setup(r => r.Request.ReadFormAsync(It.IsAny <CancellationToken>())).Throws(exception);

            var options = new AntiforgeryOptions
            {
                Cookie        = { Name = "cookie-name" },
                FormFieldName = "form-field-name",
                HeaderName    = null,
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act & Assert
            var ex = await Assert.ThrowsAsync <AntiforgeryValidationException>(() => tokenStore.GetRequestTokensAsync(httpContext.Object));

            Assert.Same(exception, ex.InnerException);
        }
Example #11
0
        public async Task GetRequestTokens_BothHeaderValueAndFormFieldsEmpty_ReturnsNullTokens()
        {
            // Arrange
            var httpContext = GetHttpContext("cookie-name", "cookie-value");

            httpContext.Request.ContentType = "application/x-www-form-urlencoded";
            httpContext.Request.Form        = FormCollection.Empty;

            var options = new AntiforgeryOptions
            {
                Cookie        = { Name = "cookie-name" },
                FormFieldName = "form-field-name",
                HeaderName    = "header-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Equal("cookie-value", tokenSet.CookieToken);
            Assert.Null(tokenSet.RequestToken);
        }
Example #12
0
 private void SetAntiforgeryOptions(AntiforgeryOptions options)
 {
     options.Cookie.Name = "antiforgery-token";
 }
        public async Task GetRequestTokens_CookieIsEmpty_ReturnsNullTokens()
        {
            // Arrange
            var httpContext = GetHttpContext(new RequestCookieCollection());
            httpContext.Request.Form = FormCollection.Empty;

            var options = new AntiforgeryOptions()
            {
                CookieName = "cookie-name",
                FormFieldName = "form-field-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Null(tokenSet.CookieToken);
            Assert.Null(tokenSet.RequestToken);
        }
        public static IAppBuilder UseAntiforgeryMiddleware(this IAppBuilder builder, AntiforgeryOptions options = null)
        {
            var hostOptions = options ?? new AntiforgeryOptions();

            return builder.Use(typeof(AntiforgeryMiddleware), hostOptions);
        }
 public ApiIgnoreAntiforgeryTokenAttributeImpl(IAntiforgery antiforgery, IOptions <AntiforgeryOptions> options)
 {
     _antiforgery = antiforgery;
     _options     = options.Value;
 }
        public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag)
        {
            // Arrange
            var token = "serialized-value";
            bool defaultCookieSecureValue = expectedCookieSecureFlag ?? false; // pulled from config; set by ctor
            var cookies = new MockResponseCookieCollection();

            var mockHttpContext = new Mock<HttpContext>();
            mockHttpContext
                .Setup(o => o.Response.Cookies)
                .Returns(cookies);

            var options = new AntiforgeryOptions()
            {
                CookieName = _cookieName,
                RequireSsl = requireSsl
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            tokenStore.SaveCookieToken(mockHttpContext.Object, token);

            // Assert
            Assert.Equal(1, cookies.Count);
            Assert.NotNull(cookies);
            Assert.Equal(_cookieName, cookies.Key);
            Assert.Equal("serialized-value", cookies.Value);
            Assert.True(cookies.Options.HttpOnly);
            Assert.Equal(defaultCookieSecureValue, cookies.Options.Secure);
        }
        public async Task GetFormToken_FormFieldIsValid_ReturnsToken()
        {
            // Arrange
            var httpContext = GetHttpContext("cookie-name", "cookie-value");
            httpContext.Request.ContentType = "application/x-www-form-urlencoded";
            httpContext.Request.Form = new FormCollection(new Dictionary<string, StringValues>
            {
                { "form-field-name", "form-value" },
            });
            httpContext.Request.Headers.Add("header-name", "header-value"); // form value has priority.

            var options = new AntiforgeryOptions()
            {
                CookieName = "cookie-name",
                FormFieldName = "form-field-name",
                HeaderName = "header-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokens = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Equal("cookie-value", tokens.CookieToken);
            Assert.Equal("form-value", tokens.RequestToken);
        }
        public async Task GetRequestTokens_NonFormContentType_NoHeaderToken_ReturnsNullToken()
        {
            // Arrange
            var httpContext = GetHttpContext("cookie-name", "cookie-value");
            httpContext.Request.ContentType = "application/json";

            // Will not be accessed
            httpContext.Request.Form = null;

            var options = new AntiforgeryOptions()
            {
                CookieName = "cookie-name",
                FormFieldName = "form-field-name",
                HeaderName = "header-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Equal("cookie-value", tokenSet.CookieToken);
            Assert.Null(tokenSet.RequestToken);
        }
 public AntiForgeryTokenStore(IOptions <AntiforgeryOptions> optionsAccessor, IAntiforgeryTokenSerializer tokenSerializer)
 {
     _defaultStore    = new DefaultAntiforgeryTokenStore(optionsAccessor);
     _options         = optionsAccessor.Value;
     _tokenSerializer = tokenSerializer;
 }
 static void action(AntiforgeryOptions o)
 {
 }
        public async Task GetRequestTokens_BothFieldsEmpty_ReturnsNullTokens()
        {
            // Arrange
            var httpContext = GetHttpContext("cookie-name", "cookie-value");
            httpContext.Request.ContentType = "application/x-www-form-urlencoded";
            httpContext.Request.Form = FormCollection.Empty;

            var options = new AntiforgeryOptions()
            {
                CookieName = "cookie-name",
                FormFieldName = "form-field-name",
                HeaderName = "header-name",
            };

            var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));

            // Act
            var tokenSet = await tokenStore.GetRequestTokensAsync(httpContext);

            // Assert
            Assert.Equal("cookie-value", tokenSet.CookieToken);
            Assert.Null(tokenSet.RequestToken);
        }
Example #22
0
        public static IAppBuilder UseAntiforgeryMiddleware(this IAppBuilder builder, AntiforgeryOptions options = null)
        {
            var hostOptions = options ?? new AntiforgeryOptions();

            return(builder.Use(typeof(AntiforgeryMiddleware), hostOptions));
        }