public static string Serialize(AntiForgeryToken token) { //Contract.Assert(token != null); using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(TokenVersion); writer.Write(token.SecurityToken.GetData()); writer.Write(token.IsSessionToken); if (!token.IsSessionToken) { writer.Write(token.Username); writer.Write(token.AdditionalData); } writer.Flush(); // This function encrypts the token to local machine and adds URL encoding // to the string. Since this encryption can only be decrypted by the same // machine, successful decryption of a received token validates that the // token was generated by the source machine. return(CryptoSystem.Protect(stream.ToArray())); } }
public static AntiForgeryToken Deserialize(string serializedToken) { try { using (MemoryStream stream = new MemoryStream(CryptoSystem.Unprotect(serializedToken))) using (BinaryReader reader = new BinaryReader(stream)) { AntiForgeryToken token = Deserialize(reader); if (token != null) { return(token); } } } catch { // swallow all exceptions - homogenize error if something went wrong } // if we reached this point, something went wrong deserializing throw new HttpAntiForgeryException("Deserialization failed or the anti-forgery token could not be decrypted."); }