• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# AntiForgeryToken类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中AntiForgeryToken的典型用法代码示例。如果您正苦于以下问题:C# AntiForgeryToken类的具体用法?C# AntiForgeryToken怎么用?C# AntiForgeryToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AntiForgeryToken类属于命名空间,在下文中一共展示了AntiForgeryToken类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ValidateTokens_Success_AuthenticatedUserWithUsername

        public void ValidateTokens_Success_AuthenticatedUserWithUsername()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>().Object;
            var identity = GetAuthenticatedIdentity("the-user");
            var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            var fieldtoken = new AntiForgeryToken()
            {
                SecurityToken = sessionToken.SecurityToken,
                Username = "THE-USER",
                IsSessionToken = false,
                AdditionalData = "some-additional-data"
            };

            var mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
                                      .Returns(true);

            var config = new AntiForgeryOptions();
            var tokenProvider = new AntiForgeryTokenProvider(
                config: config,
                claimUidExtractor: new Mock<IClaimUidExtractor>().Object,
                additionalDataProvider: mockAdditionalDataProvider.Object);

            // Act
            tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);

            // Assert
            // Nothing to assert - if we got this far, success!
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:30,代码来源:TokenProviderTest.cs


示例2: GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiForgeryContext

        public void GetCookieToken_CookieIsMissingInRequest_LooksUpCookieInAntiForgeryContext()
        {
            // Arrange
            var requestCookies = new Mock<IReadableStringCollection>();
            requestCookies
                .Setup(o => o.Get(It.IsAny<string>()))
                .Returns(string.Empty);
            var mockHttpContext = new Mock<HttpContext>();
            mockHttpContext
                .Setup(o => o.Request.Cookies)
                .Returns(requestCookies.Object);
            var contextAccessor = new ScopedInstance<AntiForgeryContext>();
            mockHttpContext.SetupGet(o => o.RequestServices)
                           .Returns(GetServiceProvider(contextAccessor));

            // add a cookie explicitly.
            var cookie = new AntiForgeryToken();
            contextAccessor.Value = new AntiForgeryContext() { CookieToken = cookie };
            var config = new AntiForgeryOptions()
            {
                CookieName = _cookieName
            };

            var tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: null);

            // Act
            var token = tokenStore.GetCookieToken(mockHttpContext.Object);

            // Assert
            Assert.Equal(cookie, token);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:33,代码来源:AntiForgeryTokenStoreTest.cs


示例3: Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful

        public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful()
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            //"01" // Version
            //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
            //+ "00" // IsSessionToken
            //+ "01" // IsClaimsBased
            //+ "6F1648E97249AA58754036A67E248CF044F07ECFB0ED387556CE029A4F9A40E0" // ClaimUid
            //+ "05" // AdditionalData length header
            //+ "E282AC3437"; // AdditionalData ("€47") as UTF8
            var token = new AntiForgeryToken()
            {
                SecurityToken = _securityToken,
                IsSessionToken = false,
                ClaimUid = _claimUid,
                AdditionalData = "€47"
            };

            // Act
            var actualSerializedData = testSerializer.Serialize(token);
            var deserializedToken = testSerializer.Deserialize(actualSerializedData);

            // Assert
            AssertTokensEqual(token, deserializedToken);
            _dataProtector.Verify();
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:28,代码来源:AntiForgeryTokenSerializerTest.cs


示例4: Serialize

		public string Serialize(AntiForgeryToken token)
		{
			string result;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
				{
					binaryWriter.Write(1);
					binaryWriter.Write(token.SecurityToken.GetData());
					binaryWriter.Write(token.IsSessionToken);
					if (!token.IsSessionToken)
					{
						if (token.ClaimUid != null)
						{
							binaryWriter.Write(true);
							binaryWriter.Write(token.ClaimUid.GetData());
						}
						else
						{
							binaryWriter.Write(false);
							binaryWriter.Write(token.Username);
						}
						binaryWriter.Write(token.AdditionalData);
					}
					binaryWriter.Flush();
					result = this._cryptoSystem.Protect(memoryStream.ToArray());
				}
			}
			return result;
		}
