public RtspSource(string name, string sourceLocation, NetworkCredential credential = null, AuthenticationSchemes authType = AuthenticationSchemes.None, Rtsp.RtspClient.ClientProtocolType? rtpProtocolType = null, int bufferSize = RtspClient.DefaultBufferSize, Sdp.MediaType? specificMedia = null, TimeSpan? startTime = null, TimeSpan? endTime = null) : this(name, new Uri(sourceLocation), credential, authType, rtpProtocolType, bufferSize, specificMedia, startTime, endTime) { //Check for a null Credential and UserInfo in the Location given. if (credential == null && !string.IsNullOrWhiteSpace(m_Source.UserInfo)) { RtspClient.Credential = Media.Common.Extensions.Uri.UriExtensions.ParseUserInfo(m_Source); //Remove the user info from the location RtspClient.CurrentLocation = new Uri(RtspClient.CurrentLocation.AbsoluteUri.Replace(RtspClient.CurrentLocation.UserInfo + (char)Common.ASCII.AtSign, string.Empty).Replace(RtspClient.CurrentLocation.UserInfo, string.Empty)); } }
public static bool DoesAuthTypeMatch(AuthenticationSchemes authScheme, string authType) { if ((authType == null) || (authType.Length == 0)) { return authScheme.IsSet(AuthenticationSchemes.Anonymous); } if (authType.Equals("kerberos", StringComparison.OrdinalIgnoreCase) || authType.Equals("negotiate", StringComparison.OrdinalIgnoreCase)) { return authScheme.IsSet(AuthenticationSchemes.Negotiate); } else if (authType.Equals("ntlm", StringComparison.OrdinalIgnoreCase)) { return authScheme.IsSet(AuthenticationSchemes.Negotiate) || authScheme.IsSet(AuthenticationSchemes.Ntlm); } AuthenticationSchemes authTypeScheme; if (!Enum.TryParse<AuthenticationSchemes>(authType, true, out authTypeScheme)) { return false; } return authScheme.IsSet(authTypeScheme); }
internal static HttpClientCredentialType MapToClientCredentialType(AuthenticationSchemes authenticationSchemes) { HttpClientCredentialType result; switch (authenticationSchemes) { case AuthenticationSchemes.Anonymous: result = HttpClientCredentialType.None; break; case AuthenticationSchemes.Basic: result = HttpClientCredentialType.Basic; break; case AuthenticationSchemes.Digest: result = HttpClientCredentialType.Digest; break; case AuthenticationSchemes.Ntlm: result = HttpClientCredentialType.Ntlm; break; case AuthenticationSchemes.Negotiate: result = HttpClientCredentialType.Windows; break; default: Fx.Assert("unsupported client AuthenticationScheme"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } return result; }
public static bool IsWindowsAuth(AuthenticationSchemes authScheme) { if (authScheme != AuthenticationSchemes.Negotiate) { return (authScheme == AuthenticationSchemes.Ntlm); } return true; }
public HttpListener(ILogger logger) { _logger = logger; prefixes = new HttpListenerPrefixCollection(logger, this); registry = new Hashtable(); connections = Hashtable.Synchronized(new Hashtable()); auth_schemes = AuthenticationSchemes.Anonymous; }
ServiceAuthenticationBehavior(ServiceAuthenticationBehavior other) { this.serviceAuthenticationManager = other.ServiceAuthenticationManager; this.authenticationSchemes = other.authenticationSchemes; this.isReadOnly = other.isReadOnly; this.isAuthenticationManagerSet = other.isAuthenticationManagerSet; this.isAuthenticationSchemesSet = other.isAuthenticationSchemesSet; }
ArrayList wait_queue; // List<ListenerAsyncResult> wait_queue; public HttpListener () { prefixes = new HttpListenerPrefixCollection (this); registry = new Hashtable (); ctx_queue = new ArrayList (); wait_queue = new ArrayList (); auth_schemes = AuthenticationSchemes.Anonymous; }
public static HttpListener CreateAndStartListener (string prefix, AuthenticationSchemes authSchemes) { HttpListener listener = new HttpListener (); listener.AuthenticationSchemes = authSchemes; listener.Prefixes.Add (prefix); listener.Start (); return listener; }
internal HttpListenerContext(HttpListener httpListener, RequestContextBase memoryBlob) { if (Logging.On) Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpListener#" + ValidationHelper.HashString(httpListener) + " requestBlob=" + ValidationHelper.HashString((IntPtr) memoryBlob.RequestBlob)); m_Listener = httpListener; m_Request = new HttpListenerRequest(this, memoryBlob); m_AuthenticationSchemes = httpListener.AuthenticationSchemes; m_ExtendedProtectionPolicy = httpListener.ExtendedProtectionPolicy; GlobalLog.Print("HttpListenerContext#" + ValidationHelper.HashString(this) + "::.ctor() HttpListener#" + ValidationHelper.HashString(m_Listener) + " HttpListenerRequest#" + ValidationHelper.HashString(m_Request)); }
/// <summary> /// Initializes a new instance of the <see cref="HttpListener"/> class. /// </summary> public HttpListener() { prefixes = new HttpListenerPrefixCollection (this); registry = new Dictionary<HttpListenerContext, HttpListenerContext> (); connections = new Dictionary<HttpConnection, HttpConnection> (); ctx_queue = new List<HttpListenerContext> (); wait_queue = new List<ListenerAsyncResult> (); auth_schemes = AuthenticationSchemes.Anonymous; }
/// <summary> /// Initializes a new instance of the <see cref="HttpListener"/> class. /// </summary> public HttpListener () { _authSchemes = AuthenticationSchemes.Anonymous; _connections = new Dictionary<HttpConnection, HttpConnection> (); _contextQueue = new List<HttpListenerContext> (); _prefixes = new HttpListenerPrefixCollection (this); _registry = new Dictionary<HttpListenerContext, HttpListenerContext> (); _waitQueue = new List<ListenerAsyncResult> (); }
internal AuthenticationChallenge(AuthenticationSchemes scheme, string realm) : base(scheme, new NameValueCollection ()) { Parameters["realm"] = realm; if (scheme == AuthenticationSchemes.Digest) { Parameters["nonce"] = CreateNonceValue (); Parameters["algorithm"] = "MD5"; Parameters["qop"] = "auth"; } }
public HttpListener () { prefixes = new HttpListenerPrefixCollection (this); registry = new Hashtable (); connections = Hashtable.Synchronized (new Hashtable ()); ctx_queue = new ArrayList (); wait_queue = new ArrayList (); auth_schemes = AuthenticationSchemes.Anonymous; defaultServiceNames = new ServiceNameStore (); extendedProtectionPolicy = new ExtendedProtectionPolicy (PolicyEnforcement.Never); }
public static WebhookServer Create(string url, Action<HttpListenerContext> handler, AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous) { var listener = new HttpListener { Prefixes = { url }, AuthenticationSchemes = authenticationSchemes }; var server = new WebhookServer(listener, handler); server.Start(); return server; }
public static bool TryExtract(BindingParameterCollection collection, out AuthenticationSchemes authenticationSchemes) { Fx.Assert(collection != null, "collection != null"); authenticationSchemes = AuthenticationSchemes.None; AuthenticationSchemesBindingParameter instance = collection.Find<AuthenticationSchemesBindingParameter>(); if (instance != null) { authenticationSchemes = instance.AuthenticationSchemes; return true; } return false; }
public static bool DoesAuthTypeMatch(AuthenticationSchemes authScheme, string authType) { if ((authType == null) || (authType.Length == 0)) { return (authScheme == AuthenticationSchemes.Anonymous); } if (authScheme == AuthenticationSchemes.Negotiate) { return ((authType.Equals("ntlm", StringComparison.OrdinalIgnoreCase) || authType.Equals("kerberos", StringComparison.OrdinalIgnoreCase)) || authType.Equals("negotiate", StringComparison.OrdinalIgnoreCase)); } return authScheme.ToString().Equals(authType, StringComparison.OrdinalIgnoreCase); }
public static bool IsSingleton(AuthenticationSchemes v) { switch (v) { case AuthenticationSchemes.Digest: case AuthenticationSchemes.Negotiate: case AuthenticationSchemes.Ntlm: case AuthenticationSchemes.Basic: case AuthenticationSchemes.Anonymous: return true; } return false; }
internal AuthenticationResponse ( AuthenticationSchemes scheme, NameValueCollection parameters, NetworkCredential credentials, uint nonceCount) : base (scheme, parameters) { Parameters["username"] = credentials.UserName; Parameters["password"] = credentials.Password; Parameters["uri"] = credentials.Domain; _nonceCount = nonceCount; if (scheme == AuthenticationSchemes.Digest) initAsDigest (); }
internal void ParseAuthentication (AuthenticationSchemes expectedSchemes) { if (expectedSchemes == AuthenticationSchemes.Anonymous) return; // TODO: Handle NTLM/Digest modes string header = request.Headers ["Authorization"]; if (header == null || header.Length < 2) return; string [] authenticationData = header.Split (new char [] {' '}, 2); if (string.Compare (authenticationData [0], "basic", true) == 0) { user = ParseBasicAuthentication (authenticationData [1]); } // TODO: throw if malformed -> 400 bad request }
//--- Constructors --- public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme) { if(env == null) { throw new ArgumentNullException("env"); } if(uri == null) { throw new ArgumentNullException("uri"); } _env = env; _uri = uri.WithoutCredentialsPathQueryFragment(); _minSimilarity = _uri.MaxSimilarity; _sourceInternal = _uri + " (internal)"; _sourceExternal = _uri.ToString(); _authenticationSheme = authenticationSheme; }
public static Task<NetworkCredential> GetCredentialAsync(AuthenticationSchemes authenticationScheme, SecurityTokenProviderContainer credentialProvider, OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper, OutWrapper<AuthenticationLevel> authenticationLevelWrapper, CancellationToken cancellationToken) { impersonationLevelWrapper.Value = TokenImpersonationLevel.None; authenticationLevelWrapper.Value = AuthenticationLevel.None; if (authenticationScheme == AuthenticationSchemes.Anonymous) { return Task.FromResult((NetworkCredential)null); } return GetCredentialCoreAsync(authenticationScheme, credentialProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken); }
/// <summary> /// Initializes a new instance of <see cref="HttpListenerSettings"/> class. /// </summary> /// <param name="authenticationSchemes">The scheme used to authenticate clients.</param> /// <param name="ignoreWriteExceptions">A <see cref="Boolean"/> value that specifies whether application receives exceptions that occur when a <see cref="HttpListener"/> sends the response to the client.</param> /// <param name="prefixes">The Uniform Resource Identifier (URI) prefixes handled by a <see cref="HttpListener"/> object.</param> /// <param name="realm">The realm, or resource partition, associated with a <see cref="HttpListener"/> object.</param> public HttpListenerSettings(AuthenticationSchemes authenticationSchemes, Boolean ignoreWriteExceptions, IList<String> prefixes, String realm) { // Check arguments if (prefixes == null) { throw new ArgumentNullException(nameof(prefixes)); } AuthenticationSchemes = authenticationSchemes; IgnoreWriteExceptions = ignoreWriteExceptions; Prefixes = prefixes; Realm = realm; }
//--- Constructors --- public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme, string dreamInParamAuthtoken) { if(env == null) { throw new ArgumentNullException("env"); } if(uri == null) { throw new ArgumentNullException("uri"); } _env = env; _uri = uri.WithoutCredentialsPathQueryFragment(); _minSimilarity = _uri.MaxSimilarity; _sourceInternal = _uri + " (internal)"; _sourceExternal = _uri.ToString(); _authenticationSheme = authenticationSheme; _dreamInParamAuthtoken = dreamInParamAuthtoken; this.ServerSignature = "Dream-HTTPAPI/" + DreamUtil.DreamVersion; }
/// <summary> /// Initializes a new instance of the <see cref="HttpListenerServerBase"/> class. /// </summary> /// <param name="prefixes">The URL prefixes.</param> /// <param name="authenticationSchema">The authentication schema.</param> /// <exception cref="Beyova.ExceptionSystem.InvalidObjectException">prefixes</exception> /// <exception cref="InvalidObjectException">prefixes</exception> public HttpListenerServerBase(string[] prefixes, AuthenticationSchemes authenticationSchema = AuthenticationSchemes.Anonymous) { // URI prefixes are required, // for example "http://beyova.org:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw ExceptionFactory.CreateInvalidObjectException("prefixes"); } // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.AuthenticationSchemes = authenticationSchema; }
/// <summary> /// Initializes a new instance of the <see cref="HttpServerBase" /> class. /// </summary> /// <param name="urlPrefixes">The URL prefixes.</param> /// <param name="authenticationSchema">The authentication schema.</param> /// <exception cref="InvalidObjectException">urlPrefixes</exception> public GuidIconHttpService(string[] urlPrefixes, AuthenticationSchemes authenticationSchema = AuthenticationSchemes.Anonymous) { // URI prefixes are required, // for example "http://ifunction.org:8080/index/". if (urlPrefixes == null || urlPrefixes.Length == 0) { throw new ArgumentNullException("urlPrefixes"); } // Add the prefixes. foreach (string s in urlPrefixes) { listener.Prefixes.Add(s); } listener.AuthenticationSchemes = authenticationSchema; }
internal void ParseAuthentication(AuthenticationSchemes expectedSchemes) { if (expectedSchemes == AuthenticationSchemes.Anonymous) return; // TODO: Handle NTLM/Digest modes var header = Request.Headers["Authorization"]; if (header == null || header.Length < 2) return; var authenticationData = header.Split(new[] {' '}, 2); if (string.Compare(authenticationData[0], "basic", StringComparison.OrdinalIgnoreCase) == 0) { User = ParseBasicAuthentication(authenticationData[1]); } // TODO: throw if malformed -> 400 bad request }
/// <summary> /// Initializes a new instance of the <see cref="HttpListener"/> class. /// </summary> public HttpListener() { _authSchemes = AuthenticationSchemes.Anonymous; _connections = new Dictionary<HttpConnection, HttpConnection> (); _connectionsSync = ((ICollection) _connections).SyncRoot; _ctxQueue = new List<HttpListenerContext> (); _ctxQueueSync = ((ICollection) _ctxQueue).SyncRoot; _ctxRegistry = new Dictionary<HttpListenerContext, HttpListenerContext> (); _ctxRegistrySync = ((ICollection) _ctxRegistry).SyncRoot; _prefixes = new HttpListenerPrefixCollection (this); _waitQueue = new List<ListenerAsyncResult> (); _waitQueueSync = ((ICollection) _waitQueue).SyncRoot; }
static async Task<NetworkCredential> GetCredentialCoreAsync(AuthenticationSchemes authenticationScheme, SecurityTokenProviderContainer credentialProvider, OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper, OutWrapper<AuthenticationLevel> authenticationLevelWrapper, CancellationToken cancellationToken) { impersonationLevelWrapper.Value = TokenImpersonationLevel.None; authenticationLevelWrapper.Value = AuthenticationLevel.None; NetworkCredential result = null; switch (authenticationScheme) { case AuthenticationSchemes.Basic: result = await TransportSecurityHelpers.GetUserNameCredentialAsync(credentialProvider, cancellationToken); impersonationLevelWrapper.Value = TokenImpersonationLevel.Delegation; break; case AuthenticationSchemes.Digest: result = await TransportSecurityHelpers.GetSspiCredentialAsync(credentialProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken); ValidateDigestCredential(result, impersonationLevelWrapper.Value); break; case AuthenticationSchemes.Negotiate: result = await TransportSecurityHelpers.GetSspiCredentialAsync(credentialProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken); break; case AuthenticationSchemes.Ntlm: result = await TransportSecurityHelpers.GetSspiCredentialAsync(credentialProvider, impersonationLevelWrapper, authenticationLevelWrapper, cancellationToken); if (authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException(SR.CredentialDisallowsNtlm)); } break; default: // The setter for this property should prevent this. throw Fx.AssertAndThrow("GetCredential: Invalid authentication scheme"); } return result; }
internal static string ToString(AuthenticationSchemes authScheme) { switch (authScheme) { case AuthenticationSchemes.Digest: return "digest"; case AuthenticationSchemes.Negotiate: return "negotiate"; case AuthenticationSchemes.Ntlm: return "ntlm"; case AuthenticationSchemes.Basic: return "basic"; case AuthenticationSchemes.Anonymous: return "anonymous"; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("authScheme", (int) authScheme, typeof(AuthenticationSchemes))); }
internal static HttpProxyCredentialType MapToProxyCredentialType(AuthenticationSchemes authenticationSchemes) { switch (authenticationSchemes) { case AuthenticationSchemes.Digest: return HttpProxyCredentialType.Digest; case AuthenticationSchemes.Negotiate: return HttpProxyCredentialType.Windows; case AuthenticationSchemes.Ntlm: return HttpProxyCredentialType.Ntlm; case AuthenticationSchemes.Basic: return HttpProxyCredentialType.Basic; case AuthenticationSchemes.Anonymous: return HttpProxyCredentialType.None; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); }
/// <summary> /// Constructs a RtspStream for use in a RtspServer /// </summary> /// <param name="name">The name given to the stream on the RtspServer</param> /// <param name="sourceLocation">The rtsp uri to the media</param> /// <param name="credential">The network credential the stream requires</param> /// /// <param name="authType">The AuthenticationSchemes the stream requires</param> public RtspSource(string name, Uri sourceLocation, NetworkCredential credential = null, AuthenticationSchemes authType = AuthenticationSchemes.None, Rtsp.RtspClient.ClientProtocolType?rtpProtocolType = null, int bufferSize = RtspClient.DefaultBufferSize, IEnumerable <Sdp.MediaType> specificMedia = null, TimeSpan?startTime = null, TimeSpan?endTime = null, bool perPacket = false) : base(name, sourceLocation, perPacket) { //Create the listener if we are the top level stream (Parent) if (IsParent) { RtspClient = new RtspClient(m_Source, rtpProtocolType, bufferSize); RtspClient.OnConnect += RtspClient_OnConnect; RtspClient.OnDisconnect += RtspClient_OnDisconnect; RtspClient.OnPlay += RtspClient_OnPlay; RtspClient.OnPause += RtspClient_OnPausing; RtspClient.OnStop += RtspClient_OnStop; } //else it is already assigned via the child if (object.ReferenceEquals(credential, null).Equals(false)) { RtspClient.Credential = SourceCredential = credential; if (false.Equals(authType == AuthenticationSchemes.None)) { RtspClient.AuthenticationScheme = SourceAuthenticationScheme = authType; } } //If only certain media should be setup if (object.ReferenceEquals(specificMedia, null).Equals(false)) { SpecificMediaTypes = specificMedia; } //If there was a start time given if (startTime.HasValue) { MediaStartTime = startTime; } if (endTime.HasValue) { MediaEndTime = endTime; } }
public IHttpListener CreateListener(IEnumerable <string> prefixes, AuthenticationSchemes authenticationSchemes) { return(new HttpListenerAdapter(prefixes, authenticationSchemes)); }
public HttpListenerHost(string uri, IServiceContainer container, AuthenticationSchemes scheme) : this(uri, container, scheme, new HttpListener()) { }
public IHeaderExtensions Authorization(AuthenticationSchemes authenticationScheme, string bearer) => CreateStronglyTypedMemberAccessWrapper().Authorization(authenticationScheme, bearer);
public static SecurityTokenProvider GetUserNameTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters) { SecurityTokenProvider result = null; if (tokenManager != null) { SecurityTokenRequirement usernameRequirement = CreateUserNameTokenRequirement(target, via, transportScheme); usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme; if (channelParameters != null) { usernameRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } result = tokenManager.CreateSecurityTokenProvider(usernameRequirement); } return(result); }
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory()) { // validate setting interactions if (bindingElement.TransferMode == TransferMode.Buffered) { if (bindingElement.MaxReceivedMessageSize > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", SR.MaxReceivedMessageSizeMustBeInIntegerRange)); } if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.MaxBufferSizeMustMatchMaxReceivedMessageSize); } } else { if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize); } } if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) && bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.HttpAuthDoesNotSupportRequestStreaming); } _allowCookies = bindingElement.AllowCookies; if (_allowCookies) { _httpCookieContainerManager = new HttpCookieContainerManager(); } if (!bindingElement.AuthenticationScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme, bindingElement.AuthenticationScheme)); } _authenticationScheme = bindingElement.AuthenticationScheme; _maxBufferSize = bindingElement.MaxBufferSize; _transferMode = bindingElement.TransferMode; _useDefaultWebProxy = bindingElement.UseDefaultWebProxy; _channelCredentials = context.BindingParameters.Find <SecurityCredentialsManager>(); _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context); _webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings); int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(MaxReceivedMessageSize); _bufferPool = new ConnectionBufferPool(webSocketBufferSize); _clientWebSocketFactory = ClientWebSocketFactory.GetFactory(); _webSocketSoapContentType = new Lazy <string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication); }
private AuthenticationResponse(AuthenticationSchemes scheme, NameValueCollection parameters) : base(scheme, parameters) { }
/// <summary> /// Create a new host with provided configuration and an Inversion of Control container. /// </summary> /// <remarks> /// The IoC container is also injected into default activator, so that <see cref="IDreamService"/> instances /// can be resolved from the container. The host configuration is provided to the container as a typed parameter. /// </remarks> /// <param name="config">Host configuration.</param> /// <param name="container">IoC Container.</param> public DreamHost(XDoc config, IContainer container) { if (config == null) { throw new ArgumentNullException("config"); } // read host settings string appDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName); int limit = config["connect-limit"].AsInt ?? 0; int httpPort = config["http-port"].AsInt ?? DEFAULT_PORT; AuthenticationSchemes authenticationScheme = AuthenticationSchemes.Anonymous; string authShemes = config["authentication-shemes"].AsText; if (!String.IsNullOrEmpty(authShemes)) { try { authenticationScheme = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), authShemes, true); } catch (Exception e) { _log.Warn(String.Format("invalid authetication scheme specified :{0}", authShemes), e); } } // get the authtoken for whitelisting dream.in.* query args _dreamInParamAuthtoken = config["dream.in.authtoken"].AsText; if (!string.IsNullOrEmpty(_dreamInParamAuthtoken)) { _log.Debug("Host is configured in dream.in param authorizing mode"); } // read ip-addresses var addresses = new List <string>(); foreach (XDoc ip in config["host|ip"]) { addresses.Add(ip.AsText); } if (addresses.Count == 0) { // if no addresses were supplied listen to all addresses.Add("*:" + httpPort); } // use default servername XUri publicUri = config["uri.public"].AsUri; if (publicUri == null) { // backwards compatibility publicUri = config["server-name"].AsUri; if (publicUri == null) { foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName())) { if (addr.AddressFamily == AddressFamily.InterNetwork) { XUri.TryParse("http://" + addr, out publicUri); } } if (publicUri == null) { // failed to get an address out of dns, fall back to localhost XUri.TryParse("http://localhost", out publicUri); } } publicUri = publicUri.AtPath(config["server-path"].AsText ?? config["path-prefix"].AsText ?? string.Empty); } // create environment and initialize it _env = new DreamHostService(container); try { // initialize environment string apikey = config["apikey"].AsText ?? StringUtil.CreateAlphaNumericKey(32); XDoc serviceConfig = new XDoc("config"); var storageType = config["storage/@type"].AsText ?? "local"; if ("s3".EqualsInvariant(storageType)) { serviceConfig.Add(config["storage"]); } else { serviceConfig.Elem("storage-dir", config["storage-dir"].AsText ?? config["service-dir"].AsText ?? appDirectory); } serviceConfig.Elem("apikey", apikey); serviceConfig.Elem("uri.public", publicUri); serviceConfig.Elem("connect-limit", limit); serviceConfig.Elem("guid", config["guid"].AsText); serviceConfig.AddAll(config["components"]); var memorize = config["memorize-aliases"]; if (!memorize.IsEmpty) { serviceConfig.Elem("memorize-aliases", memorize.AsBool); } _env.Initialize(serviceConfig); // initialize host plug _host = _env.Self.With("apikey", apikey); // load assemblies in 'services' folder string servicesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "services"); if (Directory.Exists(servicesFolder)) { // Note (arnec): Deprecated, but the suggested alternative really doesn't apply since we don't want to // load services into a separate appdomain. #pragma warning disable 618,612 AppDomain.CurrentDomain.AppendPrivatePath("services"); #pragma warning restore 618,612 foreach (string file in Directory.GetFiles(servicesFolder, "*.dll")) { // register assembly blueprints DreamMessage response = _host.At("load").With("name", Path.GetFileNameWithoutExtension(file)).Post(new Result <DreamMessage>(TimeSpan.MaxValue)).Wait(); if (!response.IsSuccessful) { _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file); } } } // add acccess-points AddListener(new XUri(String.Format("http://{0}:{1}/", "localhost", httpPort)), authenticationScheme); // check if user prescribed a set of IP addresses to use if (addresses != null) { // listen to custom addresses (don't use the supplied port info, we expect that to be part of the address) foreach (string address in addresses) { if (!StringUtil.EqualsInvariantIgnoreCase(address, "localhost")) { AddListener(new XUri(String.Format("http://{0}/", address)), authenticationScheme); } } } else { // add listeners for all known IP addresses foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName())) { XUri uri = MakeUri(address, httpPort); if (uri != null) { AddListener(uri, authenticationScheme); try { foreach (string alias in Dns.GetHostEntry(address).Aliases) { AddListener(new XUri(String.Format("http://{0}:{1}/", alias, httpPort)), authenticationScheme); } } catch { } } } } } catch (Exception e) { if ((e is HttpListenerException) && e.Message.EqualsInvariant("Access is denied")) { _log.ErrorExceptionMethodCall(e, "ctor", "insufficient privileges to create HttpListener, make sure the application runs with Administrator rights"); } else { _log.ErrorExceptionMethodCall(e, "ctor"); } try { _env.Deinitialize(); } catch { } throw; } }
internal static IPrincipal CreateUser( string response, AuthenticationSchemes scheme, string realm, string method, Func <IIdentity, NetworkCredential> credentialsFinder ) { if (response == null || response.Length == 0) { return(null); } if (scheme == AuthenticationSchemes.Digest) { if (realm == null || realm.Length == 0) { return(null); } if (method == null || method.Length == 0) { return(null); } } else { if (scheme != AuthenticationSchemes.Basic) { return(null); } } if (credentialsFinder == null) { return(null); } var compType = StringComparison.OrdinalIgnoreCase; if (response.IndexOf(scheme.ToString(), compType) != 0) { return(null); } var res = AuthenticationResponse.Parse(response); if (res == null) { return(null); } var id = res.ToIdentity(); if (id == null) { return(null); } NetworkCredential cred = null; try { cred = credentialsFinder(id); } catch { } if (cred == null) { return(null); } if (scheme == AuthenticationSchemes.Basic) { var basicId = (HttpBasicIdentity)id; return(basicId.Password == cred.Password ? new GenericPrincipal(id, cred.Roles) : null); } var digestId = (HttpDigestIdentity)id; return(digestId.IsValid(cred.Password, realm, method, null) ? new GenericPrincipal(id, cred.Roles) : null); }
protected AuthenticationBase(AuthenticationSchemes scheme, NameValueCollection parameters) { _scheme = scheme; Parameters = parameters; }
internal AuthenticationManager(WebListener listener) { _server = listener; _authSchemes = AuthenticationSchemes.AllowAnonymous; }
protected abstract void ConfigureBinding(Binding binding, string uriScheme, AuthenticationSchemes supportedAuthenticationSchemes, bool hostedEnvironment);
public async Task AuthProxy__ValidCreds_ProxySendsRequestToServer( AuthenticationSchemes proxyAuthScheme, bool secureServer, bool proxyClosesConnectionAfterFirst407Response) { if (PlatformDetection.IsFedora && IsCurlHandler) { // CurlHandler seems unstable on Fedora26 and returns error // "System.Net.Http.CurlException : Failure when receiving data from the peer". return; } if (PlatformDetection.IsWindowsNanoServer && IsWinHttpHandler && proxyAuthScheme == AuthenticationSchemes.Digest) { // WinHTTP doesn't support Digest very well and is disabled on Nano. return; } if (PlatformDetection.IsFullFramework && (proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm)) { // Skip due to bug in .NET Framework with Windows auth and proxy tunneling. return; } if (!PlatformDetection.IsWindows && (proxyAuthScheme == AuthenticationSchemes.Negotiate || proxyAuthScheme == AuthenticationSchemes.Ntlm)) { // CI machines don't have GSSAPI module installed and will fail with error from // System.Net.Security.NegotiateStreamPal.AcquireCredentialsHandle(): // "GSSAPI operation failed with error - An invalid status code was supplied // Configuration file does not specify default realm)." return; } if (IsCurlHandler && proxyAuthScheme != AuthenticationSchemes.Basic) { // Issue #27870 curl HttpHandler can only do basic auth to proxy. return; } Uri serverUri = secureServer ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer; var options = new LoopbackProxyServer.Options { AuthenticationSchemes = proxyAuthScheme, ConnectionCloseAfter407 = proxyClosesConnectionAfterFirst407Response }; using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options)) { using (HttpClientHandler handler = CreateHttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new WebProxy(proxyServer.Uri); handler.Proxy.Credentials = new NetworkCredential("username", "password"); using (HttpResponseMessage response = await client.GetAsync(serverUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } } }
public static SimpleServer Create(string url, Action <HttpListenerContext> handler, AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous) { var listener = new HttpListener { Prefixes = { url }, AuthenticationSchemes = authenticationSchemes }; var server = new SimpleServer(listener, handler); server.Start(); return(server); }
internal virtual bool GetSupportsClientWindowsIdentityImpl(AuthenticationSchemes effectiveAuthenticationSchemes) { return(effectiveAuthenticationSchemes != AuthenticationSchemes.None && effectiveAuthenticationSchemes.IsNotSet(AuthenticationSchemes.Anonymous)); }
public static void BasicHttpBinding( TestContext context, MetadataSet doc, BasicHttpSecurityMode security, WSMessageEncoding encoding, HttpClientCredentialType clientCred, AuthenticationSchemes authScheme, TestLabel label) { label.EnterScope("basicHttpBinding"); var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata; label.EnterScope("wsdl"); label.EnterScope("bindings"); Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get()); var binding = sd.Bindings [0]; Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get()); Assert.That(binding.Extensions, Is.Not.Null, label.Get()); bool hasPolicyXml; switch (security) { case BasicHttpSecurityMode.None: hasPolicyXml = encoding == WSMessageEncoding.Mtom; break; case BasicHttpSecurityMode.Message: case BasicHttpSecurityMode.Transport: case BasicHttpSecurityMode.TransportWithMessageCredential: if (encoding == WSMessageEncoding.Mtom) { throw new InvalidOperationException(); } hasPolicyXml = true; break; case BasicHttpSecurityMode.TransportCredentialOnly: hasPolicyXml = true; break; default: throw new InvalidOperationException(); } label.LeaveScope(); WS.SoapBinding soap = null; XmlElement xml = null; foreach (var ext in binding.Extensions) { if (ext is WS.SoapBinding) { soap = (WS.SoapBinding)ext; } else if (ext is XmlElement) { xml = (XmlElement)ext; } } CheckSoapBinding(soap, WS.SoapBinding.HttpTransport, label); label.LeaveScope(); label.EnterScope("policy-xml"); if (!hasPolicyXml) { Assert.That(xml, Is.Null, label.Get()); } else if (context.CheckPolicyXml) { Assert.That(xml, Is.Not.Null, label.Get()); Assert.That(xml.NamespaceURI, Is.EqualTo(WspNamespace), label.Get()); Assert.That(xml.LocalName, Is.EqualTo("PolicyReference") | Is.EqualTo("Policy"), label.Get()); } label.LeaveScope(); var importer = new WsdlImporter(doc); label.EnterScope("bindings"); var bindings = importer.ImportAllBindings(); CheckImportErrors(importer, label); Assert.That(bindings, Is.Not.Null, label.Get()); Assert.That(bindings.Count, Is.EqualTo(1), label.Get()); string scheme; if ((security == BasicHttpSecurityMode.Transport) || (security == BasicHttpSecurityMode.TransportWithMessageCredential)) { scheme = "https"; } else { scheme = "http"; } CheckBasicHttpBinding( bindings [0], scheme, security, encoding, clientCred, authScheme, label); label.LeaveScope(); label.EnterScope("endpoints"); var endpoints = importer.ImportAllEndpoints(); CheckImportErrors(importer, label); Assert.That(endpoints, Is.Not.Null, label.Get()); Assert.That(endpoints.Count, Is.EqualTo(1), label.Get()); CheckEndpoint(endpoints [0], MetadataSamples.HttpUri, label); label.LeaveScope(); label.LeaveScope(); }
public Builder AuthScheme(AuthenticationSchemes scheme) { m_authScheme = scheme; return(this); }
public static void BasicHttpsBinding( TestContext context, MetadataSet doc, BasicHttpSecurityMode security, WSMessageEncoding encoding, HttpClientCredentialType clientCred, AuthenticationSchemes authScheme, TestLabel label) { label.EnterScope("basicHttpsBinding"); var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata; label.EnterScope("wsdl"); Assert.That(sd.Extensions, Is.Not.Null, label.Get()); Assert.That(sd.Extensions.Count, Is.EqualTo(1), label.Get()); Assert.That(sd.Extensions [0], Is.InstanceOfType(typeof(XmlElement)), label.Get()); label.EnterScope("extensions"); var extension = (XmlElement)sd.Extensions [0]; Assert.That(extension.NamespaceURI, Is.EqualTo(WspNamespace), label.Get()); Assert.That(extension.LocalName, Is.EqualTo("Policy"), label.Get()); label.LeaveScope(); label.EnterScope("bindings"); Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get()); var binding = sd.Bindings [0]; Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get()); Assert.That(binding.Extensions, Is.Not.Null, label.Get()); label.LeaveScope(); WS.SoapBinding soap = null; XmlElement xml = null; foreach (var ext in binding.Extensions) { if (ext is WS.SoapBinding) { soap = (WS.SoapBinding)ext; } else if (ext is XmlElement) { xml = (XmlElement)ext; } } CheckSoapBinding(soap, WS.SoapBinding.HttpTransport, label); if (context.CheckPolicyXml) { label.EnterScope("policy-xml"); Assert.That(xml, Is.Not.Null, label.Get()); Assert.That(xml.NamespaceURI, Is.EqualTo(WspNamespace), label.Get()); Assert.That(xml.LocalName, Is.EqualTo("PolicyReference") | Is.EqualTo("Policy"), label.Get()); label.LeaveScope(); } label.LeaveScope(); // wsdl var importer = new WsdlImporter(doc); label.EnterScope("bindings"); var bindings = importer.ImportAllBindings(); CheckImportErrors(importer, label); Assert.That(bindings, Is.Not.Null, label.Get()); Assert.That(bindings.Count, Is.EqualTo(1), label.Get()); CheckBasicHttpBinding( bindings [0], "https", security, encoding, clientCred, authScheme, label); label.LeaveScope(); label.EnterScope("endpoints"); var endpoints = importer.ImportAllEndpoints(); CheckImportErrors(importer, label); Assert.That(endpoints, Is.Not.Null, label.Get()); Assert.That(endpoints.Count, Is.EqualTo(1), label.Get()); CheckEndpoint(endpoints [0], MetadataSamples.HttpsUri, label); label.LeaveScope(); label.LeaveScope(); }
public static bool IsSet(this AuthenticationSchemes thisPtr, AuthenticationSchemes authenticationSchemes) { return((thisPtr & authenticationSchemes) == authenticationSchemes); }
public static void CheckBasicHttpBinding( Binding binding, string scheme, BasicHttpSecurityMode security, WSMessageEncoding encoding, HttpClientCredentialType clientCred, AuthenticationSchemes authScheme, TestLabel label) { label.EnterScope("http"); if (security == BasicHttpSecurityMode.Message) { Assert.That(binding, Is.InstanceOfType(typeof(CustomBinding)), label.Get()); } else { Assert.That(binding, Is.InstanceOfType(typeof(BasicHttpBinding)), label.Get()); var basicHttp = (BasicHttpBinding)binding; Assert.That(basicHttp.EnvelopeVersion, Is.EqualTo(EnvelopeVersion.Soap11), label.Get()); Assert.That(basicHttp.MessageVersion, Is.EqualTo(MessageVersion.Soap11), label.Get()); Assert.That(basicHttp.Scheme, Is.EqualTo(scheme), label.Get()); Assert.That(basicHttp.TransferMode, Is.EqualTo(TransferMode.Buffered), label.Get()); Assert.That(basicHttp.MessageEncoding, Is.EqualTo(encoding), label.Get()); Assert.That(basicHttp.Security, Is.Not.Null, label.Get()); Assert.That(basicHttp.Security.Mode, Is.EqualTo(security), label.Get()); Assert.That(basicHttp.Security.Transport.ClientCredentialType, Is.EqualTo(clientCred), label.Get()); Assert.That(basicHttp.Security.Message.AlgorithmSuite, Is.EqualTo(SecurityAlgorithmSuite.Basic256), label.Get()); } label.EnterScope("elements"); var elements = binding.CreateBindingElements(); Assert.That(elements, Is.Not.Null, label.Get()); if ((security == BasicHttpSecurityMode.Message) || (security == BasicHttpSecurityMode.TransportWithMessageCredential)) { Assert.That(elements.Count, Is.EqualTo(3), label.Get()); } else { Assert.That(elements.Count, Is.EqualTo(2), label.Get()); } TextMessageEncodingBindingElement textElement = null; TransportSecurityBindingElement securityElement = null; HttpTransportBindingElement transportElement = null; AsymmetricSecurityBindingElement asymmSecurityElement = null; MtomMessageEncodingBindingElement mtomElement = null; foreach (var element in elements) { if (element is TextMessageEncodingBindingElement) { textElement = (TextMessageEncodingBindingElement)element; } else if (element is HttpTransportBindingElement) { transportElement = (HttpTransportBindingElement)element; } else if (element is TransportSecurityBindingElement) { securityElement = (TransportSecurityBindingElement)element; } else if (element is AsymmetricSecurityBindingElement) { asymmSecurityElement = (AsymmetricSecurityBindingElement)element; } else if (element is MtomMessageEncodingBindingElement) { mtomElement = (MtomMessageEncodingBindingElement)element; } else { Assert.Fail(string.Format( "Unknown element: {0}", element.GetType()), label.Get()); } } label.EnterScope("text"); if (encoding == WSMessageEncoding.Text) { Assert.That(textElement, Is.Not.Null, label.Get()); Assert.That(textElement.WriteEncoding, Is.InstanceOfType(typeof(UTF8Encoding)), label.Get()); } else { Assert.That(textElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("mtom"); if (encoding == WSMessageEncoding.Mtom) { Assert.That(mtomElement, Is.Not.Null, label.Get()); } else { Assert.That(mtomElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("security"); if (security == BasicHttpSecurityMode.TransportWithMessageCredential) { Assert.That(securityElement, Is.Not.Null, label.Get()); Assert.That(securityElement.SecurityHeaderLayout, Is.EqualTo(SecurityHeaderLayout.Lax), label.Get()); } else { Assert.That(securityElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("asymmetric"); if (security == BasicHttpSecurityMode.Message) { Assert.That(asymmSecurityElement, Is.Not.Null, label.Get()); } else { Assert.That(asymmSecurityElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("transport"); Assert.That(transportElement, Is.Not.Null, label.Get()); Assert.That(transportElement.Realm, Is.Empty, label.Get()); Assert.That(transportElement.Scheme, Is.EqualTo(scheme), label.Get()); Assert.That(transportElement.TransferMode, Is.EqualTo(TransferMode.Buffered), label.Get()); label.EnterScope("auth"); Assert.That(transportElement.AuthenticationScheme, Is.EqualTo(authScheme), label.Get()); label.LeaveScope(); // auth label.LeaveScope(); // transport label.LeaveScope(); // elements label.LeaveScope(); // http }
public static SspiSecurityTokenProvider GetSspiTokenProvider( SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters) { if (tokenManager != null) { SecurityTokenRequirement sspiRequirement = CreateSspiTokenRequirement(target, via, transportScheme); sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme; if (channelParameters != null) { sspiRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters; } SspiSecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(sspiRequirement) as SspiSecurityTokenProvider; return(tokenProvider); } return(null); }
public RtspSource(string name, string sourceLocation, NetworkCredential credential = null, AuthenticationSchemes authType = AuthenticationSchemes.None, Rtsp.RtspClient.ClientProtocolType?rtpProtocolType = null, int bufferSize = RtspClient.DefaultBufferSize, Sdp.MediaType?specificMedia = null, TimeSpan?startTime = null, TimeSpan?endTime = null, bool perPacket = false) : this(name, new Uri(sourceLocation), credential, authType, rtpProtocolType, bufferSize, specificMedia.HasValue ? Common.Extensions.Linq.LinqExtensions.Yield(specificMedia.Value) : null, startTime, endTime, perPacket) { //Check for a null Credential and UserInfo in the Location given. if (credential == null && !string.IsNullOrWhiteSpace(m_Source.UserInfo)) { RtspClient.Credential = Media.Common.Extensions.Uri.UriExtensions.ParseUserInfo(m_Source); //Remove the user info from the location RtspClient.CurrentLocation = new Uri(RtspClient.CurrentLocation.AbsoluteUri.Replace(RtspClient.CurrentLocation.UserInfo + (char)Common.ASCII.AtSign, string.Empty).Replace(RtspClient.CurrentLocation.UserInfo, string.Empty)); } }
public IHeaderExtensions Authorization(AuthenticationSchemes authenticationScheme, string username, string password) => CreateStronglyTypedMemberAccessWrapper().Authorization(authenticationScheme, username, password);
public async Task BasicAuthentication_ValidUsernameAndPassword_Success(AuthenticationSchemes authScheme) { _listener.AuthenticationSchemes = authScheme; await ValidateValidUser(); }
public static SimpleServer Create(string url, Action <HttpListenerContext> handler = null, AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous) { return(new SimpleServer(url, handler, authenticationSchemes)); }
public RestaurantSearchHttpClient(string requestUriFormat, string tenant, string language, AuthenticationSchemes authenticationSchemes, string authorizationToken, string host, HttpClient httpClient) { _requestUriFormat = requestUriFormat; _tenant = tenant; _language = language; _authenticationSchemes = authenticationSchemes; _authorizationToken = authorizationToken; _host = host; _httpClient = httpClient; }
public static void AddMexEndpoint(ServiceHostBase serviceHost, Uri baseAddress, AuthenticationSchemes schemes) { HttpTransportBindingElement httpTransport = baseAddress.Scheme == Uri.UriSchemeHttp ? new HttpTransportBindingElement() : new HttpsTransportBindingElement(); httpTransport.AuthenticationScheme = schemes; Binding binding = new CustomBinding(new BindingElement[] { httpTransport }); serviceHost.AddServiceEndpoint("IMetadataExchange", binding, baseAddress); }
public static HttpClientCredentialType ClientCredentialTypeFromAuthenticationScheme(AuthenticationSchemes oneAuthScheme) { const HttpClientCredentialType none = HttpClientCredentialType.None; switch (oneAuthScheme) { case AuthenticationSchemes.Digest: return(HttpClientCredentialType.Digest); case AuthenticationSchemes.Negotiate: case AuthenticationSchemes.IntegratedWindowsAuthentication: return(HttpClientCredentialType.Windows); case (AuthenticationSchemes.Negotiate | AuthenticationSchemes.Digest): case (AuthenticationSchemes.Ntlm | AuthenticationSchemes.Digest): case (AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Digest): return(none); case AuthenticationSchemes.Ntlm: return(HttpClientCredentialType.Ntlm); case AuthenticationSchemes.Basic: return(HttpClientCredentialType.Basic); case AuthenticationSchemes.Anonymous: return(HttpClientCredentialType.None); } return(none); }
internal static IPrincipal CreateUser( string response, AuthenticationSchemes scheme, string realm, string method, Func <IIdentity, NetworkCredential> credentialsFinder ) { if (response == null || response.Length == 0) { return(null); } if (credentialsFinder == null) { return(null); } if (!(scheme == AuthenticationSchemes.Basic || scheme == AuthenticationSchemes.Digest)) { return(null); } if (scheme == AuthenticationSchemes.Digest) { if (realm == null || realm.Length == 0) { return(null); } if (method == null || method.Length == 0) { return(null); } } if (!response.StartsWith(scheme.ToString(), StringComparison.OrdinalIgnoreCase)) { return(null); } var res = AuthenticationResponse.Parse(response); if (res == null) { return(null); } var id = res.ToIdentity(); if (id == null) { return(null); } NetworkCredential cred = null; try { cred = credentialsFinder(id); } catch { } if (cred == null) { return(null); } if (scheme == AuthenticationSchemes.Basic && ((HttpBasicIdentity)id).Password != cred.Password ) { return(null); } if (scheme == AuthenticationSchemes.Digest && !((HttpDigestIdentity)id).IsValid(cred.Password, realm, method, null) ) { return(null); } return(new GenericPrincipal(id, cred.Roles)); }
/// <summary> /// Can only call before opening the host /// </summary> public static void EnableMetadataExchange(ServiceHostBase serviceHost, Uri baseAddress, AuthenticationSchemes schemes, bool enableHttpGet) { if (serviceHost.State == CommunicationState.Opened) { throw new InvalidOperationException("Host is already opened"); } var metadataBehavior = serviceHost.Description.Behaviors.Find <ServiceMetadataBehavior>(); var address = new Uri(baseAddress, "/" + baseAddress.GetComponents(UriComponents.Path, UriFormat.Unescaped) + "/mex"); if (metadataBehavior == null) { metadataBehavior = new ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(metadataBehavior); if (object.ReferenceEquals(address.Scheme, Uri.UriSchemeHttp)) { metadataBehavior.HttpGetEnabled = enableHttpGet; metadataBehavior.HttpGetUrl = address; } else { metadataBehavior.HttpsGetEnabled = enableHttpGet; metadataBehavior.HttpsGetUrl = address; } } AddMexEndpoint(serviceHost, address, schemes); }