public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response) { SecurityToken token = null; response = new TokenResponse { TokenType = tokenType }; var result = TryIssueToken(appliesTo, principal, tokenType, out token); if (result == false) { return(false); } var ts = token.ValidTo.Subtract(DateTime.UtcNow); response.ExpiresIn = (int)ts.TotalSeconds; if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken) { var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType]; response.AccessToken = handler.WriteToken(token); } else { var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers; var sb = new StringBuilder(128); handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token); response.AccessToken = sb.ToString(); } return(result); }
/// <param name="entityId">[Required] Specifies the unique identifier of the SAML entity whose metadata is described by the element's contents.</param> /// <param name="metadataSigningCertificate">An metadata XML signature that authenticates the containing element and its contents.</param> public EntityDescriptor(EndpointReference entityId, X509Certificate2 metadataSigningCertificate = null) { EntityId = entityId; Id = new Saml2Id(); MetadataSigningCertificate = metadataSigningCertificate; CertificateIncludeOption = X509IncludeOption.EndCertOnly; }
void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new ArgumentNullException("appliesTo"); } }
/// <summary> /// Gets the proxy client. /// </summary> /// <returns> A LicenseServicesClient</returns> public static LicenseServiceClient GetClientProxy() { if ( client == null ) { string url = string.Empty; if ( System.Configuration.ConfigurationSettings.AppSettings["LicenseServicesUrl"] != null ) { url = System.Configuration.ConfigurationSettings.AppSettings["LicenseServicesUrl"]; } if ( url.Length > 0 ) { EndpointReference requestEndpoint = new EndpointReference(new Uri(url)); // Client client = new LicenseServiceClient(requestEndpoint); SoapHttpOutputChannel channel = (SoapHttpOutputChannel)client.Channel; channel.Options.Credentials = System.Net.CredentialCache.DefaultCredentials; channel.Options.Proxy = System.Net.GlobalProxySelection.Select; Security security = new Security(); client.Security = security; client.GetSessionID(); } else { throw new ArgumentNullException("System.Configuration.ConfigurationSettings.AppSettings[\"LicenseServicesUrl\"]","No service url found in the configuration file."); } } return client; }
public static EndpointReference GetEndpoint(string Url, string path) { EndpointReference endpoint = null; string url = Url; string viaurl = Url; if (url.Trim().StartsWith("https://")) { url = url.Trim().Replace("https://", "http://"); } if (!url.EndsWith("/")) { url += "/"; } if (!viaurl.EndsWith("/")) { viaurl += "/"; } endpoint = new EndpointReference(new Uri(url + path), new Uri(viaurl + path)); return(endpoint); }
/// <summary> /// Validates appliesTo and throws an exception if the appliesTo is null or contains an unexpected address. /// </summary> /// <param name="appliesTo">The AppliesTo value that came in the RST.</param> /// <exception cref="ArgumentNullException">If 'appliesTo' parameter is null.</exception> /// <exception cref="InvalidRequestException">If 'appliesTo' is not valid.</exception> private void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new ArgumentNullException("appliesTo"); } // TODO: Enable AppliesTo validation for allowed relying party Urls by setting enableAppliesToValidation to true. By default it is false. if (enableAppliesToValidation) { bool validAppliesTo = false; foreach (var rpUrl in PassiveRedirectBasedClaimsAwareWebApps) { if (appliesTo.Uri.Equals(new Uri(rpUrl))) { validAppliesTo = true; break; } } if (!validAppliesTo) { throw new InvalidRequestException(String.Format("The 'appliesTo' address '{0}' is not valid.", appliesTo.Uri.OriginalString)); } } }
public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate) { var credentials = new X509SigningCredentials(signingCertificate); // Figure out the hostname exposed from Azure and what port the service is listening on var realm = new EndpointAddress(identifier); var passiveEndpoint = new EndpointReference(passiveSignInUrl.AbsoluteUri); // Create metadata document for relying party var entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri)); var securityTokenServiceDescriptor = CreateSecurityTokenServiceDescriptor(credentials, passiveEndpoint); var applicationServiceDescriptor = CreateApplicationServiceDescriptor(); var serviceProviderSingleSignOnDescriptor = CreateServiceProviderSingleSignOnDescriptor(); entity.RoleDescriptors.Add(securityTokenServiceDescriptor); entity.RoleDescriptors.Add(applicationServiceDescriptor); entity.RoleDescriptors.Add(serviceProviderSingleSignOnDescriptor); // Set credentials with which to sign the metadata entity.SigningCredentials = credentials; // Serialize the metadata and convert it to an XElement var serializer = new MetadataSerializer(); var stream = new MemoryStream(); serializer.WriteMetadata(stream, entity); stream.Flush(); return(stream.ToArray()); }
private OutgoingMessage Subscribe(IncomingMessage requestMessage) { var toHeader = requestMessage.GetHeader <ToHeader>(); var subscriptionManagerReference = new EndpointReference(toHeader.Uri); var request = requestMessage.GetPayload <SubscribeRequest>(); var responseMessage = new OutgoingMessage() .AddHeader(new ActionHeader(Constants.SubscribeResponseAction), false); var expiration = CalculateExpiration(request.Expires); var filterInstance = GetFilterInstance(request); var identifier = GenerateUniqueSubscriptionIdentifier(); var subscription = new Subscription(expiration, _requestHandler, filterInstance, subscriptionManagerReference, requestMessage); _activeSubscriptions.Add(identifier, subscription); OnSubscribed(identifier, subscription); //R7.2.4-1 var body = new SubscribeResponse { SubscriptionManager = subscriptionManagerReference, EnumerationContext = request.Delivery.Mode == Delivery.DeliveryModePull ? new EnumerationContextKey( identifier) : null, Expires = expiration }; responseMessage.SetBody(new SerializerBodyWriter(body)); return(responseMessage); }
private void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new InvalidRequestException("The AppliesTo is null."); } }
internal SoapSqlInputChannel( EndpointReference endpoint, string unformatedConnectionString ) : base(endpoint) { _endpoint = endpoint; _unformatedConnectionString = unformatedConnectionString; _reader = SqlMessageReader.GetReaderForServer( endpoint.TransportAddress.Host, unformatedConnectionString ); }
public void It_has_a_EndpointReference_model_with_a_default_ctor_that_does_nothing() { var it = new EndpointReference(); Assert.IsNull(it.Address); Assert.IsNull(it.ReferenceProperties); }
public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out SecurityToken token) { token = null; var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue, AppliesTo = appliesTo, KeyType = KeyTypes.Bearer, TokenType = tokenType }; try { var rstr = _sts.Issue(principal, rst); token = rstr.RequestedSecurityToken.SecurityToken; return(true); } catch (Exception e) { Tracing.Error("Failed to issue token. An exception occurred. " + e); return(false); } }
internal SoapSqlOutputChannel( EndpointReference endpoint, string unformatedConnectionString ) : base(endpoint) { _endpoint = endpoint; _unformatedConnectionString = unformatedConnectionString; _lockObject = new object( ); }
public IDisposable Subscribe(IEventSink eventSink, object filterInstance, EndpointReference subscriptionManagerReference, IIncomingHeaders headers) { var selectorSetHeader = headers.GetHeader <SelectorSetHeader>(); var target = selectorSetHeader.Selectors.ExtractObjectName(); var listenerId = GenerateNextListenerId(); subscriptionManagerReference.AddProperty(new NotificationListenerListHeader(listenerId.ToString()), false); var subscriptionInfo = new SubscriptionInfo(eventSink, listenerId); lock (_subscriptions) { _subscriptions.Add(subscriptionInfo); } _server.AddNotificationListener(target, subscriptionInfo.OnNotification, subscriptionInfo.FilterNotification, listenerId); return(new SubscriptionRemover( () => { lock (_subscriptions) { var toRemove = _subscriptions.Single(x => x.EventSink == eventSink); _server.RemoveNotificationListener(target, toRemove.OnNotification, toRemove.FilterNotification, toRemove.ListenerId); _subscriptions.Remove(toRemove); } })); }
private OutgoingMessage Subscribe(IncomingMessage requestMessage) { var toHeader = requestMessage.GetHeader<ToHeader>(); var subscriptionManagerReference = new EndpointReference(toHeader.Uri); var request = requestMessage.GetPayload<SubscribeRequest>(); var responseMessage = new OutgoingMessage() .AddHeader(new ActionHeader(Constants.SubscribeResponseAction), false); var expiration = CalculateExpiration(request.Expires); var filterInstance = GetFilterInstance(request); var identifier = GenerateUniqueSubscriptionIdentifier(); var subscription = new Subscription(expiration, _requestHandler, filterInstance, subscriptionManagerReference, requestMessage); _activeSubscriptions.Add(identifier, subscription); OnSubscribed(identifier, subscription); //R7.2.4-1 var body = new SubscribeResponse { SubscriptionManager = subscriptionManagerReference, EnumerationContext = request.Delivery.Mode == Delivery.DeliveryModePull ? new EnumerationContextKey( identifier) : null, Expires = expiration }; responseMessage.SetBody(new SerializerBodyWriter(body)); return responseMessage; }
public void It_writes_address_property() { var endpointReference = new EndpointReference("http://example.com"); var xml = ToXml(endpointReference); var addressElement = xml.Element(Constants.Namespace + "Address"); Assert.AreEqual("http://example.com", addressElement.Value); }
public EndpointReference DeserializeCreateResponse(IncomingMessage createResponseMessage) { var reader = createResponseMessage.GetReaderAtBodyContents(); reader.ReadStartElement(Constants.CreateResponse_ResourceCreatedElement, Constants.Namespace); var result = new EndpointReference(); result.ReadXml(reader); reader.ReadEndElement(); return result; }
private void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new InvalidRequestException("The AppliesTo is null."); } // should check applies to, but for convienence, not }
public Selector(string name, EndpointReference value) : this(name) { if (value == null) { throw new ArgumentNullException("value"); } _addressReferenceValue = value; }
private static EndpointReference FromXml(XElement endpointReferenceElement) { var endpointAddress = new EndpointReference(); using (var reader = endpointReferenceElement.ToReader()) { endpointAddress.ReadXml(reader); } return endpointAddress; }
private static EndpointReference DeserializeCreateResponse(IncomingMessage createResponseMessage) { var reader = createResponseMessage.GetReaderAtBodyContents(); reader.ReadStartElement(Constants.CreateResponse_ResourceCreatedElement, Constants.Namespace); var result = new EndpointReference(); result.ReadOuterXml(reader); return(result); }
private static EndpointReference FromXml(XElement endpointReferenceElement) { var endpointAddress = new EndpointReference(); using (var reader = endpointReferenceElement.ToReader()) { endpointAddress.ReadXml(reader); } return(endpointAddress); }
/// <summary> /// Constructor. /// </summary> /// <param name="endpoint">The local endpoint for the channel.</param> /// <param name="socket">The socket for the channel.</param> /// <param name="transport">The transport for the channel.</param> internal SoapUdpInputChannel( EndpointReference endpoint, SoapUdpSocket socket, SoapUdpTransport transport ) : base(endpoint) { Debug.Assert( socket != null ); Debug.Assert( transport != null ); _remoteEndpoint = null; _socket = socket; _transport = transport; }
private static XElement ToXml(EndpointReference endpointAddress) { var buffer = new StringBuilder(); using (var writer = XmlWriter.Create(buffer)) { endpointAddress.WriteOuterXml(writer); writer.Flush(); } return XElement.Parse(buffer.ToString()); }
private static XElement ToXml(EndpointReference endpointAddress) { var buffer = new StringBuilder(); using (var writer = XmlWriter.Create(buffer)) { endpointAddress.WriteOuterXml(writer); writer.Flush(); } return(XElement.Parse(buffer.ToString())); }
/// <summary> /// Validates the appliesTo and throws an exception if the appliesTo is null or appliesTo contains some unexpected address. /// </summary> /// <param name="appliesTo">The AppliesTo parameter in the request that came in (RST)</param> /// <returns></returns> void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new InvalidRequestException("The appliesTo is null."); } if (!appliesTo.Uri.Equals(new Uri(_addressExpected))) { throw new InvalidRequestException(String.Format("The relying party address is not valid. Expected value is {0}, the actual value is {1}.", _addressExpected, appliesTo.Uri.AbsoluteUri)); } }
public void It_writes_embedded_headers() { var endpointReference = new EndpointReference("http://example.com"); endpointReference.AddProperty(new MessageHeader("someHeader", new[] {new XText("someText")}, false)); var xml = ToXml(endpointReference); var parametersElement = xml.Element(Constants.Namespace + "ReferenceProperties"); var headerElement = parametersElement.Element("someHeader"); var headerText = (XText)headerElement.FirstNode; Assert.AreEqual("someText", headerText.Value); }
static void Main(string[] args) { Console.WriteLine("Starting..."); EndpointReference requestEndpoint = new EndpointReference(new Uri("soap.tcp://localhost:2005/LicenseServices")); services = new LicenseServices(); SoapReceivers.Add(requestEndpoint, services); Console.WriteLine("Service started."); Console.WriteLine("Press X to exit"); Console.Read(); Console.Read(); Console.WriteLine("Service stopped."); }
/// <summary> /// 客户端白名单校验 /// </summary> /// <param name="appliesTo"></param> static void ValidateAppliesTo(EndpointReference appliesTo) { if (SupportedWebApps == null || SupportedWebApps.Length == 0) { return; } var validAppliesTo = SupportedWebApps.Any(x => appliesTo.Uri.Equals(x)); if (!validAppliesTo) { throw new InvalidRequestException(String.Format("The 'appliesTo' address '{0}' is not valid.", appliesTo.Uri.OriginalString)); } }
public Selector(XElement element) { _name = element.Attribute("Name").Value; if (element.FirstNode.NodeType == XmlNodeType.Text) { _simpleValue = ((XText)element.FirstNode).Value; } else if (element.FirstNode.NodeType == XmlNodeType.Element) { var reference = new EndpointReference(); reference.ReadOuterXml(element.FirstNode.CreateReader()); _addressReferenceValue = reference; } }
public Selector(XElement element) { _name = element.Attribute("Name").Value; if (element.FirstNode.NodeType == XmlNodeType.Text) { _simpleValue = ((XText) element.FirstNode).Value; } else if(element.FirstNode.NodeType == XmlNodeType.Element) { var reference = new EndpointReference(); reference.ReadOuterXml(element.FirstNode.CreateReader()); _addressReferenceValue = reference; } }
public string GetFederationMetadata(Uri endpoint) { // hostname var passiveEndpoint = new EndpointReference(endpoint.AbsoluteUri); var activeEndpoint = new EndpointReference(endpoint.AbsoluteUri); // metadata document var entity = new EntityDescriptor(new EntityId(TwitterClaims.IssuerName)); var sts = new SecurityTokenServiceDescriptor(); entity.RoleDescriptors.Add(sts); // signing key var signingKey = new KeyDescriptor(SigningCredentials.SigningKeyIdentifier) { Use = KeyType.Signing }; sts.Keys.Add(signingKey); // claim types sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "User name")); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.NameIdentifier, "Name Identifier", "User name identifier")); sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterToken, "Token", "Service token")); sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterTokenSecret, "Token Secret", "Service token secret")); // passive federation endpoint sts.PassiveRequestorEndpoints.Add(passiveEndpoint); // supported protocols //Inaccessable due to protection level //sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace)); sts.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706")); // add passive STS endpoint sts.SecurityTokenServiceEndpoints.Add(activeEndpoint); // metadata signing entity.SigningCredentials = SigningCredentials; // serialize var serializer = new MetadataSerializer(); using (var memoryStream = new MemoryStream()) { serializer.WriteMetadata(memoryStream, entity); return(Encoding.UTF8.GetString(memoryStream.ToArray())); } }
void ValidateAppliesTo(EndpointReference appliesTo) { if (_addressExpected == null || _addressExpected.Length == 0) { return; } var validAppliesTo = Enumerable.Any(_addressExpected, x => appliesTo.Uri.Equals(x)); if (!validAppliesTo) { throw new InvalidRequestException(String.Format("The relying party address is not valid. Expected value is {0}, the actual value is {1}.", _addressExpected, appliesTo.Uri.AbsoluteUri)); } }
/// <summary> /// Validates appliesTo and throws an exception if the appliesTo is null or appliesTo contains some unexpected address. /// </summary> /// <param name="appliesTo">The AppliesTo parameter in the request that came in (RST)</param> void ValidateAppliesTo(EndpointReference appliesTo) { if (appliesTo == null) { throw new InvalidRequestException("The AppliesTo is null."); } // Throw if the appliesTo doesn't match either of the RPs for which this STS is meant to issue tokens. if (!appliesTo.Uri.Equals(new Uri(PassiveRedirectBasedClaimsAwareMvcApp))) { throw new InvalidRequestException(String.Format("The AppliesTo address is not valid. Expected value is {0}, the actual value is {1}.", PassiveRedirectBasedClaimsAwareMvcApp, appliesTo.Uri.AbsoluteUri)); } }
public void It_writes_embedded_headers() { var endpointReference = new EndpointReference("http://example.com"); endpointReference.AddProperty(new MessageHeader("someHeader", new[] { new XText("someText") }, false)); var xml = ToXml(endpointReference); var parametersElement = xml.Element(Constants.Namespace + "ReferenceProperties"); var headerElement = parametersElement.Element("someHeader"); var headerText = (XText)headerElement.FirstNode; Assert.AreEqual("someText", headerText.Value); }
public HttpResponseMessage Post(TokenRequest tokenRequest) { Tracing.Information("OAuth2 endpoint called."); Client client = null; if (!ValidateClient(out client)) { Tracing.Error("Invalid client: " + ClaimsPrincipal.Current.Identity.Name); return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidClient)); } Tracing.Information("Client: " + client.Name); var tokenType = ConfigurationRepository.Global.DefaultHttpTokenType; // validate scope EndpointReference appliesTo; try { appliesTo = new EndpointReference(tokenRequest.Scope); Tracing.Information("OAuth2 endpoint called for scope: " + tokenRequest.Scope); } catch { Tracing.Error("Malformed scope: " + tokenRequest.Scope); return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidScope)); } // check grant type if (string.Equals(tokenRequest.Grant_Type, OAuth2Constants.GrantTypes.Password, System.StringComparison.Ordinal)) { if (ConfigurationRepository.OAuth2.EnableResourceOwnerFlow) { if (client.AllowResourceOwnerFlow) { return(ProcessResourceOwnerCredentialRequest(tokenRequest.UserName, tokenRequest.Password, appliesTo, tokenType, client)); } else { Tracing.Error("Client is not allowed to use the resource owner password flow:" + client.Name); } } } Tracing.Error("invalid grant type: " + tokenRequest.Grant_Type); return(OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType)); }
public void ReadXml(XmlReader reader) { if (reader.Name() == ItemElementName) { _mode = EnumerationMode.EnumerateObjectAndEPR; reader.ReadStartElement(ItemElementName); _rawValue = reader.ReadOuterXml(); } _eprValue = new EndpointReference(); _eprValue.ReadOuterXml(reader); if (IncludeObject()) { reader.ReadEndElement(); } }
public HttpResponseMessage Get(HttpRequestMessage request) { Tracing.Information("Simple HTTP endpoint called."); var query = request.GetQueryNameValuePairs(); var auth = new AuthenticationHelper(); var realm = query.FirstOrDefault(p => p.Key.Equals("realm", System.StringComparison.OrdinalIgnoreCase)).Value; var tokenType = query.FirstOrDefault(p => p.Key.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase)).Value; if (string.IsNullOrWhiteSpace(realm)) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "realm parameter is missing.")); } EndpointReference appliesTo; try { appliesTo = new EndpointReference(realm); Tracing.Information("Simple HTTP endpoint called for realm: " + realm); } catch { Tracing.Error("Malformed realm: " + realm); return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name.")); } if (string.IsNullOrWhiteSpace(tokenType)) { tokenType = ConfigurationRepository.Global.DefaultHttpTokenType; } Tracing.Verbose("Token type: " + tokenType); TokenResponse tokenResponse; var sts = new STS(); if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse)) { var resp = request.CreateResponse <TokenResponse>(HttpStatusCode.OK, tokenResponse); return(resp); } else { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid request.")); } }
public SecurityToken GetSecurityToken() { //service identifier whitin the ADFS server where I want to access, must be configured as RP in ADFS //this is the same value we configure on server side for the parameter audienceUris EndpointReference serviceAddress = new EndpointReference(@"http://testWCFService.gianlucb.local"); //who gives me the token string stsAddress; //ignores certificates error ServicePointManager.ServerCertificateValidationCallback = (x, y, z, w) => true; //USERNAME stsAddress = @"https://sts.gianlucb.local/adfs/services/trust/13/usernamemixed"; WS2007HttpBinding stsBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential); stsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; stsBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; stsBinding.Security.Message.EstablishSecurityContext = false; WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(stsBinding, stsAddress); trustChannelFactory.Credentials.SupportInteractive = false; trustChannelFactory.Credentials.UserName.Password = "******"; trustChannelFactory.Credentials.UserName.UserName = "******"; //--------------------- //connection WSTrustChannel channel = (WSTrustChannel)trustChannelFactory.CreateChannel(); RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue); rst.AppliesTo = serviceAddress; rst.KeyType = KeyTypes.Symmetric; RequestSecurityTokenResponse rstr = null; SecurityToken token = channel.Issue(rst, out rstr); var xmlSecurityToken = token as GenericXmlSecurityToken; Trace.WriteLine("Received the token:"); Trace.WriteLine(xmlSecurityToken.TokenXml.InnerXml); return(token); }
private HttpResponseMessage ProcessResourceOwnerCredentialRequest(TokenRequest request, string tokenType, Client client) { Tracing.Information("Starting resource owner password credential flow for client: " + client.Name); var appliesTo = new EndpointReference(request.Scope); if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password)) { Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri); return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant)); } if (UserRepository.ValidateUser(request.UserName, request.Password)) { return(CreateTokenResponse(request.UserName, client, appliesTo, tokenType, client.AllowRefreshToken)); } Tracing.Error("Resource owner credential validation failed: " + request.UserName); return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant)); }
public EndpointReference GetEndpoint(string path) { string url = Url; string viaurl = url; if (string.IsNullOrEmpty(viaurl)) { viaurl = url; } if (!url.EndsWith("/")) { url += "/"; } if (!viaurl.EndsWith("/")) { viaurl += "/"; } EndpointReference endpoint = new EndpointReference(new Uri(url + path), new Uri(viaurl + path)); return(endpoint); }
/// <summary> /// Gets the proxy client. /// </summary> /// <returns> A LicenseServiceClient.</returns> public static LicenseServiceClient GetClientProxy() { if ( client == null ) { if ( System.Configuration.ConfigurationSettings.AppSettings["LicenseServicesUrl"] == null ) { throw new ArgumentException("There is no License Services URL set in the configuration file."); } else { string url = System.Configuration.ConfigurationSettings.AppSettings["LicenseServicesUrl"]; EndpointReference requestEndpoint = new EndpointReference(new Uri(url)); // Client client = new LicenseServiceClient(requestEndpoint); Security security = new Security(); client.Security = security; } } return client; }
/// <summary> /// Build an ISoapInputChannel for the specified endpoint. /// </summary> /// <param name="endpoint"></param> /// <param name="capabilities"></param> /// <returns></returns> ISoapInputChannel ISoapTransport.GetInputChannel( EndpointReference endpoint, SoapChannelCapabilities capabilities ) { if ( endpoint == null ) throw new ArgumentNullException( "endpoint" ); if ( capabilities == SoapChannelCapabilities.ActivelyListening && endpoint.TransportAddress.Scheme != UriScheme ) throw new ArgumentException( "Invalid Transport Scheme specified" ); if ( capabilities != SoapChannelCapabilities.None && capabilities != SoapChannelCapabilities.ActivelyListening ) throw new NotSupportedException( "Unsupported SoapChannelCapabilities Flags" ); Debug( "GetInputChannel TransportAddress: " + endpoint.TransportAddress.ToString( ) ); // // NOTE: Transport level receiving requires that we map the transport address to // one of the local interfaces for the machine. // IPEndPoint localEP = GetLocalIPEndPoint( endpoint.TransportAddress ); if ( localEP == null ) throw new ArgumentException( "Transport address " + endpoint.TransportAddress.ToString( ) + " could not be mapped to a local network interface." ); // // Lock the InputChannels collection while we register the new channel. // lock ( InputChannels.SyncRoot ) { // // Determine whether the request channel already exists. // SoapUdpInputChannel channel = InputChannels[ endpoint ] as SoapUdpInputChannel; SoapUdpSocket socket; if ( channel != null ) return channel; // // Lock the sockets collection while checking for an existing socket // or creating a new one. // lock ( _sockets ) { socket = _sockets[ localEP ] as SoapUdpSocket; if ( socket == null ) { // // There is no suitable socket available. Create a new one, // increment it's reference count and start receiving packets. // socket = new SoapUdpSocket( localEP, _options ); _sockets[ localEP ] = socket; socket.AddReference( ); socket.BeginReceiveFrom( new AsyncCallback( OnReceiveComplete ), socket ); } else { // // Increment the reference count on the listener for unregister behaviour // socket.AddReference( ); } } // // Create the channel, then modify the via so that it matches // the local endpoint address. // // TODO: Fix the race condition here where a packet might be // received before the channel is established for // dispatching. // channel = new SoapUdpInputChannel( endpoint, socket, this ); // // TODO: Do not do Via for the Any address // channel.LocalEndpoint.Via = new Via( ConvertToUri( localEP ) ); // // Record the channel // InputChannels.Add( channel ); return channel; } }
/// <summary> /// Send does not catch any exceptions - the caller must handle exceptions. /// </summary> internal void SendTo( SoapEnvelope envelope, EndpointReference destination ) { if ( _localEP != null ) SoapUdpTransport.Debug( "SoapUdpSocket[" + _localEP.ToString( ) + "] Send" ); else SoapUdpTransport.Debug( "SoapUdpSocket[Unbound] Send" ); // // IPv6: We need to process each of the addresses return from // DNS when trying to connect. Use of AddressList[0] is // bad form. // string host = destination.TransportAddress.Host; int port = ( destination.TransportAddress.Port == -1 ) ? _options.DefaultPort : destination.TransportAddress.Port; IPAddress remoteAddress = null; IPAddress[ ] remoteAddresses = null; try { if ( string.Compare( host, "localhost", true, CultureInfo.CurrentCulture ) == 0 && Socket.SupportsIPv4 ) remoteAddress = IPAddress.Loopback; else if ( string.Compare( host, "localhost6", true, CultureInfo.CurrentCulture ) == 0 && Socket.OSSupportsIPv6 ) remoteAddress = IPAddress.IPv6Loopback; else remoteAddress = IPAddress.Parse( host ); remoteAddresses = new IPAddress[ 1 ] { remoteAddress }; } catch { // // Intentionally empty - hostname is not a plain IP address. // Use DNS to resolve the name. // remoteAddresses = Dns.GetHostEntry( host ).AddressList; } // // Now form the packet to send. // MemoryStream stream = new MemoryStream( ); _formatter.Serialize( envelope, stream ); System.Diagnostics.Debug.Assert( stream.Length <= SoapUdpDatagram.MaxDataSize ); if ( stream.Length > SoapUdpDatagram.MaxDataSize ) throw new ArgumentException( "Message is too large" ); if ( _localEP != null ) SoapUdpTransport.Debug( "SoapUdpSocket[" + _localEP.ToString( ) + "] Packet size is " + stream.Length.ToString( ) ); else SoapUdpTransport.Debug( "SoapUdpSocket[Unbound] Packet size is " + stream.Length.ToString( ) ); for ( int i = 0; i < remoteAddresses.Length; i++ ) { // // Set the address family appropriately, create the socket and // try to connect. // remoteAddress = remoteAddresses[ i ]; if ( _socket == null ) { // // Unbound case: create a temporary socket to send the data on. // Socket socket = new Socket( remoteAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp ); socket.SendTo( stream.GetBuffer( ), 0, ( int )stream.Length, SocketFlags.None, new IPEndPoint( remoteAddress, port ) ); socket.Close( ); break; } else if ( remoteAddress.AddressFamily == _socket.AddressFamily ) { // // Bound case: use the existing socket to send the data on. // _socket.SendTo( stream.GetBuffer( ), 0, ( int )stream.Length, SocketFlags.None, new IPEndPoint( remoteAddress, port ) ); break; } } }
public static EndpointReference GetEndpoint(string Url, string path) { EndpointReference endpoint = null; string url = Url; string viaurl = Url; if (url.Trim().StartsWith("https://")) { url = url.Trim().Replace("https://", "http://"); } if (!url.EndsWith("/")) { url += "/"; } if (!viaurl.EndsWith("/")) { viaurl += "/"; } endpoint = new EndpointReference(new Uri(url + path), new Uri(viaurl + path)); return endpoint; }
//Called by SoapSmtpOutputChannel.Send(). Implementing //this on the transport instead of the channel keeps all references to //transport-specific network resources inside of the transport class, and keeps //the channels clean. internal void Send( SoapEnvelope e, EndpointReference destination ) { //Create a new mailbox based on the TransportAddress of the endpoint. Again, //we use TransportAddress instead of Address to allow soap.smtp:// endpoints to //act as intermediaries. Mailbox box = new Mailbox( destination.TransportAddress, _options ); //Send the message via SMTP. box.Send( e, destination.TransportAddress ); }
public static string EndpointToConnectionString( EndpointReference endpoint, string connectionString ) { return HostnameToConnectionString( endpoint.TransportAddress.Host, connectionString ); }
/// <summary> /// Creates a new LicenseServiceClient. /// </summary> /// <param name="er"> The EndpointReference type. </param> public LicenseServiceClient(EndpointReference er) : base(er) { }
//Create a new output channel that can send messages to the provided Endpoint, using //the provided instance of SoapSmtpTransport. public SoapSmtpOutputChannel( EndpointReference epr, SoapSmtpTransport transport ) : base(epr) { this.transport = transport; }
public Subscription(Expires expires, IEventingRequestHandler requestHandler, object filterInstance, EndpointReference subscriptionManagerReference, IIncomingHeaders incomingHeaders) { _handlerSubscription = requestHandler.Subscribe(this, filterInstance, subscriptionManagerReference, incomingHeaders); Renew(expires); }
protected SqlChannelBase( EndpointReference endpoint ) { _lockObject = new object( ); _endpoint = endpoint; }
public SoapSmtpInputChannel(EndpointReference epr) : base(epr) { }
public EnumerationItem(EndpointReference epr) { _eprValue = epr; _mode = EnumerationMode.EnumerateEPR; }
public EnumerationItem(EndpointReference epr, object value) { _eprValue = epr; _objectValue = value; _mode = EnumerationMode.EnumerateObjectAndEPR; }
//Creates a new InputChannel for the specified endpoint. As part of this operation, the transport //must create a new Mailbox and begin polling that Mailbox for new messages. public ISoapInputChannel GetInputChannel( EndpointReference endpoint, Microsoft.Web.Services3.Messaging.SoapChannelCapabilities capabilities ) { //The newly created InputChannel SoapSmtpInputChannel channel; if ( null == endpoint ) throw new ArgumentNullException( "destination", "Cannot open input channel on null endpoint" ); //It's vitally important to lock the InputChannels collection. Otherwise, we get a race condition //if a message arrives between the call to m.BeginReceive() and InputChannels.Add(). However, //SoapTransport.DispatchMessage() will block trying to take the lock on InputChannels, //so as long as we lock here we're OK. lock ( this.InputChannels.SyncRoot ) { //Create a new Mailbox on the transport address of the endpoint. We use endpoint.TransportAddress here //to look for a Via on the endpoint if one exists. If we just used endpoint.Address, we'd be unable //to use soap.smtp endpoints as intermediaries. Mailbox m = FindOrCreateMailbox( endpoint.TransportAddress ); //Create the new input channel channel = new SoapSmtpInputChannel( endpoint ); //If the mailbox isn't already listening, start polling for messages. if ( !m.Listening ) m.BeginRecieve( new AsyncCallback( this.OnReceiveComplete ) ); //Finally, add the new channel to our collection of InputChannels (which we inherited from the SoapTransport base //class). This will allow us to dispatch messages addressed to this channel via DispatchMessage(). this.InputChannels.Add( channel ); } //Return the channel so that the higher-level messaging components can do what they need to on it. //Usually, they will take the returned InputChannel and call BeginReceive() on it, so that when messages //arrive on the channel they can pick them off and dispatch them to the appropriate SoapReceiver for processing. return channel; }
//Creating an OutputChannel is a lot easier than creating an InputChannel, since we don't have to //store the channel or the Mailbox. We just do some sanity checks on the input and then return //a new SoapSmtpOutputChannel. public ISoapOutputChannel GetOutputChannel( EndpointReference endpoint, Microsoft.Web.Services3.Messaging.SoapChannelCapabilities capabilities ) { if ( capabilities != SoapChannelCapabilities.None ) throw new NotSupportedException( "Unsupported channel capabilities" ); if ( endpoint == null ) throw new ArgumentNullException( "endpoint", "Cannot open output channel for null endpoint" ); return new SoapSmtpOutputChannel( endpoint, this ); }
/// <summary> /// Builds an ISoapOutputChannel for the specified endpoint. /// </summary> /// <param name="endpoint">The target endpoint</param> /// <param name="capabilities">The channel capabilities</param> /// <returns>ISoapOutputChannel</returns> ISoapOutputChannel ISoapTransport.GetOutputChannel( EndpointReference endpoint, SoapChannelCapabilities capabilities ) { Debug( "GetOutputChannel TransportAddress: " + endpoint.TransportAddress.ToString( ) ); if ( endpoint.TransportAddress.Scheme != UriScheme ) throw new ArgumentException( "The transport scheme for the specified endpoint does not match this transport.", "endpoint" ); if ( capabilities != SoapChannelCapabilities.None ) throw new NotSupportedException( "Unsupported SoapChannelCapabilities flags. Use SoapChannelCapabilities.None." ); return new SoapUdpOutputChannel( endpoint, new SoapUdpSocket( _options ), this ); }