开发者ID:BikS2013,项目名称:bUtility,代码行数:30,代码来源:AntiForgeryTokenSerializer.cs


示例5: GenerateFormToken

		public AntiForgeryToken GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken)
		{
			AntiForgeryToken antiForgeryToken = new AntiForgeryToken
			{
				SecurityToken = cookieToken.SecurityToken,
				IsSessionToken = false
			};
			bool flag = false;
			if (identity != null && identity.IsAuthenticated)
			{
				if (!this._config.SuppressIdentityHeuristicChecks)
				{
					flag = true;
				}
				antiForgeryToken.ClaimUid = this._claimUidExtractor.ExtractClaimUid(identity);
				if (antiForgeryToken.ClaimUid == null)
				{
					antiForgeryToken.Username = identity.Name;
				}
			}
			if (this._config.AdditionalDataProvider != null)
			{
				antiForgeryToken.AdditionalData = this._config.AdditionalDataProvider.GetAdditionalData(httpContext);
			}
			if (flag && string.IsNullOrEmpty(antiForgeryToken.Username) && 
				antiForgeryToken.ClaimUid == null && 
				string.IsNullOrEmpty(antiForgeryToken.AdditionalData))
			{
				throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, WebPageResources.TokenValidator_AuthenticatedUserWithoutUsername, new object[]
				{
					identity.GetType()
				}));
			}
			return antiForgeryToken;
		}
开发者ID:BikS2013,项目名称:bUtility,代码行数:35,代码来源:TokenValidator.cs


示例6: GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData

        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
        {
            // Arrange
            var cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };

            var httpContext = new Mock<HttpContext>().Object;
            ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername();
            var config = new AntiForgeryOptions();
            IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object;

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

            // Act & assert
            var ex =
                Assert.Throws<InvalidOperationException>(
                    () => tokenProvider.GenerateFormToken(httpContext, identity, cookieToken));
            Assert.Equal(
                "The provided identity of type " +
                "'Microsoft.AspNet.Mvc.Core.Test.TokenProviderTest+MyAuthenticatedIdentityWithoutUsername' " +
                "is marked IsAuthenticated = true but does not have a value for Name. " +
                "By default, the anti-forgery 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 IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider " +
                "or a custom type that can provide some form of unique identifier for the current user.",
                ex.Message);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:32,代码来源:TokenProviderTest.cs


