public async Task GettingTurnCredentialsWithRequestedRouteType(AuthMethod authMethod, RouteType routeType)
        {
            CommunicationRelayClient client = authMethod switch
            {
                AuthMethod.ConnectionString => CreateClientWithConnectionString(),
                AuthMethod.KeyCredential => CreateClientWithAzureKeyCredential(),
                AuthMethod.TokenCredential => CreateClientWithTokenCredential(),
                _ => throw new ArgumentOutOfRangeException(nameof(authMethod)),
            };

            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();

            Response <CommunicationUserIdentifier> userResponse = await communicationIdentityClient.CreateUserAsync();

            Response <CommunicationRelayConfiguration> turnCredentialsResponse = await client.GetRelayConfigurationAsync(userResponse.Value, routeType);

            Assert.IsNotNull(turnCredentialsResponse.Value);
            Assert.IsNotNull(turnCredentialsResponse.Value.ExpiresOn);
            Assert.IsNotNull(turnCredentialsResponse.Value.IceServers);
            foreach (CommunicationIceServer serverCredential in turnCredentialsResponse.Value.IceServers)
            {
                foreach (string url in serverCredential.Urls)
                {
                    Assert.IsFalse(string.IsNullOrWhiteSpace(url));
                }
                Assert.IsFalse(string.IsNullOrWhiteSpace(serverCredential.Username));
                Assert.IsFalse(string.IsNullOrWhiteSpace(serverCredential.Credential));
                Assert.AreEqual(routeType, serverCredential.RouteType);
            }
        }
Ejemplo n.º 2
0
        public async Task IssuingTokenGeneratesTokenAndIdentityWithScopes(AuthMethod authMethod, params string[] scopes)
        {
            CommunicationIdentityClient client = authMethod switch
            {
                AuthMethod.ConnectionString => CreateClientWithConnectionString(),
                AuthMethod.KeyCredential => CreateClientWithAzureKeyCredential(),
                AuthMethod.TokenCredential => CreateClientWithTokenCredential(),
                _ => throw new ArgumentOutOfRangeException(nameof(authMethod)),
            };

            Response <CommunicationUserIdentifier> userResponse = await client.CreateUserAsync();

            Response <CommunicationUserToken> tokenResponse = await client.IssueTokenAsync(userResponse.Value, scopes : scopes.Select(x => new CommunicationTokenScope(x)));

            Assert.IsNotNull(tokenResponse.Value);
            Assert.IsFalse(string.IsNullOrWhiteSpace(tokenResponse.Value.Token));
            ValidateScopesIfNotSanitized();

            void ValidateScopesIfNotSanitized()
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    JwtTokenParser.JwtPayload payload = JwtTokenParser.DecodeJwtPayload(tokenResponse.Value.Token);
                    CollectionAssert.AreEquivalent(scopes, payload.Scopes);
                }
            }
        }
        public async Task Participants_Async()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.LiveTestDynamicConnectionString);
            Response <CommunicationUserIdentifier> threadCreatorIdentifier     = await communicationIdentityClient.CreateUserAsync();

            Response <CommunicationUserIdentifier> participantIdentifier = await communicationIdentityClient.CreateUserAsync();

            AccessToken communicationUserToken = await communicationIdentityClient.GetTokenAsync(threadCreatorIdentifier.Value, new[] { CommunicationTokenScope.Chat });

            string userToken = communicationUserToken.Token;

            ChatClient chatClient = new ChatClient(
                TestEnvironment.LiveTestDynamicEndpoint,
                new CommunicationTokenCredential(userToken));

            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new ChatParticipant[] { });

            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(createChatThreadResult.ChatThread.Id);

            #region Snippet:Azure_Communication_Chat_Tests_Samples_AddParticipants_KeyConcepts
            chatThreadClient.AddParticipants(participants: new[] { new ChatParticipant(participantIdentifier) });
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_AddParticipants_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetParticipants_KeyConcepts
            Pageable <ChatParticipant> chatParticipants = chatThreadClient.GetParticipants();
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetParticipants_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_RemoveParticipant_KeyConcepts
            chatThreadClient.RemoveParticipant(identifier: participantIdentifier);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_RemoveParticipant_KeyConcepts
        }
        private async Task <CommunicationUserIdentifier> CreateUser()
        {
            var client = new CommunicationIdentityClient(connectionString);
            var user   = await client.CreateUserAsync().ConfigureAwait(false);

            return(new CommunicationUserIdentifier(user.Value.Id));
        }
