当前位置: 首页>>代码示例>>C#>>正文


C# AntiForgeryToken类代码示例

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


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


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