示例7: GenerateFormToken_AnonymousUser

        public void GenerateFormToken_AnonymousUser()
        {
            // Arrange
            var cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            var httpContext = new Mock<HttpContext>().Object;
            var mockIdentity = new Mock<ClaimsIdentity>();
            mockIdentity.Setup(o => o.IsAuthenticated)
                        .Returns(false);

            var config = new AntiForgeryOptions();

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

            // Act
            var fieldToken = tokenProvider.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Empty(fieldToken.Username);
            Assert.Null(fieldToken.ClaimUid);
            Assert.Empty(fieldToken.AdditionalData);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:27,代码来源:TokenProviderTest.cs


示例8: DeserializeImpl

		private static AntiForgeryToken DeserializeImpl(BinaryReader reader)
		{
			byte b = reader.ReadByte();
			if (b != 1)
			{
				return null;
			}
			AntiForgeryToken antiForgeryToken = new AntiForgeryToken();
			byte[] data = reader.ReadBytes(16);
			antiForgeryToken.SecurityToken = new BinaryBlob(128, data);
			antiForgeryToken.IsSessionToken = reader.ReadBoolean();
			if (!antiForgeryToken.IsSessionToken)
			{
				bool flag = reader.ReadBoolean();
				if (flag)
				{
					byte[] data2 = reader.ReadBytes(32);
					antiForgeryToken.ClaimUid = new BinaryBlob(256, data2);
				}
				else
				{
					antiForgeryToken.Username = reader.ReadString();
				}
				antiForgeryToken.AdditionalData = reader.ReadString();
			}
			if (reader.BaseStream.ReadByte() != -1)
			{
				return null;
			}
			return antiForgeryToken;
		}
开发者ID:BikS2013,项目名称:bUtility,代码行数:31,代码来源:AntiForgeryTokenSerializer.cs


示例9: ValidateTokens

        public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
        {
            // Were the tokens even present at all?
            if (sessionToken == null)
            {
                throw HttpAntiForgeryException.CreateCookieMissingException(_config.CookieName);
            }
            if (fieldToken == null)
            {
                throw HttpAntiForgeryException.CreateFormFieldMissingException(_config.FormFieldName);
            }

            // Do the tokens have the correct format?
            if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
            {
                throw HttpAntiForgeryException.CreateTokensSwappedException(_config.CookieName, _config.FormFieldName);
            }

            // Are the security tokens embedded in each incoming token identical?
            if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken))
            {
                throw HttpAntiForgeryException.CreateSecurityTokenMismatchException();
            }

            // Is the incoming token meant for the current user?
            string currentUsername = String.Empty;
            BinaryBlob currentClaimUid = null;

            if (identity != null && identity.IsAuthenticated)
            {
                currentClaimUid = _claimUidExtractor.ExtractClaimUid(identity);
                if (currentClaimUid == null)
                {
                    currentUsername = identity.Name ?? String.Empty;
                }
            }

            // OpenID and other similar authentication schemes use URIs for the username.
            // These should be treated as case-sensitive.
            bool useCaseSensitiveUsernameComparison = currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
                || currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase);

            if (!String.Equals(fieldToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
            {
                throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, currentUsername);
            }
            if (!Equals(fieldToken.ClaimUid, currentClaimUid))
            {
                throw HttpAntiForgeryException.CreateClaimUidMismatchException();
            }

            // Is the AdditionalData valid?
            if (_config.AdditionalDataProvider != null && !_config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))
            {
                throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException();
            }
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:57,代码来源:TokenValidator.cs


示例10: UsernameProperty

        public void UsernameProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.Equal("", token.Username);

            // Act & assert - 2
            token.Username = "my username";
            Assert.Equal("my username", token.Username);

            // Act & assert - 3
            token.Username = null;
            Assert.Equal("", token.Username);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:16,代码来源:AntiForgeryTokenTest.cs


示例11: IsSessionTokenProperty

        public void IsSessionTokenProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.False(token.IsSessionToken);

            // Act & assert - 2
            token.IsSessionToken = true;
            Assert.True(token.IsSessionToken);

            // Act & assert - 3
            token.IsSessionToken = false;
            Assert.False(token.IsSessionToken);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:16,代码来源:AntiForgeryTokenTest.cs


示例12: AdditionalDataProperty

        public void AdditionalDataProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.Equal("", token.AdditionalData);

            // Act & assert - 2
            token.AdditionalData = "additional data";
            Assert.Equal("additional data", token.AdditionalData);

            // Act & assert - 3
            token.AdditionalData = null;
            Assert.Equal("", token.AdditionalData);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:16,代码来源:AntiForgeryTokenTest.cs


