public FileTransferManagerFactory( SerializationAssistantFactory serializationAssistantFactory, IChannelProvider channelProvider) { _serializationAssistantFactory = serializationAssistantFactory; _channelProvider = channelProvider; }
public void Setup() { manager = new ServerUserManager(); permissions = new MockPermissionsProvider(); channels = new LobbyChannelProvider(); MockServerContext mcontext; context = mcontext = new MockServerContext { ChannelsProvider = channels, PermissionsProvider = permissions, UserManager = new ServerUserManager (), Settings = new ServerSettings { Name = "Test Server" } }; mcontext.Users = new ServerUserHandler (context, manager); mcontext.Channels = handler = new ServerChannelHandler (context); user = UserInfoTests.GetTestUser (1, 1, false); provider = new MockConnectionProvider (GablarskiProtocol.Instance); mcontext.AddConnectionProvider (provider); mcontext.Start(); var connections = provider.GetConnections (GablarskiProtocol.Instance); client = new ConnectionBuffer (connections.Item1); server = connections.Item2; manager.Connect (server); manager.Join (server, user); }
public void Release(IChannelProvider channelProvider) { var disposable = channelProvider as IDisposable; if (disposable != null) { disposable.Dispose(); } }
/// <summary> /// Initializes a new <c>GablarskiServer</c> instance. /// </summary> /// <param name="settings">The settings for the server, providing name, description, etc.</param> /// <param name="authProvider">The user authentication provider for the server to use.</param> /// <param name="permissionProvider">The user permissions provider for the server to use.</param> /// <param name="channelProvider">The channel provider for the server to use.</param> public GablarskiServer(ServerSettings settings, IUserProvider authProvider, IPermissionsProvider permissionProvider, IChannelProvider channelProvider) : this(settings) { this.authProvider = authProvider; this.permissionProvider = permissionProvider; this.permissionProvider.PermissionsChanged += OnPermissionsChanged; this.channelProvider = channelProvider; SetupHandlers(); }
public ServerProviders(IChannelProvider channels, IUserProvider auth, IPermissionsProvider permissions, IEnumerable<IConnectionProvider> cproviders) : this(cproviders) { if (channels == null) throw new ArgumentNullException ("channels"); if (auth == null) throw new ArgumentNullException ("auth"); if (permissions == null) throw new ArgumentNullException ("permissions"); Channels = channels; Users = auth; Permissions = permissions; }
public KafkaMessageSender(IRoutingTopology routingTopology, IChannelProvider channelProvider, BehaviorContext context) { this.routingTopology = routingTopology; this.channelProvider = channelProvider; this.context = context; }
public void ServerTestCleanup() { this.server.Stop(); this.server = null; this.provider = null; this.users = null; this.channels = null; this.permissions = null; this.settings = null; }
private protected SlotCursor(IChannelProvider provider) { Contracts.AssertValue(provider); Ch = provider.Start("Slot Cursor"); }
public Cursor(IChannelProvider provider, SingleRowLoopDataView <TRow> dataView, Func <int, bool> predicate) : base(provider, dataView, predicate) { _currentRow = dataView._current; }
/// <summary> /// Validate the incoming Auth Header as a token sent from a Bot Framework Channel Service. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="channelProvider">The user defined configuration for the channel.</param> /// <param name="serviceUrl">The service url from the request.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <returns>ClaimsIdentity.</returns> #pragma warning disable UseAsyncSuffix // Use Async suffix (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string serviceUrl, HttpClient httpClient, string channelId) #pragma warning restore UseAsyncSuffix // Use Async suffix { return(await AuthenticateChannelToken(authHeader, credentials, channelProvider, serviceUrl, httpClient, channelId, new AuthenticationConfiguration()).ConfigureAwait(false)); }
private void WriteWorker(Stream stream, BlockingCollection <Block> toWrite, ColumnCodec[] activeColumns, ISchema sourceSchema, int rowsPerBlock, IChannelProvider cp, ExceptionMarshaller exMarshaller) { _host.AssertValue(exMarshaller); try { _host.AssertValue(cp); cp.AssertValue(stream); cp.AssertValue(toWrite); cp.AssertValue(activeColumns); cp.AssertValue(sourceSchema); cp.Assert(rowsPerBlock > 0); using (IChannel ch = cp.Start("Write")) { var blockLookups = new List <BlockLookup> [activeColumns.Length]; for (int c = 0; c < blockLookups.Length; ++c) { blockLookups[c] = new List <BlockLookup>(); } var deadLookups = new int[activeColumns.Length]; // Reserve space for the header at the start. This will be filled // in with valid values once writing has completed. ch.CheckIO(stream.Position == 0); stream.Write(new byte[Header.HeaderSize], 0, Header.HeaderSize); ch.CheckIO(stream.Position == Header.HeaderSize); long expectedPosition = stream.Position; BlockLookup deadLookup = new BlockLookup(); foreach (Block block in toWrite.GetConsumingEnumerable(exMarshaller.Token)) { ch.CheckIO(stream.Position == expectedPosition); MemoryStream compressed = block.BlockData; ArraySegment <byte> buffer; bool tmp = compressed.TryGetBuffer(out buffer); ch.Assert(tmp); stream.Write(buffer.Array, buffer.Offset, buffer.Count); BlockLookup currLookup = new BlockLookup(expectedPosition, (int)compressed.Length, block.UncompressedLength); expectedPosition += compressed.Length; _memPool.Return(ref compressed); ch.CheckIO(stream.Position == expectedPosition); // Record the position. We have this "lookups" list per column. Yet, it may be that sometimes // the writer receives things out of order. // REVIEW: The format and the rest of the pipeline supposedly supports a long number // of blocks, but the writing scheme does not yet support that. int blockIndex = (int)block.BlockIndex; var lookups = blockLookups[block.ColumnIndex]; if (lookups.Count == block.BlockIndex) // Received in order. { lookups.Add(currLookup); } else if (lookups.Count < block.BlockIndex) // Received a block a little bit early. { // Add a bunch of dead filler lookups, until these late blocks come in. int deadToAdd = (int)block.BlockIndex - lookups.Count; for (int i = 0; i < deadToAdd; ++i) { lookups.Add(deadLookup); } deadLookups[block.ColumnIndex] += deadToAdd; ch.Assert(lookups.Count == block.BlockIndex); lookups.Add(currLookup); } else // Received a block a little bit late. { // This should be a dead block unless the compressors are buggy and somehow // yielding duplicate blocks or something. ch.Assert(lookups[blockIndex].BlockOffset == 0); deadLookups[block.ColumnIndex]--; lookups[blockIndex] = currLookup; } } // We have finished writing all blocks. We will now write the block lookup tables (so we can // find the blocks), the slot names (for any columns that have them), the column table of // contents (so we know how to decode the blocks, and where the lookups and names are), // and the header (so we know dataview wide information and where to find the table of // contents) in that order. long[] lookupOffsets = new long[blockLookups.Length]; using (BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) { // Write the block lookup directories. These are referenced from the table of contents, // so that someone knows where to look for some block data. for (int c = 0; c < blockLookups.Length; ++c) { ch.Assert(deadLookups[c] == 0); // The block lookup directories are written uncompressed and in fixed length // to enable rapid seeking. lookupOffsets[c] = stream.Position; foreach (BlockLookup lookup in blockLookups[c]) { // *** Lookup table entry format *** // long: Offset to the start of a block // int: Byte length of block as written // int: Byte length of block when uncompressed ch.Assert(lookup.BlockOffset > 0); writer.Write(lookup.BlockOffset); writer.Write(lookup.BlockLength); writer.Write(lookup.DecompressedBlockLength); } ch.CheckIO(stream.Position == lookupOffsets[c] + (16 * blockLookups[c].Count), "unexpected offsets after block lookup table write"); } // Write the metadata for each column. long[] metadataTocOffsets = new long[activeColumns.Length]; for (int c = 0; c < activeColumns.Length; ++c) { metadataTocOffsets[c] = WriteMetadata(writer, sourceSchema, activeColumns[c].SourceIndex, ch); } // Write the table of contents. long tocOffset = stream.Position; { int c = 0; expectedPosition = stream.Position; foreach (var active in activeColumns) { // *** Column TOC entry format *** // string: column name // codec (as interpretable by CodecFactory.TryGetCodec): column block codec // CompressionKind(byte): block compression strategy // LEB128 int: Rows per block // long: Offset to the start of the lookup table // long: Offset to the start of the metadata TOC entries, or 0 if this has no metadata string name = sourceSchema.GetColumnName(active.SourceIndex); writer.Write(name); int nameLen = Encoding.UTF8.GetByteCount(name); expectedPosition += Utils.Leb128IntLength((uint)nameLen) + nameLen; ch.CheckIO(stream.Position == expectedPosition, "unexpected offsets after table of contents name"); expectedPosition += _factory.WriteCodec(stream, active.Codec); ch.CheckIO(stream.Position == expectedPosition, "unexpected offsets after table of contents type description"); writer.Write((byte)_compression); expectedPosition++; // REVIEW: Right now the number of rows per block is fixed, so we // write the same value each time. In some future state, it may be that this // is relaxed, with possibly some tradeoffs (e.g., inability to randomly seek). writer.WriteLeb128Int((ulong)rowsPerBlock); expectedPosition += Utils.Leb128IntLength((uint)rowsPerBlock); // Offset of the lookup table. writer.Write(lookupOffsets[c]); expectedPosition += sizeof(long); // Offset of the metadata table of contents. writer.Write(metadataTocOffsets[c]); expectedPosition += sizeof(long); ch.CheckIO(stream.Position == expectedPosition, "unexpected offsets after table of contents"); c++; } } // Write the tail signature. long tailOffset = stream.Position; writer.Write(Header.TailSignatureValue); // Now move back to the beginning of the stream, and write out the now completed header. Header header = new Header() { Signature = Header.SignatureValue, Version = Header.WriterVersion, CompatibleVersion = Header.CanBeReadByVersion, TableOfContentsOffset = tocOffset, TailOffset = tailOffset, RowCount = _rowCount, ColumnCount = activeColumns.Length }; byte[] headerBytes = new byte[Header.HeaderSize]; unsafe { Marshal.Copy(new IntPtr(&header), headerBytes, 0, Marshal.SizeOf(typeof(Header))); } writer.Seek(0, SeekOrigin.Begin); writer.Write(headerBytes); } ch.Done(); } } catch (Exception ex) { exMarshaller.Set("writing", ex); } }
private protected static bool WarnOnOldNormalizer(ModelLoadContext ctx, Type typePredictor, IChannelProvider provider) { Contracts.CheckValue(provider, nameof(provider)); provider.CheckValue(ctx, nameof(ctx)); provider.CheckValue(typePredictor, nameof(typePredictor)); if (!ctx.ContainsModel(@"Normalizer")) { return(false); } using (var ch = provider.Start("WarnNormalizer")) { ch.Warning(NormalizerWarningFormat, typePredictor, Environment.NewLine); } return(true); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceClient"/> class. /// </summary> /// <param name="channelProvider">The <see cref="IChannelProvider"/> that is responsible /// for creating a channel that is used to invoke the target service.</param> public ServiceClient(IChannelProvider channelProvider) { this.channelProvider = channelProvider; }
public BotFrameworkHttpAdapterWithHandoff(ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILogger <BotFrameworkHttpAdapter> logger = null) : base(credentialProvider, channelProvider, logger) { }
public BotFrameworkHttpAdapterWithHandoff(ICredentialProvider credentialProvider, IChannelProvider channelProvider, HttpClient httpClient, ILogger <BotFrameworkHttpAdapter> logger) : base(credentialProvider, channelProvider, httpClient, logger) { }
/// <summary> /// Validate the incoming Auth Header as a token sent from the Bot Framework Emulator. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]"</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="channelProvider">The channelService value that distinguishes public Azure from US Government Azure.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <returns> /// A valid ClaimsIdentity. /// </returns> /// <remarks> /// A token issued by the Bot Framework will FAIL this check. Only Emulator tokens will pass. /// </remarks> public static async Task <ClaimsIdentity> AuthenticateEmulatorToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, HttpClient httpClient, string channelId) { var openIdMetadataUrl = (channelProvider != null && channelProvider.IsGovernment()) ? GovernmentAuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl : AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl; var tokenExtractor = new JwtTokenExtractor( httpClient, ToBotFromEmulatorTokenValidationParameters, openIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId); if (identity == null) { // No valid identity. Not Authorized. throw new UnauthorizedAccessException("Invalid Identity"); } if (!identity.IsAuthenticated) { // The token is in some way invalid. Not Authorized. throw new UnauthorizedAccessException("Token Not Authenticated"); } // Now check that the AppID in the claimset matches // what we're looking for. Note that in a multi-tenant bot, this value // comes from developer code that may be reaching out to a service, hence the // Async validation. Claim versionClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.VersionClaim); if (versionClaim == null) { throw new UnauthorizedAccessException("'ver' claim is required on Emulator Tokens."); } string tokenVersion = versionClaim.Value; string appID = string.Empty; // The Emulator, depending on Version, sends the AppId via either the // appid claim (Version 1) or the Authorized Party claim (Version 2). if (string.IsNullOrWhiteSpace(tokenVersion) || tokenVersion == "1.0") { // either no Version or a version of "1.0" means we should look for // the claim in the "appid" claim. Claim appIdClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AppIdClaim); if (appIdClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'appid' claim is required on Emulator Token version '1.0'."); } appID = appIdClaim.Value; } else if (tokenVersion == "2.0") { // Emulator, "2.0" puts the AppId in the "azp" claim. Claim appZClaim = identity.Claims.FirstOrDefault(c => c.Type == AuthenticationConstants.AuthorizedParty); if (appZClaim == null) { // No claim around AppID. Not Authorized. throw new UnauthorizedAccessException("'azp' claim is required on Emulator Token version '2.0'."); } appID = appZClaim.Value; } else { // Unknown Version. Not Authorized. throw new UnauthorizedAccessException($"Unknown Emulator Token version '{tokenVersion}'."); } if (!await credentials.IsValidAppIdAsync(appID)) { throw new UnauthorizedAccessException($"Invalid AppId passed on token: {appID}"); } return(identity); }
public HttpResponseMessage Push(PushParams pushParams) { try { if (pushParams == null || pushParams.Targets == null || pushParams.Targets.Count == 0 || pushParams.Message == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "推送参数为空。")); } //按apptype的类型分组 Dictionary <int, List <PushTarget> > dicAppType = (from item in pushParams.Targets group item by item.AppType into gtype orderby gtype.Key select new { Key = gtype.Key, Value = gtype.ToList() }).ToDictionary(a => a.Key, a => a.Value); foreach (int type in dicAppType.Keys) { AppPushChannelInfo channelInfo = null; if (EnvProvider.Default.DicAppPushInfo.TryGetValue((AppType)type, out channelInfo)) { if (channelInfo == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("App类型:{0}对应的推送配置信息为空。", type.ToString()))); } IChannelProvider pushChannel = GetProviderByType(channelInfo.Channel); if (pushChannel == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "未能找到需要的推送通道。")); } PushParams thisPush = new PushParams() { Message = pushParams.Message, Targets = dicAppType[type] }; if (thisPush.Targets == null || thisPush.Targets.Count == 0) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("App类型:{0}对应的推送目标为空。", type.ToString()))); } PushResult result = pushChannel.Push(thisPush); if (result == null || result.IsCallPushError) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("向App类型:{0}对应的推送目标推送时结果为空。", type.ToString()))); } if (result.IsCallPushError) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("向App类型:{0}对应的推送目标推送时出现错误,推送结果:{1}。", type.ToString(), result.ResultMessage))); } } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("未找到App类型:{0}对应的推送配置信息。", type.ToString()))); } } return(Request.CreateResponse <PushResult>(HttpStatusCode.OK, new PushResult() { IsCallPushError = false, ResultMessage = "调用推送接口成功。" })); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } }
public SageCommandProcessor(ILifetimeScope lifetimeScope, TunerElement tunerSettings, DeviceElement deviceSettings, ICaptureManager executableProcessCaptureManager, IChannelProvider channelProvider, Logger logger) { _lifetimeScope = lifetimeScope; _tunerSettings = tunerSettings; _deviceSettings = deviceSettings; _executableProcessCapture = executableProcessCaptureManager; _channelProvider = channelProvider; Logger = logger; _tunerState = new TunerState(); _tunerState.Name = _tunerSettings.Name; }
/// <summary> /// Convenience method for <see cref="ServerChannel.Start"/> that looks more idiomatic to typical /// channel creation methods on <see cref="IChannelProvider"/>. /// </summary> /// <param name="provider">The channel provider.</param> /// <param name="identifier">This is an identifier of the "type" of bundle that is being published, /// and should form a path with forward-slash '/' delimiters.</param> /// <returns>The newly created server channel, or <c>null</c> if there was no listener for /// server channels on <paramref name="provider"/>.</returns> public static ServerChannel StartServerChannel(this IChannelProvider provider, string identifier) { Contracts.CheckValue(provider, nameof(provider)); Contracts.CheckNonWhiteSpace(identifier, nameof(identifier)); return(ServerChannel.Start(provider, identifier)); }
/// <summary> /// Initializes a new instance of the <see cref="BotFrameworkHttpAdapter"/> class, /// using a credential provider. /// </summary> /// <param name="credentialProvider">The credential provider.</param> /// <param name="channelProvider">The channel provider.</param> /// <param name="logger">The ILogger implementation this adapter should use.</param> public BotFrameworkHttpAdapter(ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILogger <BotFrameworkHttpAdapter> logger = null) : this(credentialProvider ?? new SimpleCredentialProvider(), new AuthenticationConfiguration(), channelProvider, null, null, null, logger) { }
/// <summary> /// Authenticates the request and adds the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable UseAsyncSuffix // Use Async suffix (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, HttpClient httpClient = null) #pragma warning restore UseAsyncSuffix // Use Async suffix { return(await AuthenticateRequest(activity, authHeader, credentials, provider, new AuthenticationConfiguration(), httpClient).ConfigureAwait(false)); }
public RabbitMQReceiver(IChannelProvider channelProvider) { this._channelProvider = channelProvider; }
/// <summary> /// Initializes a new instance of the <see cref="SkillHttpClient"/> class. /// </summary> /// <param name="httpClient">A HttpClient.</param> /// <param name="credentialProvider">An instance of <see cref="ICredentialProvider"/>.</param> /// <param name="conversationIdFactory">An instance of a class derived from <see cref="SkillConversationIdFactoryBase"/>.</param> /// <param name="channelProvider">An instance of <see cref="IChannelProvider"/>.</param> /// <param name="logger">An instance of <see cref="ILogger"/>.</param> public SkillHttpClient(HttpClient httpClient, ICredentialProvider credentialProvider, SkillConversationIdFactoryBase conversationIdFactory, IChannelProvider channelProvider = null, ILogger logger = null) : base(httpClient, credentialProvider, channelProvider, logger) { _conversationIdFactory = conversationIdFactory; }
public BotFrameworkHttpAdapterBase(ICredentialProvider credentialProvider, IChannelProvider channelProvider, HttpClient httpClient, ILogger <BotFrameworkHttpAdapterBase> logger) : this(credentialProvider ?? new SimpleCredentialProvider(), new AuthenticationConfiguration(), channelProvider, null, httpClient, null, logger) { }
/// <summary> /// Validate the incoming Auth Header as a token sent from a Bot Framework Channel Service. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="channelProvider">The user defined configuration for the channel.</param> /// <param name="serviceUrl">The service url from the request.</param> /// <param name="httpClient">Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended.</param> /// <param name="channelId">The ID of the channel to validate.</param> /// <param name="authConfig">The authentication configuration.</param> /// <returns>ClaimsIdentity.</returns> #pragma warning disable UseAsyncSuffix // Use Async suffix (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string serviceUrl, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig) #pragma warning restore UseAsyncSuffix // Use Async suffix { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } var channelService = await channelProvider.GetChannelServiceAsync().ConfigureAwait(false); var tokenExtractor = new JwtTokenExtractor( httpClient, ToBotFromEnterpriseChannelTokenValidationParameters, string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ToBotFromEnterpriseChannelOpenIdMetadataUrlFormat, channelService), AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false); await ValidateIdentity(identity, credentials, serviceUrl).ConfigureAwait(false); return(identity); }
public BotFrameworkHttpAdapter(ICredentialProvider credentialProvider = null, IChannelProvider channelProvider = null, ILogger <BotFrameworkHttpAdapter> logger = null) : base(credentialProvider ?? new SimpleCredentialProvider(), channelProvider, null, null, null, logger) { }
public RootSlotCursor(IChannelProvider provider) : base(provider) { _slotIndex = -1; }
public SkillHandlerInstanceForTests(BotAdapter adapter, IBot bot, SkillConversationIdFactoryBase testConversationIdFactory, ICredentialProvider credentialProvider, AuthenticationConfiguration authConfig, IChannelProvider channelProvider = null, ILogger logger = null) : base(adapter, bot, testConversationIdFactory, credentialProvider, authConfig, channelProvider, logger) { }
public Cursor(IChannelProvider provider, StreamingDataView <TRow> dataView, Func <int, bool> predicate) : base(provider, dataView, predicate) { _enumerator = dataView._data.GetEnumerator(); _currentRow = null; }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="authConfig">The authentication configuration.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, AuthenticationConfiguration authConfig, string serviceUrl = null, HttpClient httpClient = null) { if (string.IsNullOrEmpty(authHeader)) { throw new ArgumentNullException(nameof(authHeader)); } if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } httpClient = httpClient ?? _httpClient; bool usingEmulator = EmulatorValidation.IsTokenFromEmulator(authHeader); if (usingEmulator) { return(await EmulatorValidation.AuthenticateEmulatorToken(authHeader, credentials, channelProvider, httpClient, channelId, authConfig)); } else if (channelProvider == null || channelProvider.IsPublicAzure()) { // No empty or null check. Empty can point to issues. Null checks only. if (serviceUrl != null) { return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig)); } else { return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, httpClient, channelId, authConfig)); } } else if (channelProvider.IsGovernment()) { return(await GovernmentChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } else { return(await EnterpriseChannelValidation.AuthenticateChannelToken(authHeader, credentials, channelProvider, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } }
/// <summary> /// Validates that the incoming Auth Header is a token sent from a bot to a skill or from a skill to a bot. /// </summary> /// <param name="authHeader">The raw HTTP header in the format: "Bearer [longString]".</param> /// <param name="credentials">The user defined set of valid credentials, such as the AppId.</param> /// <param name="channelProvider">The channelService value that distinguishes public Azure from US Government Azure.</param> /// <param name="httpClient"> /// Authentication of tokens requires calling out to validate Endorsements and related documents. The /// HttpClient is used for making those calls. Those calls generally require TLS connections, which are expensive to /// setup and teardown, so a shared HttpClient is recommended. /// </param> /// <param name="channelId">The ID of the channel to validate.</param> /// <param name="authConfig">The authentication configuration.</param> /// <returns>A <see cref="ClaimsIdentity"/> instance if the validation is successful.</returns> public static async Task <ClaimsIdentity> AuthenticateChannelToken(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, HttpClient httpClient, string channelId, AuthenticationConfiguration authConfig) { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } var openIdMetadataUrl = channelProvider != null && channelProvider.IsGovernment() ? GovernmentAuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl : AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl; var tokenExtractor = new JwtTokenExtractor( httpClient, _tokenValidationParameters, openIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms); var identity = await tokenExtractor.GetIdentityAsync(authHeader, channelId, authConfig.RequiredEndorsements).ConfigureAwait(false); await ValidateIdentityAsync(identity, credentials).ConfigureAwait(false); return(identity); }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="authConfig">The authentication configuration.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> #pragma warning disable UseAsyncSuffix // Use Async suffix (can't change this without breaking binary compat) public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, AuthenticationConfiguration authConfig, string serviceUrl = null, HttpClient httpClient = null) #pragma warning restore UseAsyncSuffix // Use Async suffix { if (string.IsNullOrEmpty(authHeader)) { throw new ArgumentNullException(nameof(authHeader)); } if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } httpClient = httpClient ?? _httpClient; var identity = await AuthenticateTokenAsync(authHeader, credentials, channelProvider, channelId, authConfig, serviceUrl, httpClient).ConfigureAwait(false); await ValidateClaimsAsync(authConfig, identity.Claims).ConfigureAwait(false); return(identity); }
public MessageDispatcher(IChannelProvider channelProvider) { this.channelProvider = channelProvider; }
/// <summary> /// Authenticates the request and add's the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="authConfig">The optional authentication configuration.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, AuthenticationConfiguration authConfig, HttpClient httpClient = null) { if (authConfig == null) { throw new ArgumentNullException(nameof(authConfig)); } if (string.IsNullOrWhiteSpace(authHeader)) { bool isAuthDisabled = await credentials.IsAuthenticationDisabledAsync().ConfigureAwait(false); if (isAuthDisabled) { // In the scenario where Auth is disabled, we still want to have the // IsAuthenticated flag set in the ClaimsIdentity. To do this requires // adding in an empty claim. return(new ClaimsIdentity(new List <Claim>(), "anonymous")); } // No Auth Header. Auth is required. Request is not authorized. throw new UnauthorizedAccessException(); } var claimsIdentity = await ValidateAuthHeader(authHeader, credentials, provider, activity.ChannelId, authConfig, activity.ServiceUrl, httpClient ?? _httpClient); MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl); return(claimsIdentity); }
public void ServerTestInitialize() { this.settings = new ServerSettings {Name = "Test Server", Description = "Test Server"}; this.permissions = new GuestPermissionProvider (); this.channels = new LobbyChannelProvider(); this.users = new GuestUserProvider(); this.server = new GablarskiServer (this.settings, this.users, this.permissions, this.channels); this.server.AddConnectionProvider (this.provider = new MockConnectionProvider (GablarskiProtocol.Instance), ExecutionMode.GlobalOrder); this.server.Start (); }
/// <summary> /// Validates the authentication header of an incoming request. /// </summary> /// <param name="authHeader">The authentication header to validate.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="channelProvider">The bot's channel service provider.</param> /// <param name="channelId">The ID of the channel that sent the request.</param> /// <param name="serviceUrl">The service URL for the activity.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> ValidateAuthHeader(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, string serviceUrl = null, HttpClient httpClient = null) { return(await ValidateAuthHeader(authHeader, credentials, channelProvider, channelId, new AuthenticationConfiguration(), serviceUrl, httpClient).ConfigureAwait(false)); }
/// <summary> /// Authenticates the request and add's the activity's <see cref="Activity.ServiceUrl"/> /// to the set of trusted URLs. /// </summary> /// <param name="activity">The activity.</param> /// <param name="authHeader">The authentication header.</param> /// <param name="credentials">The bot's credential provider.</param> /// <param name="provider">The bot's channel service provider.</param> /// <param name="httpClient">The HTTP client.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the task completes successfully, the result contains the claims-based /// identity for the request.</remarks> public static async Task <ClaimsIdentity> AuthenticateRequest(IActivity activity, string authHeader, ICredentialProvider credentials, IChannelProvider provider, HttpClient httpClient = null) { return(await AuthenticateRequest(activity, authHeader, credentials, provider, new AuthenticationConfiguration(), httpClient)); }
/// <summary> /// Authenticates the auth header token from the request. /// </summary> private static async Task <ClaimsIdentity> AuthenticateTokenAsync(string authHeader, ICredentialProvider credentials, IChannelProvider channelProvider, string channelId, AuthenticationConfiguration authConfig, string serviceUrl, HttpClient httpClient) { if (SkillValidation.IsSkillToken(authHeader)) { return(await SkillValidation.AuthenticateChannelToken(authHeader, credentials, channelProvider, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (EmulatorValidation.IsTokenFromEmulator(authHeader)) { return(await EmulatorValidation.AuthenticateEmulatorToken(authHeader, credentials, channelProvider, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (channelProvider == null || channelProvider.IsPublicAzure()) { // No empty or null check. Empty can point to issues. Null checks only. if (serviceUrl != null) { return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } return(await ChannelValidation.AuthenticateChannelToken(authHeader, credentials, httpClient, channelId, authConfig).ConfigureAwait(false)); } if (channelProvider.IsGovernment()) { return(await GovernmentChannelValidation.AuthenticateChannelToken(authHeader, credentials, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); } return(await EnterpriseChannelValidation.AuthenticateChannelToken(authHeader, credentials, channelProvider, serviceUrl, httpClient, channelId, authConfig).ConfigureAwait(false)); }