Ejemplo n.º 5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string code        = req.Query["entryCode"];
            string correctCode = Environment.GetEnvironmentVariable("EntryCode");

            if (correctCode != null && code.ToLower() == correctCode.ToLower())
            {
                CommunicationIdentityClient _client = new CommunicationIdentityClient(Environment.GetEnvironmentVariable("ACS_Connection_String"));

                Response <CommunicationUser> userResponse = await _client.CreateUserAsync();

                CommunicationUser user = userResponse.Value;
                Response <CommunicationUserToken> tokenResponse =
                    await _client.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.VoIP });

                string         token     = tokenResponse.Value.Token;
                DateTimeOffset expiresOn = tokenResponse.Value.ExpiresOn;
                return(new OkObjectResult(tokenResponse));
            }
            else
            {
                Random rnd = new Random();
                System.Threading.Thread.Sleep(rnd.Next(500, 5000));
                return(new UnauthorizedResult());
            }
        }
        private async Task <Response <CreateCallResponse> > CreateCallOperation(CallClient client)
        {
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();
            var source = await CreateUserAsync(communicationIdentityClient).ConfigureAwait(false);

            var targets = new List <CommunicationIdentifier>()
            {
                new PhoneNumberIdentifier(TestEnvironment.TargetPhoneNumber)
            };
            var createCallOption = new CreateCallOptions(
                new Uri(TestEnvironment.AppCallbackUrl),
                new List <CallModality> {
                CallModality.Audio
            },
                new List <EventSubscriptionType> {
                EventSubscriptionType.ParticipantsUpdated, EventSubscriptionType.DtmfReceived
            });

            createCallOption.AlternateCallerId = new PhoneNumberIdentifier(TestEnvironment.SourcePhoneNumber);

            Console.WriteLine("Performing CreateCall operation");

            var createCallResponse = await client.CreateCallAsync(source : source, targets : targets, options : createCallOption).ConfigureAwait(false);

            Console.WriteLine("Call initiated with Call Leg id: {0}", createCallResponse.Value.CallLegId);

            Assert.IsFalse(string.IsNullOrWhiteSpace(createCallResponse.Value.CallLegId));
            return(createCallResponse);
        }
Ejemplo n.º 7
0
        public void CreateCall()
        {
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();
            var source           = communicationIdentityClient.CreateUser();
            var targets          = new[] { new PhoneNumberIdentifier(TestEnvironment.TargetPhoneNumber) };
            var createCallOption = new CreateCallOptions(
                new Uri(TestEnvironment.AppCallbackUrl),
                new[] { MediaType.Audio },
                new[] {
                EventSubscriptionType.ParticipantsUpdated,
                EventSubscriptionType.DtmfReceived
            });
            CallingServerClient callingServerClient = CreateInstrumentedCallingServerClient();

            Console.WriteLine("Performing CreateCallConnection operation");
            #region Snippet:Azure_Communication_Call_Tests_CreateCall
            var callConnection = callingServerClient.CreateCallConnection(
                //@@ source: new CommunicationUserIdentifier("<source-identifier>"), // Your Azure Communication Resource Guid Id used to make a Call
                //@@ targets: new List<CommunicationIdentifier>() { new PhoneNumberIdentifier("<targets-phone-number>") }, // E.164 formatted recipient phone number
                //@@ options: createCallOption // The options for creating a call.
                /*@@*/ source: source,
                /*@@*/ targets: targets,
                /*@@*/ options: createCallOption
                );
            Console.WriteLine($"Call connection id: {callConnection.Value.CallConnectionId}");
            #endregion Snippet:Azure_Communication_Call_Tests_CreateCall
        }
        private (CommunicationUserIdentifier user, string token) CreateUserAndToken(CommunicationIdentityClient communicationIdentityClient)
        {
            Response <CommunicationUserIdentifier> user   = communicationIdentityClient.CreateUser();
            IEnumerable <CommunicationTokenScope>  scopes = new[] { CommunicationTokenScope.Chat };
            Response <AccessToken> tokenResponseUser      = communicationIdentityClient.GetToken(user.Value, scopes);

            return(user, tokenResponseUser.Value.Token);
        }
Ejemplo n.º 9
0
        private (CommunicationUser user, string token) CreateUserAndToken(CommunicationIdentityClient communicationIdentityClient)
        {
            Response <CommunicationUser>          threadMember = communicationIdentityClient.CreateUser();
            IEnumerable <CommunicationTokenScope> scopes       = new[] { CommunicationTokenScope.Chat };
            Response <CommunicationUserToken>     tokenResponseThreadMember = communicationIdentityClient.IssueToken(threadMember.Value, scopes);

            return(tokenResponseThreadMember.Value.User, tokenResponseThreadMember.Value.Token);
        }
