本文整理汇总了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!
}
示例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);
}
示例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();
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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();
}
}
示例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);
}
示例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);
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}