示例13: GenerateFormToken

        public AntiForgeryToken GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken)
        {
            Contract.Assert(IsCookieTokenValid(cookieToken));

            AntiForgeryToken formToken = new AntiForgeryToken()
            {
                SecurityToken = cookieToken.SecurityToken,
                IsSessionToken = false
            };

            bool requireAuthenticatedUserHeuristicChecks = false;
            // populate Username and ClaimUid
            if (identity != null && identity.IsAuthenticated)
            {
                if (!_config.SuppressIdentityHeuristicChecks)
                {
                    // If the user is authenticated and heuristic checks are not suppressed,
                    // then Username, ClaimUid, or AdditionalData must be set.
                    requireAuthenticatedUserHeuristicChecks = true;
                }

                formToken.ClaimUid = _claimUidExtractor.ExtractClaimUid(identity);
                if (formToken.ClaimUid == null)
                {
                    formToken.Username = identity.Name;
                }
            }

            // populate AdditionalData
            if (_config.AdditionalDataProvider != null)
            {
                formToken.AdditionalData = _config.AdditionalDataProvider.GetAdditionalData(httpContext);
            }

            if (requireAuthenticatedUserHeuristicChecks
                && String.IsNullOrEmpty(formToken.Username)
                && formToken.ClaimUid == null
                && String.IsNullOrEmpty(formToken.AdditionalData))
            {
                // Application says user is authenticated, but we have no identifier for the user.
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                    WebPageResources.TokenValidator_AuthenticatedUserWithoutUsername, identity.GetType()));
            }

            return formToken;
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:46,代码来源:TokenValidator.cs


示例14: ClaimUidProperty

        public void ClaimUidProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.Null(token.ClaimUid);

            // Act & assert - 2
            BinaryBlob blob = new BinaryBlob(32);
            token.ClaimUid = blob;
            Assert.Equal(blob, token.ClaimUid);

            // Act & assert - 3
            token.ClaimUid = null;
            Assert.Null(token.ClaimUid);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:17,代码来源:AntiForgeryTokenTest.cs


