public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) { SecurityKeyIdentifierClause clause = null; reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, this.NamespaceUri); while (reader.IsStartElement()) { if ((clause == null) && reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, this.NamespaceUri)) { X509Certificate2 certificate = null; if (!System.ServiceModel.Security.SecurityUtils.TryCreateX509CertificateFromRawData(reader.ReadElementContentAsBase64(), out certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("InvalidX509RawData"))); } clause = new X509RawDataKeyIdentifierClause(certificate); } else if ((clause == null) && reader.IsStartElement("X509SKI", this.NamespaceUri.ToString())) { clause = new X509SubjectKeyIdentifierClause(reader.ReadElementContentAsBase64()); } else { reader.Skip(); } } reader.ReadEndElement(); return(clause); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { string secretType = reader.GetAttribute(XD.SecurityJan2004Dictionary.TypeAttribute, null); string id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); bool isNonce = false; if (secretType != null && secretType.Length > 0) { if (secretType == _parent.SerializerDictionary.NonceBinarySecret.Value || secretType == _otherDictionary.NonceBinarySecret.Value) { isNonce = true; } else if (secretType != _parent.SerializerDictionary.SymmetricKeyBinarySecret.Value && secretType != _otherDictionary.SymmetricKeyBinarySecret.Value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(string.Format(SRServiceModel.UnexpectedBinarySecretType, _parent.SerializerDictionary.SymmetricKeyBinarySecret.Value, secretType))); } } byte[] secret = reader.ReadElementContentAsBase64(); if (isNonce) { return(new NonceToken(id, secret)); } else { return(new BinarySecretSecurityToken(id, secret)); } }
public static void Main() { // Typically this request would be constructed by a web browser or non-WCF application instead of using WCF Console.WriteLine("Starting client with ByteStreamHttpBinding"); using (ChannelFactory <IHttpHandler> cf = new ChannelFactory <IHttpHandler>("byteStreamHttpBinding")) { IHttpHandler channel = cf.CreateChannel(); Console.WriteLine("Client channel created"); Message byteStream = Message.CreateMessage(MessageVersion.None, "*", new ByteStreamBodyWriter(TestFileName)); HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add("Content-Type", "application/octet-stream"); byteStream.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty); Console.WriteLine("Client calling service"); Message reply = channel.ProcessRequest(byteStream); //Get bytes from the reply XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.MoveToElement(); String name = reader.Name; Console.WriteLine("First element in the byteStream message is : <" + name + ">"); byte[] array = reader.ReadElementContentAsBase64(); String replyMessage = System.Text.Encoding.UTF8.GetString(array); Console.WriteLine("Client received a reply from service of length :" + replyMessage.Length); } Console.WriteLine("Done"); Console.WriteLine("Press <ENTER> to exit client"); Console.ReadLine(); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { UniqueId generation = null; bool isCookieMode = false; Fx.Assert(reader.NodeType == XmlNodeType.Element, ""); // check if there is an id string id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); SecurityContextSecurityToken sct = null; // There needs to be at least a contextId in here. reader.ReadFullStartElement(); reader.MoveToStartElement(Parent.SerializerDictionary.Identifier, Parent.SerializerDictionary.Namespace); UniqueId contextId = reader.ReadElementContentAsUniqueId(); if (CanReadGeneration(reader)) { generation = ReadGeneration(reader); } if (reader.IsStartElement(Parent.SerializerDictionary.Cookie, XD.DotNetSecurityDictionary.Namespace)) { isCookieMode = true; sct = TryResolveSecurityContextToken(contextId, generation, id, tokenResolver, out ISecurityContextSecurityTokenCache sctCache); if (sct == null) { byte[] encodedCookie = reader.ReadElementContentAsBase64(); if (encodedCookie != null) { sct = _cookieSerializer.CreateSecurityContextFromCookie(encodedCookie, contextId, generation, id, reader.Quotas); if (sctCache != null) { sctCache.AddContext(sct); } } } else { reader.Skip(); } } reader.ReadEndElement(); if (contextId == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.NoSecurityContextIdentifier))); } if (sct == null && !isCookieMode) { sct = TryResolveSecurityContextToken(contextId, generation, id, tokenResolver, out ISecurityContextSecurityTokenCache sctCache); } if (sct == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new Exception(SR.Format(SR.SecurityContextNotRegistered, contextId, generation))); } return(sct); }
/// <summary> /// Reads the XML stream or document with an <see cref="T:System.Xml.XmlDictionaryReader" /> and returns the deserialized object; it also enables you to specify whether the serializer can read the data before attempting to read it. /// </summary> /// <param name="reader">An <see cref="T:System.Xml.XmlDictionaryReader" /> used to read the XML document.</param> /// <param name="verifyObjectName">true to check whether the enclosing XML element name and namespace correspond to the root name and root namespace; otherwise, false to skip the verification.</param> /// <returns> /// The deserialized object. /// </returns> public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { Argument.IsNotNull("reader", reader); var memoryStream = new MemoryStream(reader.ReadElementContentAsBase64()); return(BinarySerializerHelper.DiscoverAndDeSerialize(memoryStream, _type)); }
/// <summary> /// Parses the "X509Certificate" element and generates a corresponding <see cref="X509RawDataKeyIdentifierClause"/> instance. /// </summary> /// <param name="dictionaryReader">The <see cref="XmlDictionaryReader"/> currently positioning on the "X509Certificate" element. </param> /// <returns>An instance of <see cref="X509RawDataKeyIdentifierClause"/> created from the "X509Certificate" element.</returns> private static SecurityKeyIdentifierClause CreateRawDataKeyIdentifierClause(XmlDictionaryReader dictionaryReader) { #if INCLUDE_CERT_CHAIN List <byte[]> rawDatas = new List <byte[]>(); while (dictionaryReader.IsStartElement(XmlSignatureConstants.Elements.X509Certificate, XmlSignatureConstants.Namespace)) { byte[] rawBuffer = dictionaryReader.ReadElementContentAsBase64(); if (rawBuffer == null || rawBuffer.Length == 0) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4258, XmlSignatureConstants.Elements.X509Certificate, XmlSignatureConstants.Namespace)); } rawDatas.Add(rawBuffer); } if (rawDatas.Count > 1) { return(new X509ChainRawDataKeyIdentifierClause(rawDatas)); } else { return(new X509RawDataKeyIdentifierClause(rawDatas[0])); } #else byte[] rawData = null; while (dictionaryReader.IsStartElement(XmlSignatureConstants.Elements.X509Certificate, XmlSignatureConstants.Namespace)) { if (rawData == null) { rawData = dictionaryReader.ReadElementContentAsBase64(); if ((rawData == null) || (rawData.Length == 0)) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4258, XmlSignatureConstants.Elements.X509Certificate, XmlSignatureConstants.Namespace)); } } else { // We do not support reading intermediary certs. dictionaryReader.Skip(); } } return(new X509RawDataKeyIdentifierClause(rawData)); #endif }
/// <summary> /// Reads the X.509 Security token referenced by the XmlReader. /// </summary> /// <param name="reader">XmlReader pointing to a X.509 Security token.</param> /// <returns>An instance of <see cref="X509SecurityToken"/>.</returns> /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception> /// <exception cref="XmlException">XmlReader is not pointing to an valid X509SecurityToken as /// defined in WS-Security X.509 Token Profile. Or the encodingType specified is other than Base64 /// or HexBinary.</exception> public override SecurityToken ReadToken(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } XmlDictionaryReader dicReader = XmlDictionaryReader.CreateDictionaryReader(reader); if (!dicReader.IsStartElement(WSSecurity10Constants.Elements.BinarySecurityToken, WSSecurity10Constants.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new XmlException( SR.GetString( SR.ID4065, WSSecurity10Constants.Elements.BinarySecurityToken, WSSecurity10Constants.Namespace, dicReader.LocalName, dicReader.NamespaceURI))); } string valueTypeUri = dicReader.GetAttribute(WSSecurity10Constants.Attributes.ValueType, null); if (!StringComparer.Ordinal.Equals(valueTypeUri, WSSecurity10Constants.X509TokenType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new XmlException( SR.GetString( SR.ID4066, WSSecurity10Constants.Elements.BinarySecurityToken, WSSecurity10Constants.Namespace, WSSecurity10Constants.Attributes.ValueType, WSSecurity10Constants.X509TokenType, valueTypeUri))); } string wsuId = dicReader.GetAttribute(WSSecurityUtilityConstants.Attributes.Id, WSSecurityUtilityConstants.Namespace); string encoding = dicReader.GetAttribute(WSSecurity10Constants.Attributes.EncodingType, null); byte[] binaryData; if (encoding == null || StringComparer.Ordinal.Equals(encoding, WSSecurity10Constants.Base64EncodingType)) { binaryData = dicReader.ReadElementContentAsBase64(); } else if (StringComparer.Ordinal.Equals(encoding, WSSecurity10Constants.HexBinaryEncodingType)) { binaryData = SoapHexBinary.Parse(dicReader.ReadElementContentAsString()).Value; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4068))); } return(String.IsNullOrEmpty(wsuId) ? new X509SecurityToken(new X509Certificate2(binaryData)) : new X509SecurityToken(new X509Certificate2(binaryData), wsuId)); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { UniqueId generation = (UniqueId)null; string attribute = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); reader.ReadFullStartElement(); reader.MoveToStartElement(this.parent.SerializerDictionary.Identifier, this.parent.SerializerDictionary.Namespace); UniqueId contextId = reader.ReadElementContentAsUniqueId(); if (this.CanReadGeneration(reader)) { generation = this.ReadGeneration(reader); } #if FEATURE_CORECLR throw new NotImplementedException("DotNetSecurityDictionary not implemented in .NET Core"); #else bool flag = false; SecurityContextSecurityToken token = (SecurityContextSecurityToken)null; if (reader.IsStartElement(this.parent.SerializerDictionary.Cookie, DotNetSecurityDictionary.Namespace)) { flag = true; ISecurityContextSecurityTokenCache sctCache; token = this.TryResolveSecurityContextToken(contextId, generation, attribute, tokenResolver, out sctCache); if (token == null) { byte[] encodedCookie = reader.ReadElementContentAsBase64(); if (encodedCookie != null) { token = this.cookieSerializer.CreateSecurityContextFromCookie(encodedCookie, contextId, generation, attribute, reader.Quotas); if (sctCache != null) { sctCache.AddContext(token); } } } else { reader.Skip(); } } reader.ReadEndElement(); if (contextId == (UniqueId)null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError((Exception) new MessageSecurityException(SR.GetString("NoSecurityContextIdentifier"))); } if (token == null && !flag) { ISecurityContextSecurityTokenCache sctCache; token = this.TryResolveSecurityContextToken(contextId, generation, attribute, tokenResolver, out sctCache); } if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning((Exception) new SecurityContextTokenValidationException(SR.GetString("SecurityContextNotRegistered", (object)contextId, (object)generation))); } return((SecurityToken)token); #endif }
/// <summary> /// Parses the "X509SKI" element and generates a corresponding <see cref="SecurityKeyIdentifierClause"/> instance. /// </summary> /// <param name="dictionaryReader">The <see cref="XmlDictionaryReader"/> currently positioning on the "X509SKI" element. </param> /// <returns>An instance of <see cref="X509SubjectKeyIdentifierClause"/> created from the "X509SKI" element.</returns> private static SecurityKeyIdentifierClause CreateSubjectKeyIdentifierClause(XmlDictionaryReader dictionaryReader) { byte[] ski = dictionaryReader.ReadElementContentAsBase64(); if ((ski == null) || (ski.Length == 0)) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4258, XmlSignatureConstants.Elements.X509SKI, XmlSignatureConstants.Namespace)); } return(new X509SubjectKeyIdentifierClause(ski)); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { UniqueId contextId = null; byte[] encodedCookie = null; UniqueId generation = null; bool flag = false; string attribute = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); SecurityContextSecurityToken token = null; reader.ReadFullStartElement(); reader.MoveToStartElement(this.parent.SerializerDictionary.Identifier, this.parent.SerializerDictionary.Namespace); contextId = reader.ReadElementContentAsUniqueId(); if (this.CanReadGeneration(reader)) { generation = this.ReadGeneration(reader); } if (reader.IsStartElement(this.parent.SerializerDictionary.Cookie, XD.DotNetSecurityDictionary.Namespace)) { ISecurityContextSecurityTokenCache cache; flag = true; token = this.TryResolveSecurityContextToken(contextId, generation, attribute, tokenResolver, out cache); if (token == null) { encodedCookie = reader.ReadElementContentAsBase64(); if (encodedCookie != null) { token = this.cookieSerializer.CreateSecurityContextFromCookie(encodedCookie, contextId, generation, attribute, reader.Quotas); if (cache != null) { cache.AddContext(token); } } } else { reader.Skip(); } } reader.ReadEndElement(); if (contextId == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("NoSecurityContextIdentifier"))); } if ((token == null) && !flag) { ISecurityContextSecurityTokenCache cache2; token = this.TryResolveSecurityContextToken(contextId, generation, attribute, tokenResolver, out cache2); } if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(System.ServiceModel.SR.GetString("SecurityContextNotRegistered", new object[] { contextId, generation }))); } return(token); }
public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) { SecurityKeyIdentifierClause ski = null; reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, NamespaceUri); while (reader.IsStartElement()) { if (ski == null && reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, NamespaceUri)) { X509Certificate2 certificate = null; if (!SecurityUtils.TryCreateX509CertificateFromRawData(reader.ReadElementContentAsBase64(), out certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityMessageSerializationException(SR.GetString(SR.InvalidX509RawData))); } ski = new X509RawDataKeyIdentifierClause(certificate); } else if (ski == null && reader.IsStartElement(XmlSignatureStrings.X509Ski, NamespaceUri.ToString())) { ski = new X509SubjectKeyIdentifierClause(reader.ReadElementContentAsBase64()); } else if ((ski == null) && reader.IsStartElement(XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace)) { reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerSerial, XD.XmlSignatureDictionary.Namespace); reader.ReadStartElement(XD.XmlSignatureDictionary.X509IssuerName, XD.XmlSignatureDictionary.Namespace); string issuerName = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadStartElement(XD.XmlSignatureDictionary.X509SerialNumber, XD.XmlSignatureDictionary.Namespace); string serialNumber = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadEndElement(); ski = new X509IssuerSerialKeyIdentifierClause(issuerName, serialNumber); } else { reader.Skip(); } } reader.ReadEndElement(); return(ski); }
public static void Deserialize(XmlDictionaryReader reader, out IList <DirectoryControl> controls, bool mustBePresent, bool fullChecks) { string str = null; string str1 = null; bool flag; byte[] numArray = null; controls = new List <DirectoryControl>(); if (mustBePresent || reader.IsStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory")) { reader.ReadFullStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory"); while (reader.IsStartElement("control", "http://schemas.microsoft.com/2008/1/ActiveDirectory")) { string attribute = reader.GetAttribute("type"); string attribute1 = reader.GetAttribute("criticality"); reader.Read(); if (!reader.IsStartElement("controlValue", "http://schemas.microsoft.com/2008/1/ActiveDirectory")) { numArray = null; } else { string attribute2 = reader.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance"); if (attribute2 != null) { XmlUtility.SplitPrefix(attribute2, out str, out str1); numArray = reader.ReadElementContentAsBase64(); } else { throw new ArgumentException(); } } if (!string.Equals("true", attribute1)) { flag = false; } else { flag = true; } DirectoryControl directoryControl = new DirectoryControl(attribute, numArray, flag, true); controls.Add(directoryControl); reader.Read(); } return; } else { return; } }
public object DeserializeReply(Message message, object[] parameters) { if (this.operationDescription.Messages.Count == 1) { return(null); } if (parameters.Length == 0 && this.operationDescription.Messages[1].Body.ReturnValue.Type == typeof(void)) { return(null); } XmlDictionaryReader reader = message.GetReaderAtBodyContents(); byte[] buffer = reader.ReadElementContentAsBase64(); MemoryStream jsonStream = new MemoryStream(buffer); WebMessageBodyStyle bodyStyle = GetBodyStyle(this.operationDescription); if (bodyStyle == WebMessageBodyStyle.Bare || bodyStyle == WebMessageBodyStyle.WrappedRequest) { DataContractJsonSerializer dcjs = new DataContractJsonSerializer(this.operationDescription.Messages[1].Body.ReturnValue.Type); return(dcjs.ReadObject(jsonStream)); } else { JsonObject jo = JsonValue.Load(jsonStream) as JsonObject; if (jo == null) { throw new InvalidOperationException("Response is not a JSON object"); } for (int i = 0; i < this.operationDescription.Messages[1].Body.Parts.Count; i++) { MessagePartDescription outPart = this.operationDescription.Messages[1].Body.Parts[i]; if (jo.ContainsKey(outPart.Name)) { parameters[i] = Deserialize(outPart.Type, jo[outPart.Name]); } } MessagePartDescription returnPart = this.operationDescription.Messages[1].Body.ReturnValue; if (returnPart != null && jo.ContainsKey(returnPart.Name)) { return(Deserialize(returnPart.Type, jo[returnPart.Name])); } else { return(null); } } }
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { if (this.isCustomSerialization) { object result = Activator.CreateInstance(this.type); MemoryStream ms = new MemoryStream(reader.ReadElementContentAsBase64()); ((ICustomSerializable)result).InitializeFrom(ms); return(result); } else { return(this.fallbackSerializer.ReadObject(reader, verifyObjectName)); } }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { HttpRequestMessageProperty reqProp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; if (reqProp.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded") { string operation = request.Headers.To.AbsolutePath; int lastSlash = operation.LastIndexOf('/'); if (lastSlash >= 0) { operation = operation.Substring(lastSlash + 1); } OperationDescription operationDescription = this.endpoint.Contract.Operations.Find(operation); if (operationDescription != null && operationDescription.Behaviors.Find <CanReceiveFormsUrlEncodedInputAttribute>() != null) { // Decode the forms-urlencoded input XmlDictionaryReader bodyReader = request.GetReaderAtBodyContents(); byte[] input = bodyReader.ReadElementContentAsBase64(); string inputStr = Encoding.UTF8.GetString(input); NameValueCollection parameters = HttpUtility.ParseQueryString(inputStr); // Create an equivalent JSON StringBuilder json = new StringBuilder(); json.Append('{'); this.ConvertNVCToJson(operationDescription, parameters, json); json.Append('}'); // Recreate the message with the JSON input byte[] jsonBytes = Encoding.UTF8.GetBytes(json.ToString()); XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max); Message newMessage = Message.CreateMessage(request.Version, null, jsonReader); newMessage.Headers.CopyHeadersFrom(request); newMessage.Properties.CopyProperties(request.Properties); // Notify the application this this change happened OperationContext.Current.IncomingMessageProperties.Add(FormUrlEncodedEnabledJsonEndpointFactory.FormUrlEncodedInputProperty, true); newMessage.Properties.Add(FormUrlEncodedEnabledJsonEndpointFactory.FormUrlEncodedInputProperty, true); // Change the 'raw' input to 'json' newMessage.Properties.Remove(WebBodyFormatMessageProperty.Name); newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json)); request = newMessage; } } return(null); }
internal virtual byte[] ReadElementContentAsBase64() { if (_isEndOfEmptyElement) { ThrowNotAtElement(); } if (_dictionaryReader == null) { return(ReadContentAsBase64(_reader.ReadElementContentAsString())); } else { return(_dictionaryReader.ReadElementContentAsBase64()); } }
protected override SecurityToken ReadTokenCore(XmlReader reader, SecurityTokenResolver tokenResolver) { if (!SimpleWebSecurityTokenSerializer.IsSimpleWebSecurityToken(reader)) { return(this.innerSerializer.ReadToken(reader, tokenResolver)); } XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); string attribute = xmlDictionaryReader.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); string str = xmlDictionaryReader.GetAttribute("EncodingType", null); if (str != null && !(str == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary")) { throw new NotSupportedException(SRClient.UnsupportedEncodingType); } return(SimpleWebSecurityTokenSerializer.ReadBinaryCore(attribute, xmlDictionaryReader.ReadElementContentAsBase64())); }
internal string GetJsonTokenString(System.Xml.XmlReader reader, out string wsuId) { reader.MoveToContent(); string @string; using (XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader)) { wsuId = xmlDictionaryReader.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); string attribute = xmlDictionaryReader.GetAttribute("EncodingType", null); if (attribute != null && !(attribute == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary")) { throw new System.Xml.XmlException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Unsupported encoding type: {0}", new object[] { attribute })); } byte[] bytes = xmlDictionaryReader.ReadElementContentAsBase64(); @string = Base64UrlEncoder.TextEncoding.GetString(bytes); } return(@string); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { string wsuId = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); string valueTypeUri = reader.GetAttribute(s_valueTypeAttribute, null); string encoding = reader.GetAttribute(s_encodingTypeAttribute, null); byte[] binaryData; if (encoding == null || encoding == EncodingTypeValueBase64Binary) { binaryData = reader.ReadElementContentAsBase64(); } else if (encoding == EncodingTypeValueHexBinary) { binaryData = HexBinary.Parse(reader.ReadElementContentAsString()).Value; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.UnknownEncodingInBinarySecurityToken)); } return(ReadBinaryCore(wsuId, valueTypeUri, binaryData)); }
private static bool ReadTest(MemoryStream ms, Encoding encoding, ReaderWriterFactory.ReaderWriterType rwType, byte[] byteArray) { ms.Position = 0; XmlDictionaryReader reader = (XmlDictionaryReader)ReaderWriterFactory.CreateXmlReader(rwType, ms, encoding); reader.ReadToDescendant("Root"); byte[] bytesFromReader = reader.ReadElementContentAsBase64(); if (bytesFromReader.Length != byteArray.Length) { return false; } else { for (int i = 0; i < byteArray.Length; i++) { if (byteArray[i] != bytesFromReader[i]) { return false; } } } return true; }
public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { bool useRawEncoder = false; if (message.Properties.ContainsKey(WebBodyFormatMessageProperty.Name)) { WebBodyFormatMessageProperty prop = (WebBodyFormatMessageProperty)message.Properties[WebBodyFormatMessageProperty.Name]; useRawEncoder = prop.Format == WebContentFormat.Json || prop.Format == WebContentFormat.Raw; } if (useRawEncoder) { MemoryStream ms = new MemoryStream(); XmlDictionaryReader reader = message.GetReaderAtBodyContents(); byte[] buffer = reader.ReadElementContentAsBase64(); byte[] managedBuffer = bufferManager.TakeBuffer(buffer.Length + messageOffset); Array.Copy(buffer, 0, managedBuffer, messageOffset, buffer.Length); return(new ArraySegment <byte>(managedBuffer, messageOffset, buffer.Length)); } else { return(this.xmlEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset)); } }
/// <summary cref="IClientMessageInspector.AfterReceiveReply" /> public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { // check for fault. if (reply.IsFault) { return; } // parse request parameters. object[] parameters = correlationState as object[]; if (parameters == null || parameters.Length != 3) { throw new InvalidOperationException("Cannot decode request because the IClientMessageInspector not configured properly."); } // extract request parameters. MessageVersion messageVersion = parameters[0] as MessageVersion; string action = parameters[1] as string; IServiceMessage request = parameters[2] as IServiceMessage; object encodeable = null; if (!reply.Properties.TryGetValue(MessageProperties.UnencodedBody, out encodeable)) { // extract binary encoded response from body. XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.MoveToStartElement("InvokeServiceResponse", Namespaces.OpcUaXsd); byte[] response = reader.ReadElementContentAsBase64(); // decode body. try { encodeable = BinaryDecoder.DecodeMessage(response, null, m_messageContext); } catch (Exception e) { ServiceResult error = ServiceResult.Create( e, StatusCodes.BadDecodingError, "Could not decoding incoming response message."); ServiceFault fault = new ServiceFault(); fault.ResponseHeader.RequestHandle = request.GetRequest().RequestHeader.RequestHandle; fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.ServiceResult = error.Code; StringTable stringTable = new StringTable(); fault.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( error, DiagnosticsMasks.NoInnerStatus, true, stringTable); fault.ResponseHeader.StringTable = stringTable.ToArray(); encodeable = fault; } } object unencodedBody = request.CreateResponse((IServiceResponse)encodeable); // create the unencoded reply message. Message unencodedReply = Message.CreateMessage( messageVersion, action + "Response", unencodedBody); unencodedReply.Headers.MessageId = reply.Headers.MessageId; unencodedReply.Headers.RelatesTo = reply.Headers.RelatesTo; unencodedReply.Properties.Add(MessageProperties.UnencodedBody, unencodedBody); // replace the incoming message. reply = unencodedReply; }
private SecurityContextSecurityToken DeserializeContext(byte[] serializedContext, byte[] cookieBlob, string id, XmlDictionaryReaderQuotas quotas) { List <IAuthorizationPolicy> list3; SctClaimDictionary instance = SctClaimDictionary.Instance; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(serializedContext, 0, serializedContext.Length, instance, quotas, null, null); int num = -1; UniqueId contextId = null; DateTime minUtcDateTime = System.ServiceModel.Security.SecurityUtils.MinUtcDateTime; DateTime maxUtcDateTime = System.ServiceModel.Security.SecurityUtils.MaxUtcDateTime; byte[] key = null; string str = null; UniqueId keyGeneration = null; DateTime keyEffectiveTime = System.ServiceModel.Security.SecurityUtils.MinUtcDateTime; DateTime keyExpirationTime = System.ServiceModel.Security.SecurityUtils.MaxUtcDateTime; List <ClaimSet> claimSets = null; IList <IIdentity> identities = null; bool isCookieMode = true; reader.ReadFullStartElement(instance.SecurityContextSecurityToken, instance.EmptyString); while (reader.IsStartElement()) { if (reader.IsStartElement(instance.Version, instance.EmptyString)) { num = reader.ReadElementContentAsInt(); } else { if (reader.IsStartElement(instance.ContextId, instance.EmptyString)) { contextId = reader.ReadElementContentAsUniqueId(); continue; } if (reader.IsStartElement(instance.Id, instance.EmptyString)) { str = reader.ReadElementContentAsString(); continue; } if (reader.IsStartElement(instance.EffectiveTime, instance.EmptyString)) { minUtcDateTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); continue; } if (reader.IsStartElement(instance.ExpiryTime, instance.EmptyString)) { maxUtcDateTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); continue; } if (reader.IsStartElement(instance.Key, instance.EmptyString)) { key = reader.ReadElementContentAsBase64(); continue; } if (reader.IsStartElement(instance.KeyGeneration, instance.EmptyString)) { keyGeneration = reader.ReadElementContentAsUniqueId(); continue; } if (reader.IsStartElement(instance.KeyEffectiveTime, instance.EmptyString)) { keyEffectiveTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); continue; } if (reader.IsStartElement(instance.KeyExpiryTime, instance.EmptyString)) { keyExpirationTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); continue; } if (reader.IsStartElement(instance.Identities, instance.EmptyString)) { identities = SctClaimSerializer.DeserializeIdentities(reader, instance, DataContractSerializerDefaults.CreateSerializer(typeof(IIdentity), this.knownTypes, 0x7fffffff)); continue; } if (reader.IsStartElement(instance.ClaimSets, instance.EmptyString)) { reader.ReadStartElement(); DataContractSerializer serializer = DataContractSerializerDefaults.CreateSerializer(typeof(ClaimSet), this.knownTypes, 0x7fffffff); DataContractSerializer claimSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(Claim), this.knownTypes, 0x7fffffff); claimSets = new List <ClaimSet>(1); while (reader.IsStartElement()) { claimSets.Add(SctClaimSerializer.DeserializeClaimSet(reader, instance, serializer, claimSerializer)); } reader.ReadEndElement(); continue; } if (reader.IsStartElement(instance.IsCookieMode, instance.EmptyString)) { isCookieMode = reader.ReadElementString() == "1"; } else { OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieXmlParseError")); } } } reader.ReadEndElement(); if (num != 1) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.ServiceModel.SR.GetString("SerializedTokenVersionUnsupported", new object[] { num }))); } if (contextId == null) { OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieValueMissingOrIncorrect", new object[] { "ContextId" })); } if ((key == null) || (key.Length == 0)) { OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieValueMissingOrIncorrect", new object[] { "Key" })); } if (str != id) { OnInvalidCookieFailure(System.ServiceModel.SR.GetString("SctCookieValueMissingOrIncorrect", new object[] { "Id" })); } if (claimSets != null) { list3 = new List <IAuthorizationPolicy>(1) { new SctUnconditionalPolicy(identities, claimSets, maxUtcDateTime) }; } else { list3 = null; } return(new SecurityContextSecurityToken(contextId, str, key, minUtcDateTime, maxUtcDateTime, (list3 != null) ? list3.AsReadOnly() : null, isCookieMode, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime)); }
public static SecurityContextSecurityToken ResolveCookie(byte [] bytes, byte [] cookie) { string id = null; UniqueId context = null; DateTime validFrom = DateTime.MinValue, validTo = DateTime.MaxValue, keyEffective = DateTime.MinValue, keyExpired = DateTime.MaxValue; byte [] key = null; X509Certificate2 cert = null; X500DistinguishedName issuer = null; XmlDictionary dic = new XmlDictionary(); for (int i = 0; i < 30; i++) { dic.Add("n" + i); } // FIXME: create proper quotas XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); XmlDictionaryReader cr = XmlDictionaryReader.CreateBinaryReader(bytes, 0, bytes.Length, dic, quotas); cr.MoveToContent(); // -> n1 cr.ReadStartElement("n0", String.Empty); do { cr.MoveToContent(); if (cr.NodeType == XmlNodeType.EndElement) { break; } if (cr.NodeType != XmlNodeType.Element) { throw new Exception("Unxpected non-element content:" + cr.NodeType); } switch (cr.Name) { case "n1": // FIXME: some integer here int n1 = cr.ReadElementContentAsInt(); if (n1 != 1) { throw new Exception("INTERNAL ERROR: there was unexpected n2 content: " + n1); } break; case "n2": context = cr.ReadElementContentAsUniqueId(); break; case "n3": id = cr.ReadElementContentAsString(); break; case "n4": key = cr.ReadElementContentAsBase64(); break; case "n7": validFrom = new DateTime(cr.ReadElementContentAsLong()); break; case "n8": validTo = new DateTime(cr.ReadElementContentAsLong()); break; case "n10": keyEffective = new DateTime(cr.ReadElementContentAsLong()); break; case "n11": keyExpired = new DateTime(cr.ReadElementContentAsLong()); break; case "n13": // <n18>X509Certificate</n18> cr.Read(); cr.MoveToContent(); cert = new X509Certificate2(cr.ReadElementContentAsBase64()); cr.ReadEndElement(); break; case "n15": // <n16><n24 n25="IssuerName" /></n16> cr.Read(); cr.ReadStartElement("n16", String.Empty); issuer = new X500DistinguishedName(cr.GetAttribute("n25")); bool empty = cr.IsEmptyElement; cr.ReadStartElement("n24", String.Empty); if (!empty) { cr.ReadEndElement(); // n24 } cr.ReadEndElement(); // n16 cr.ReadEndElement(); // n15 break; default: throw new Exception("INTERNAL ERROR: there was an unhandled element: " + cr.Name); } }while (true); SecurityContextSecurityToken sct = new SecurityContextSecurityToken( context, id, key, validFrom, validTo, null, keyEffective, keyExpired, null); sct.Cookie = cookie; return(sct); }
SecurityContextSecurityToken DeserializeContext(byte[] serializedContext, byte[] cookieBlob, string id, XmlDictionaryReaderQuotas quotas) { SctClaimDictionary dictionary = SctClaimDictionary.Instance; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(serializedContext, 0, serializedContext.Length, dictionary, quotas, null, null); int cookieVersion = -1; UniqueId cookieContextId = null; DateTime effectiveTime = SecurityUtils.MinUtcDateTime; DateTime expiryTime = SecurityUtils.MaxUtcDateTime; byte[] key = null; string localId = null; UniqueId keyGeneration = null; DateTime keyEffectiveTime = SecurityUtils.MinUtcDateTime; DateTime keyExpirationTime = SecurityUtils.MaxUtcDateTime; List <ClaimSet> claimSets = null; IList <IIdentity> identities = null; bool isCookie = true; reader.ReadFullStartElement(dictionary.SecurityContextSecurityToken, dictionary.EmptyString); while (reader.IsStartElement()) { if (reader.IsStartElement(dictionary.Version, dictionary.EmptyString)) { cookieVersion = reader.ReadElementContentAsInt(); } else if (reader.IsStartElement(dictionary.ContextId, dictionary.EmptyString)) { cookieContextId = reader.ReadElementContentAsUniqueId(); } else if (reader.IsStartElement(dictionary.Id, dictionary.EmptyString)) { localId = reader.ReadElementContentAsString(); } else if (reader.IsStartElement(dictionary.EffectiveTime, dictionary.EmptyString)) { effectiveTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); } else if (reader.IsStartElement(dictionary.ExpiryTime, dictionary.EmptyString)) { expiryTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); } else if (reader.IsStartElement(dictionary.Key, dictionary.EmptyString)) { key = reader.ReadElementContentAsBase64(); } else if (reader.IsStartElement(dictionary.KeyGeneration, dictionary.EmptyString)) { keyGeneration = reader.ReadElementContentAsUniqueId(); } else if (reader.IsStartElement(dictionary.KeyEffectiveTime, dictionary.EmptyString)) { keyEffectiveTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); } else if (reader.IsStartElement(dictionary.KeyExpiryTime, dictionary.EmptyString)) { keyExpirationTime = new DateTime(XmlHelper.ReadElementContentAsInt64(reader), DateTimeKind.Utc); } else if (reader.IsStartElement(dictionary.Identities, dictionary.EmptyString)) { identities = SctClaimSerializer.DeserializeIdentities(reader, dictionary, DataContractSerializerDefaults.CreateSerializer(typeof(IIdentity), this.knownTypes, int.MaxValue)); } else if (reader.IsStartElement(dictionary.ClaimSets, dictionary.EmptyString)) { reader.ReadStartElement(); DataContractSerializer claimSetSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(ClaimSet), this.knownTypes, int.MaxValue); DataContractSerializer claimSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(Claim), this.knownTypes, int.MaxValue); claimSets = new List <ClaimSet>(1); while (reader.IsStartElement()) { claimSets.Add(SctClaimSerializer.DeserializeClaimSet(reader, dictionary, claimSetSerializer, claimSerializer)); } reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.IsCookieMode, dictionary.EmptyString)) { isCookie = reader.ReadElementString() == "1" ? true : false; } else { OnInvalidCookieFailure(SR.GetString(SR.SctCookieXmlParseError)); } } reader.ReadEndElement(); if (cookieVersion != SupportedPersistanceVersion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SerializedTokenVersionUnsupported, cookieVersion))); } if (cookieContextId == null) { OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "ContextId")); } if (key == null || key.Length == 0) { OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "Key")); } if (localId != id) { OnInvalidCookieFailure(SR.GetString(SR.SctCookieValueMissingOrIncorrect, "Id")); } List <IAuthorizationPolicy> authorizationPolicies; if (claimSets != null) { authorizationPolicies = new List <IAuthorizationPolicy>(1); authorizationPolicies.Add(new SctUnconditionalPolicy(identities, claimSets, expiryTime)); } else { authorizationPolicies = null; } return(new SecurityContextSecurityToken(cookieContextId, localId, key, effectiveTime, expiryTime, authorizationPolicies != null ? authorizationPolicies.AsReadOnly() : null, isCookie, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime)); }
public override SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver) { UniqueId contextId = null; byte[] encodedCookie = null; UniqueId generation = null; bool isCookieMode = false; Fx.Assert(reader.NodeType == XmlNodeType.Element, ""); // check if there is an id string id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); SecurityContextSecurityToken sct = null; // There needs to be at least a contextId in here. reader.ReadFullStartElement(); reader.MoveToStartElement(Parent.SerializerDictionary.Identifier, Parent.SerializerDictionary.Namespace); contextId = reader.ReadElementContentAsUniqueId(); if (CanReadGeneration(reader)) { generation = ReadGeneration(reader); } if (reader.IsStartElement(Parent.SerializerDictionary.Cookie, XD.DotNetSecurityDictionary.Namespace)) { isCookieMode = true; ISecurityContextSecurityTokenCache sctCache; sct = TryResolveSecurityContextToken(contextId, generation, id, tokenResolver, out sctCache); if (sct == null) { encodedCookie = reader.ReadElementContentAsBase64(); if (encodedCookie != null) { throw new PlatformNotSupportedException(); // Ultimately depends on ProtectedData which isn't available cross platform // I believe this is server side only code but too complicated to reason about // to know for sure. } } else { reader.Skip(); } } reader.ReadEndElement(); if (contextId == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.NoSecurityContextIdentifier)); } if (sct == null && !isCookieMode) { ISecurityContextSecurityTokenCache sctCache; sct = TryResolveSecurityContextToken(contextId, generation, id, tokenResolver, out sctCache); } if (sct == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityContextTokenValidationException(SR.Format(SR.SecurityContextNotRegistered, contextId, generation))); } return(sct); }
public static object Deserialize(XmlDictionaryReader reader, Type targetType) { object returnValue = null; if (reader.IsStartElement()) { switch (reader.LocalName) { case XmlRpcProtocol.Nil: returnValue = null; break; case XmlRpcProtocol.Bool: returnValue = Convert.ChangeType((reader.ReadElementContentAsInt() == 1), targetType); break; case XmlRpcProtocol.ByteArray: if (targetType == typeof(Stream)) { returnValue = new MemoryStream(reader.ReadElementContentAsBase64()); } else { returnValue = Convert.ChangeType(reader.ReadElementContentAsBase64(), targetType); } break; case XmlRpcProtocol.DateTime: returnValue = Convert.ChangeType(reader.ReadElementContentAsDateTime(), targetType); break; case XmlRpcProtocol.Double: returnValue = Convert.ChangeType(reader.ReadElementContentAsDouble(), targetType); break; case XmlRpcProtocol.Int32: case XmlRpcProtocol.Integer: returnValue = Convert.ChangeType(reader.ReadElementContentAsString(), targetType); break; case XmlRpcProtocol.String: if (targetType == typeof(Uri)) { returnValue = new Uri(reader.ReadElementContentAsString()); } else { returnValue = Convert.ChangeType(reader.ReadElementContentAsString(), targetType); } break; case XmlRpcProtocol.Struct: returnValue = DeserializeStruct(reader, targetType); break; case XmlRpcProtocol.Array: if (targetType.IsArray || targetType is IEnumerable || targetType is IList || targetType is ICollection) { reader.ReadStartElement(XmlRpcProtocol.Array); ArrayList arrayData = new ArrayList(); reader.ReadStartElement(XmlRpcProtocol.Data); reader.MoveToContent(); while (reader.IsStartElement(XmlRpcProtocol.Value)) { reader.ReadStartElement(); arrayData.Add(Deserialize(reader, targetType.GetElementType())); reader.ReadEndElement(); reader.MoveToContent(); } if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == XmlRpcProtocol.Data) { reader.ReadEndElement(); } reader.ReadEndElement(); if (targetType is IEnumerable || targetType is IList || targetType is ICollection) { returnValue = arrayData; } else { returnValue = arrayData.ToArray(targetType.GetElementType()); } } else { throw new InvalidOperationException(); } break; } } return(returnValue); }
public override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlDictionaryReader reader) { byte[] secret = reader.ReadElementContentAsBase64(); return(new BinarySecretKeyIdentifierClause(secret, false)); }
public object ReadValue(XmlDictionaryReader reader) { object value; if (_isArray) { switch (_typeCode) { case TypeCode.Byte: value = reader.ReadElementContentAsBase64(); break; case TypeCode.Boolean: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadBooleanArray(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <bool>(); } break; case TypeCode.DateTime: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadDateTimeArray(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <DateTime>(); } break; case TypeCode.Decimal: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadDecimalArray(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <Decimal>(); } break; case TypeCode.Int32: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadInt32Array(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <Int32>(); } break; case TypeCode.Int64: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadInt64Array(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <Int64>(); } break; case TypeCode.Single: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadSingleArray(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <Single>(); } break; case TypeCode.Double: if (!reader.IsEmptyElement) { reader.ReadStartElement(); value = reader.ReadDoubleArray(_itemName, _itemNamespace); reader.ReadEndElement(); } else { reader.Read(); value = Array.Empty <Double>(); } break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter)); } } else { switch (_typeCode) { case TypeCode.Boolean: value = reader.ReadElementContentAsBoolean(); break; case TypeCode.DateTime: value = reader.ReadElementContentAsDateTime(); break; case TypeCode.Decimal: value = reader.ReadElementContentAsDecimal(); break; case TypeCode.Double: value = reader.ReadElementContentAsDouble(); break; case TypeCode.Int32: value = reader.ReadElementContentAsInt(); break; case TypeCode.Int64: value = reader.ReadElementContentAsLong(); break; case TypeCode.Single: value = reader.ReadElementContentAsFloat(); break; case TypeCode.String: return(reader.ReadElementContentAsString()); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter)); } } return(value); }
/// <summary> /// Reads the SessionSecurityToken from the given reader. /// </summary> /// <param name="reader">XmlReader over the SessionSecurityToken.</param> /// <param name="tokenResolver">SecurityTokenResolver that can used to resolve SessionSecurityToken.</param> /// <returns>An instance of <see cref="SessionSecurityToken"/>.</returns> /// <exception cref="ArgumentNullException">The input argument 'reader' is null.</exception> /// <exception cref="SecurityTokenException">The 'reader' is not positioned at a SessionSecurityToken /// or the SessionSecurityToken cannot be read.</exception> public override SecurityToken ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (tokenResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenResolver"); } byte[] encodedCookie = null; SysUniqueId contextId = null; SysUniqueId keyGeneration = null; string ns = null; string identifier = null; string instance = null; SecurityToken securityContextToken = null; SessionDictionary dictionary = SessionDictionary.Instance; XmlDictionaryReader dicReader = XmlDictionaryReader.CreateDictionaryReader(reader); if (dicReader.IsStartElement(WSSecureConversationFeb2005Constants.ElementNames.Name, WSSecureConversationFeb2005Constants.Namespace)) { ns = WSSecureConversationFeb2005Constants.Namespace; identifier = WSSecureConversationFeb2005Constants.ElementNames.Identifier; instance = WSSecureConversationFeb2005Constants.ElementNames.Instance; } else if (dicReader.IsStartElement(WSSecureConversation13Constants.ElementNames.Name, WSSecureConversation13Constants.Namespace)) { ns = WSSecureConversation13Constants.Namespace; identifier = WSSecureConversation13Constants.ElementNames.Identifier; instance = WSSecureConversation13Constants.ElementNames.Instance; } else { // // Something is wrong // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException( SR.GetString(SR.ID4230, WSSecureConversationFeb2005Constants.ElementNames.Name, dicReader.Name))); } string id = dicReader.GetAttribute(WSUtilityConstants.Attributes.IdAttribute, WSUtilityConstants.NamespaceURI); dicReader.ReadFullStartElement(); if (!dicReader.IsStartElement(identifier, ns)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException( SR.GetString(SR.ID4230, WSSecureConversation13Constants.ElementNames.Identifier, dicReader.Name))); } contextId = dicReader.ReadElementContentAsUniqueId(); if (contextId == null || string.IsNullOrEmpty(contextId.ToString())) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4242))); } // // The token can be a renewed token, in which case we need to know the // instance id, which will be the secondary key to the context id for // cache lookups // if (dicReader.IsStartElement(instance, ns)) { keyGeneration = dicReader.ReadElementContentAsUniqueId(); } if (dicReader.IsStartElement(CookieElementName, CookieNamespace)) { // Get the token from the Cache, which is returned as an SCT SecurityToken cachedToken = null; SecurityContextKeyIdentifierClause sctClause = null; if (keyGeneration == null) { sctClause = new SecurityContextKeyIdentifierClause(contextId); } else { sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration); } tokenResolver.TryResolveToken(sctClause, out cachedToken); if (cachedToken != null) { securityContextToken = cachedToken; dicReader.Skip(); } else { // // CookieMode // encodedCookie = dicReader.ReadElementContentAsBase64(); if (encodedCookie == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4237))); } // // appply transforms // byte[] decodedCookie = ApplyTransforms(encodedCookie, false); using (MemoryStream ms = new MemoryStream(decodedCookie)) { BinaryFormatter formatter = new BinaryFormatter(); securityContextToken = formatter.Deserialize(ms) as SecurityToken; } SessionSecurityToken sessionToken = securityContextToken as SessionSecurityToken; if (sessionToken != null && sessionToken.ContextId != contextId) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4229, sessionToken.ContextId, contextId))); } if (sessionToken != null && sessionToken.Id != id) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4227, sessionToken.Id, id))); } } } else { // // SessionMode // // Get the token from the Cache. SecurityToken cachedToken = null; SecurityContextKeyIdentifierClause sctClause = null; if (keyGeneration == null) { sctClause = new SecurityContextKeyIdentifierClause(contextId); } else { sctClause = new SecurityContextKeyIdentifierClause(contextId, keyGeneration); } tokenResolver.TryResolveToken(sctClause, out cachedToken); if (cachedToken != null) { securityContextToken = cachedToken; } } dicReader.ReadEndElement(); if (securityContextToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4243))); } return(securityContextToken); }