Ejemplo n.º 10
0
        public async Task <IHttpActionResult> ACSRefreshAsync(TokenRequest request)
        {
            var client            = new CommunicationIdentityClient(connectionString);
            var identitytoRefresh = new CommunicationUser(request.UserEmail);
            var tokenResponse     = await client.IssueTokenAsync(identitytoRefresh, scopes : new[] { CommunicationTokenScope.VoIP });

            return(Ok(tokenResponse.Value));
        }
Ejemplo n.º 11
0
 public TokenController(ILogger <TokenController> logger, IConfiguration configuration)
 {
     _logger        = logger;
     _configuration = configuration;
     //Azure Communication Services connection string
     _connectionString = _configuration["ConnectionString"];
     _endpoint         = _configuration["EndPoint"];
     _client           = new CommunicationIdentityClient(_connectionString);
 }
Ejemplo n.º 12
0
        public async Task <IHttpActionResult> GetTokenAsync()
        {
            var client           = new CommunicationIdentityClient(connectionString);
            var identityResponse = await client.CreateUserAsync();

            var identity      = identityResponse.Value;
            var tokenResponse = await client.IssueTokenAsync(identity, scopes : new[] { CommunicationTokenScope.VoIP });

            return(Ok(tokenResponse.Value));
        }
        public Response <AccessToken> CreateIdentityAndGetTokenAsync(Uri resourceEndpoint)
        {
            var client           = new CommunicationIdentityClient(resourceEndpoint, this.credential);
            var identityResponse = client.CreateUser();
            var identity         = identityResponse.Value;

            var tokenResponse = client.GetToken(identity, scopes: new[] { CommunicationTokenScope.VoIP });

            return(tokenResponse);
        }
Ejemplo n.º 14
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Access Tokens Quickstart");

            //  Authenticate the client
            // This code demonstrates how to fetch your connection string
            // from an environment variable.
            string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
            var    client           = new CommunicationIdentityClient(connectionString);

            // This code demonstrates how to fetch your endpoint and access key
            // from an environment variable.

            /*string endpoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ENDPOINT");
             * string accessKey = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ACCESSKEY");
             * var client = new CommunicationIdentityClient(new Uri(endpoint), new AzureKeyCredential(accessKey));*/

            // Update documentation with URI details

            /*TokenCredential tokenCredential = new DefaultAzureCredential();
             * string endPoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ENDPOINT");
             * var client = new CommunicationIdentityClient(new Uri(endPoint), tokenCredential);*/

            // Create an identity
            var identityResponse = await client.CreateUserAsync();

            var identity = identityResponse.Value;

            Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");

            // Issue an access token with the "voip" scope for an identity
            var tokenResponse = await client.GetTokenAsync(identity, scopes : new[] { CommunicationTokenScope.VoIP });

            var token     = tokenResponse.Value.Token;
            var expiresOn = tokenResponse.Value.ExpiresOn;

            Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:");
            Console.WriteLine(token);

            // Refresh access tokens
            var identityToRefresh    = new CommunicationUserIdentifier(identity.Id);
            var refreshTokenResponse = await client.GetTokenAsync(identityToRefresh, scopes : new[] { CommunicationTokenScope.VoIP });

            // Revoke access tokens
            await client.RevokeTokensAsync(identity);

            Console.WriteLine($"\nSuccessfully revoked all access tokens for identity with ID: {identity.Id}");

            // Delete an identity
            await client.DeleteUserAsync(identity);

            Console.WriteLine($"\nDeleted the identity with ID: {identity.Id}");
        }
Ejemplo n.º 15
0
        public async Task GetTokenForTeamsUserWithValidParameters()
        {
            if (TestEnvironment.ShouldIgnoreIdentityExchangeTokenTest)
            {
                Assert.Ignore("Ignore exchange teams token test if flag is enabled.");
            }

            CommunicationIdentityClient client        = CreateClientWithConnectionString();
            Response <AccessToken>      tokenResponse = await client.GetTokenForTeamsUserAsync(CTEOptions);

            Assert.IsNotNull(tokenResponse.Value);
            Assert.IsFalse(string.IsNullOrWhiteSpace(tokenResponse.Value.Token));
        }
Ejemplo n.º 16
0
 public async Task GetTokenForTeamsUserWithNullTokenShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client        = CreateClientWithConnectionString();
         Response <AccessToken>      tokenResponse = await client.GetTokenForTeamsUserAsync(null);
     }
     catch (ArgumentNullException ex)
     {
         Assert.AreEqual("token", ex.ParamName);
         return;
     }
     Assert.Fail("An exception should have been thrown.");
 }
        public async Task MessagesNotificationsReadReceipts_Async()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUserIdentifier> threadCreatorIdentifier     = await communicationIdentityClient.CreateUserAsync();

            AccessToken communicationUserToken = await communicationIdentityClient.GetTokenAsync(threadCreatorIdentifier.Value, new[] { CommunicationTokenScope.Chat });

            string userToken = communicationUserToken.Token;
            string endpoint  = TestEnvironment.ChatApiUrl();

            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationTokenCredential(userToken));

            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new ChatParticipant[] { });

            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(createChatThreadResult.ChatThread.Id);

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendMessage_KeyConcepts
            string messageId = chatThreadClient.SendMessage("Let's meet at 11am");
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendMessage_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage_KeyConcepts
            ChatMessage message = chatThreadClient.GetMessage(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages_KeyConcepts
            Pageable <ChatMessage> messages = chatThreadClient.GetMessages();
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage_KeyConcepts
            chatThreadClient.UpdateMessage(messageId, content: "Instead of 11am, let's meet at 2pm");
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage_KeyConcepts
            chatThreadClient.DeleteMessage(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt_KeyConcepts
            chatThreadClient.SendReadReceipt(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts_KeyConcepts
            Pageable <ChatMessageReadReceipt> readReceipts = chatThreadClient.GetReadReceipts();
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts_KeyConcepts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification_KeyConcepts
            chatThreadClient.SendTypingNotification();
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification_KeyConcepts
        }
        public async Task ReadReceiptGSAsync()
        {
            //arr
            Console.WriteLine($"ReadReceiptGSAsync Running on RecordedTestMode : {Mode}");
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();

            (CommunicationUserIdentifier user1, string token1) = await CreateUserAndTokenAsync(communicationIdentityClient);

            (CommunicationUserIdentifier user2, string token2) = await CreateUserAndTokenAsync(communicationIdentityClient);

            var participants = new List <ChatParticipant>
            {
                new ChatParticipant(user1),
                new ChatParticipant(user2)
            };
            ChatClient chatClient  = CreateInstrumentedChatClient(token1);
            ChatClient chatClient2 = CreateInstrumentedChatClient(token2);

            string repeatabilityRequestId1 = "contoso-E0A747F1-6245-4307-8267-B974340677DE";

            //act
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync("Thread topic - ReadReceipts Async Test", participants, repeatabilityRequestId1);

            ChatThreadClient chatThreadClient = GetInstrumentedChatThreadClient(chatClient, createChatThreadResult.ChatThread.Id);
            var threadId = chatThreadClient.Id;
            ChatThreadClient chatThreadClient2 = GetInstrumentedChatThreadClient(chatClient2, threadId);

            SendChatMessageResult sendChatMessageResult2 = await chatThreadClient.SendMessageAsync("This is message 1 content");

            string messageId2 = sendChatMessageResult2.Id;

            SendChatMessageResult sendChatMessageResult = await chatThreadClient2.SendMessageAsync("This is message 2 content");

            string messageId = sendChatMessageResult.Id;

            await chatThreadClient.SendReadReceiptAsync(messageId);

            await chatThreadClient2.SendReadReceiptAsync(messageId2);

            AsyncPageable <ChatMessageReadReceipt> readReceipts  = chatThreadClient.GetReadReceiptsAsync();
            AsyncPageable <ChatMessageReadReceipt> readReceipts2 = chatThreadClient2.GetReadReceiptsAsync();
            var readReceiptsCount  = readReceipts.ToEnumerableAsync().Result.Count;
            var readReceiptsCount2 = readReceipts2.ToEnumerableAsync().Result.Count;

            await chatClient.DeleteChatThreadAsync(threadId);

            //assert
            Assert.AreEqual(2, readReceiptsCount);
            Assert.AreEqual(2, readReceiptsCount2);
        }
Ejemplo n.º 19
0
        public void GetAddRemoveMembers()
        {
            CommunicationIdentityClient  communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUser> threadCreator = communicationIdentityClient.CreateUser();
            Response <CommunicationUser> threadMember2 = communicationIdentityClient.CreateUser();
            Response <CommunicationUser> threadMember3 = communicationIdentityClient.CreateUser();

            string userToken = communicationIdentityClient.IssueToken(threadCreator.Value, new[] { CommunicationTokenScope.Chat }).Value.Token;
            string endpoint  = TestEnvironment.ChatApiUrl();

            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationUserCredential(userToken));

            var chatThreadMember = new ChatThreadMember(new CommunicationUser(threadCreator.Value.Id))
            {
                DisplayName      = "UserDisplayName",
                ShareHistoryTime = DateTime.MinValue
            };
            ChatThreadClient chatThreadClient = chatClient.CreateChatThread(topic: "Hello world!", members: new[] { chatThreadMember });

            Pageable <ChatThreadMember> allMembers = chatThreadClient.GetMembers();

            foreach (ChatThreadMember member in allMembers)
            {
                Console.WriteLine($"{member.User.Id}:{member.DisplayName}:{member.ShareHistoryTime}");
            }

            var members = new[]
            {
                new ChatThreadMember(threadCreator)
                {
                    DisplayName = "display name thread creator"
                },
                new ChatThreadMember(threadMember2)
                {
                    DisplayName = "display name member 2"
                },
                new ChatThreadMember(threadMember3)
                {
                    DisplayName = "display name member 3"
                }
            };

            chatThreadClient.AddMembers(members);

            chatThreadClient.RemoveMember(new CommunicationUser(threadMember2.Value.Id));

            chatClient.DeleteChatThread(chatThreadClient.Id);
        }
        public async Task <AccessToken> GenerateTokenAsync(string resourceConnectionString, string identity)
        {
            try
            {
                var communicationIdentityClient = new CommunicationIdentityClient(resourceConnectionString);
                var userResponse = await communicationIdentityClient.GetTokenAsync(new CommunicationUserIdentifier(identity), scopes : new[] { CommunicationTokenScope.Chat });

                return(userResponse.Value);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 21
0
 public async Task RevokeTokenWithNullUserShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client = CreateClientWithConnectionString();
         Response deleteResponse            = await client.RevokeTokensAsync(communicationUser : null);
     }
     catch (NullReferenceException ex)
     {
         Assert.NotNull(ex.Message);
         Console.WriteLine(ex.Message);
         return;
     }
     Assert.Fail("RevokeTokensAsync should have thrown an exception.");
 }
Ejemplo n.º 22
0
 public async Task GetTokenWithNullUserShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client      = CreateClientWithConnectionString();
         Response <AccessToken>      accessToken = await client.GetTokenAsync(communicationUser : null, scopes : new[] { CommunicationTokenScope.Chat });
     }
     catch (NullReferenceException ex)
     {
         Assert.NotNull(ex.Message);
         Console.WriteLine(ex.Message);
         return;
     }
     Assert.Fail("RevokeTokensAsync should have thrown an exception.");
 }
Ejemplo n.º 23
0
        public async Task <CommunicationUserToken> RefreshTokenAsync(string resourceConnectionString, string identity)
        {
            try
            {
                var communicationIdentityClient = new CommunicationIdentityClient(resourceConnectionString);
                var user          = new CommunicationUser(identity);
                var tokenResponse = await communicationIdentityClient.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.Chat });

                return(tokenResponse);
            }
            catch
            {
                throw;
            }
        }
 public async Task CreateUserAndTokenWithNullScopeShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client = CreateClientWithConnectionString();
         Response <CommunicationUserIdentifierAndToken> response = await client.CreateUserAndTokenAsync(scopes : null);
     }
     catch (NullReferenceException ex)
     {
         Assert.NotNull(ex.Message);
         Console.WriteLine(ex.Message);
         return;
     }
     Assert.Fail("CreateUserAndTokenAsync should have thrown an exception.");
 }
Ejemplo n.º 25
0
        public async Task ExchangeTeamsTokenWithValidToken()
        {
            if (TestEnvironment.ShouldIgnoreIdentityExchangeTokenTest)
            {
                Assert.Ignore("Ignore exchange teams token test if flag is enabled.");
            }

            string token = await generateTeamsToken();

            CommunicationIdentityClient client        = CreateClientWithConnectionString();
            Response <AccessToken>      tokenResponse = await client.ExchangeTeamsTokenAsync(token);

            Assert.IsNotNull(tokenResponse.Value);
            Assert.IsFalse(string.IsNullOrWhiteSpace(tokenResponse.Value.Token));
        }
Ejemplo n.º 26
0
 public async Task GetTokenForTeamsUserWithExpiredTokenShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client        = CreateClientWithConnectionString();
         Response <AccessToken>      tokenResponse = await client.GetTokenForTeamsUserAsync(new GetTokenForTeamsUserOptions(TestEnvironment.CommunicationExpiredTeamsToken, CTEOptions.ClientId, CTEOptions.UserObjectId));
     }
     catch (RequestFailedException ex)
     {
         Assert.NotNull(ex.Message);
         Assert.True(ex.Message.Contains("401"));
         Console.WriteLine(ex.Message);
         return;
     }
     Assert.Fail("An exception should have been thrown.");
 }
Ejemplo n.º 27
0
 public async Task ExchangeTeamsTokenWithInvalidTokenShouldThrow()
 {
     try
     {
         CommunicationIdentityClient client        = CreateClientWithConnectionString();
         Response <AccessToken>      tokenResponse = await client.ExchangeTeamsTokenAsync("invalid");
     }
     catch (RequestFailedException ex)
     {
         Assert.NotNull(ex.Message);
         Assert.True(ex.Message.Contains("401"));
         Console.WriteLine(ex.Message);
         return;
     }
     Assert.Fail("An exception should have been thrown.");
 }
Ejemplo n.º 28
0
        public async Task GetTokenWithNullScopesShouldThrow()
        {
            try
            {
                CommunicationIdentityClient client         = CreateClientWithConnectionString();
                CommunicationUserIdentifier userIdentifier = await client.CreateUserAsync();

                Response <AccessToken> accessToken = await client.GetTokenAsync(communicationUser : userIdentifier, scopes : null);
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual("scopes", ex.ParamName);
                return;
            }
            Assert.Fail("RevokeTokensAsync should have thrown an exception.");
        }
        public void SendGetUpdateDeleteMessagesSendNotificationReadReceipts()
        {
            CommunicationIdentityClient  communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUser> threadMember           = communicationIdentityClient.CreateUser();
            CommunicationUserToken       communicationUserToken = communicationIdentityClient.IssueToken(threadMember.Value, new[] { CommunicationTokenScope.Chat });
            string userToken            = communicationUserToken.Token;
            string endpoint             = TestEnvironment.ChatApiUrl();
            string theadCreatorMemberId = communicationUserToken.User.Id;

            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationUserCredential(userToken));

            var chatThreadMember = new ChatThreadMember(new CommunicationUser(theadCreatorMemberId))
            {
                DisplayName      = "UserDisplayName",
                ShareHistoryTime = DateTime.MinValue
            };
            ChatThreadClient chatThreadClient = chatClient.CreateChatThread(topic: "Hello world!", members: new[] { chatThreadMember });
            string           threadId         = chatThreadClient.Id;

            var content           = "hello world";
            var priority          = ChatMessagePriority.Normal;
            var senderDisplayName = "sender name";
            SendChatMessageResult sendMessageResult = chatThreadClient.SendMessage(content, priority, senderDisplayName);

            var                    messageId   = sendMessageResult.Id;
            ChatMessage            chatMessage = chatThreadClient.GetMessage(messageId);
            Pageable <ChatMessage> allMessages = chatThreadClient.GetMessages();

            foreach (ChatMessage message in allMessages)
            {
                Console.WriteLine($"{message.Id}:{message.Sender.Id}:{message.Content}");
            }

            chatThreadClient.UpdateMessage(messageId, "updated message content");
            chatThreadClient.SendReadReceipt(messageId);
            Pageable <ReadReceipt> allReadReceipts = chatThreadClient.GetReadReceipts();

            foreach (ReadReceipt readReceipt in allReadReceipts)
            {
                Console.WriteLine($"{readReceipt.ChatMessageId}:{readReceipt.Sender.Id}:{readReceipt.ReadOn}");
            }
            chatThreadClient.DeleteMessage(messageId);
            chatThreadClient.SendTypingNotification();
            chatClient.DeleteChatThread(threadId);
        }
Ejemplo n.º 30
0
        public async Task <CommunicationUserToken> GenerateTokenAsync(string resourceConnectionString)
        {
            try
            {
                var communicationIdentityClient = new CommunicationIdentityClient(resourceConnectionString);
                var userResponse = await communicationIdentityClient.CreateUserAsync();

                var user          = userResponse.Value;
                var tokenResponse = await communicationIdentityClient.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.Chat });

                return(tokenResponse);
            }
            catch
            {
                throw;
            }
        }