示例15: SaveCookieToken

        public void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token)
        {
            string serializedToken = _serializer.Serialize(token);
            HttpCookie newCookie = new HttpCookie(_config.CookieName, serializedToken)
            {
                HttpOnly = true
            };

            // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default
            // value of newCookie.Secure is automatically populated from the <httpCookies>
            // config element.
            if (_config.RequireSSL)
            {
                newCookie.Secure = true;
            }

            httpContext.Response.Cookies.Set(newCookie);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:18,代码来源:AntiForgeryTokenStore.cs


示例16: ValidateTokens

		public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
		{
			if (sessionToken == null)
			{
				throw HttpAntiForgeryException.CreateCookieMissingException(this._config.CookieName);
			}
			if (fieldToken == null)
			{
				throw HttpAntiForgeryException.CreateFormFieldMissingException(this._config.FormFieldName);
			}
			if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
			{
				throw HttpAntiForgeryException.CreateTokensSwappedException(this._config.CookieName, this._config.FormFieldName);
			}
			if (!object.Equals(sessionToken.SecurityToken, fieldToken.SecurityToken))
			{
				throw HttpAntiForgeryException.CreateSecurityTokenMismatchException();
			}
			string text = string.Empty;
			BinaryBlob binaryBlob = null;
			if (identity != null && identity.IsAuthenticated)
			{
				binaryBlob = this._claimUidExtractor.ExtractClaimUid(identity);
				if (binaryBlob == null)
				{
					text = (identity.Name ?? string.Empty);
				}
			}
			bool flag = text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || text.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
			if (!string.Equals(fieldToken.Username, text, flag ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
			{
				throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, text);
			}
			if (!object.Equals(fieldToken.ClaimUid, binaryBlob))
			{
				throw HttpAntiForgeryException.CreateClaimUidMismatchException();
			}
			if (this._config.AdditionalDataProvider != null && !this._config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))
			{
				throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException();
			}
		}
开发者ID:BikS2013,项目名称:bUtility,代码行数:42,代码来源:TokenValidator.cs


示例17: DeserializeImpl

        /* The serialized format of the anti-XSRF token is as follows:
         * Version: 1 byte integer
         * SecurityToken: 16 byte binary blob
         * IsSessionToken: 1 byte Boolean
         * [if IsSessionToken = true]
         *   +- IsClaimsBased: 1 byte Boolean
         *   |  [if IsClaimsBased = true]
         *   |    `- ClaimUid: 32 byte binary blob
         *   |  [if IsClaimsBased = false]
         *   |    `- Username: UTF-8 string with 7-bit integer length prefix
         *   `- AdditionalData: UTF-8 string with 7-bit integer length prefix
         */
        private static AntiForgeryToken DeserializeImpl(BinaryReader reader)
        {
            // we can only consume tokens of the same serialized version that we generate
            byte embeddedVersion = reader.ReadByte();
            if (embeddedVersion != TokenVersion)
            {
                return null;
            }

            AntiForgeryToken deserializedToken = new AntiForgeryToken();
            byte[] securityTokenBytes = reader.ReadBytes(AntiForgeryToken.SecurityTokenBitLength / 8);
            deserializedToken.SecurityToken = new BinaryBlob(AntiForgeryToken.SecurityTokenBitLength, securityTokenBytes);
            deserializedToken.IsSessionToken = reader.ReadBoolean();

            if (!deserializedToken.IsSessionToken)
            {
                bool isClaimsBased = reader.ReadBoolean();
                if (isClaimsBased)
                {
                    byte[] claimUidBytes = reader.ReadBytes(AntiForgeryToken.ClaimUidBitLength / 8);
                    deserializedToken.ClaimUid = new BinaryBlob(AntiForgeryToken.ClaimUidBitLength, claimUidBytes);
                }
                else
                {
                    deserializedToken.Username = reader.ReadString();
                }

                deserializedToken.AdditionalData = reader.ReadString();
            }

            // if there's still unconsumed data in the stream, fail
            if (reader.BaseStream.ReadByte() != -1)
            {
                return null;
            }

            // success
            return deserializedToken;
        }
开发者ID:reza899,项目名称:aspnetwebstack,代码行数:51,代码来源:AntiForgeryTokenSerializer.cs


示例18: SecurityTokenProperty

        public void SecurityTokenProperty()
        {
            // Arrange
            AntiForgeryToken token = new AntiForgeryToken();

            // Act & assert - 1
            BinaryBlob securityToken = token.SecurityToken;
            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call

            // Act & assert - 2
            securityToken = new BinaryBlob(64);
            token.SecurityToken = securityToken;
            Assert.Equal(securityToken, token.SecurityToken);

            // Act & assert - 3
            token.SecurityToken = null;
            securityToken = token.SecurityToken;
            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:23,代码来源:AntiForgeryTokenTest.cs


示例19: ValidateTokens_Success_ClaimsBasedUser

        public void ValidateTokens_Success_ClaimsBasedUser()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>().Object;
            var identity = GetAuthenticatedIdentity("the-user");
            var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            var fieldtoken = new AntiForgeryToken()
            {
                SecurityToken = sessionToken.SecurityToken,
                IsSessionToken = false,
                ClaimUid = new BinaryBlob(256)
            };

            var mockClaimUidExtractor = new Mock<IClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
                                 .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData()));

            var config = new AntiForgeryOptions();

            var tokenProvider = new AntiForgeryTokenProvider(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            // Act
            tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);

            // Assert
            // Nothing to assert - if we got this far, success!
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:30,代码来源:TokenProviderTest.cs


示例20: ValidateTokens_AdditionalDataRejected

        public void ValidateTokens_AdditionalDataRejected()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>().Object;
            var identity = new ClaimsIdentity();
            var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            var fieldtoken = new AntiForgeryToken()
            {
                SecurityToken = sessionToken.SecurityToken,
                Username = String.Empty,
                IsSessionToken = false,
                AdditionalData = "some-additional-data"
            };

            var mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
                                      .Returns(false);

            var config = new AntiForgeryOptions();
            var tokenProvider = new AntiForgeryTokenProvider(
                config: config,
                claimUidExtractor: null,
                additionalDataProvider: mockAdditionalDataProvider.Object);

            // Act & assert
            var ex =
                Assert.Throws<InvalidOperationException>(
                    () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));
            Assert.Equal(@"The provided anti-forgery token failed a custom data check.", ex.Message);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:30,代码来源:TokenProviderTest.cs



注:本文中的AntiForgeryToken类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Runtime.IToken类代码示例发布时间:2022-05-24
下一篇:
C# Answer类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap