Back to Azure Sdk For

Azure Communication Identity client library for .NET

sdk/communication/Azure.Communication.Identity/README.md

2019-05-16T16-5211.6 KB
Original Source

Azure Communication Identity client library for .NET

Azure Communication Identity is managing tokens for Azure Communication Services.

Source code <!--| [Package (NuGet)][package]--> | Product documentation | Samples

Getting started

Install the package

Install the Azure Communication Identity client library for .NET with NuGet:

dotnetcli
dotnet add package Azure.Communication.Identity

Prerequisites

You need an Azure subscription and a Communication Service Resource to use this package.

To create a new Communication Service, you can use the Azure Portal, the Azure PowerShell, or the .NET management client library.

<!-- Here's an example using the Azure CLI: ```Powershell [To be ADDED] ``` -->

Authenticate the client

The identity client can be authenticated using a connection string acquired from an Azure Communication Resources in the Azure Portal.

C#
// Get a connection string to our Azure Communication resource.
var connectionString = "<connection_string>";
var client = new CommunicationIdentityClient(connectionString);

Or alternatively using the endpoint and access key acquired from an Azure Communication Resources in the Azure Portal.

C#
var endpoint = new Uri("https://my-resource.communication.azure.com");
var accessKey = "<access_key>";
endpoint = TestEnvironment.LiveTestDynamicEndpoint;
accessKey = TestEnvironment.LiveTestDynamicAccessKey;
var client = new CommunicationIdentityClient(endpoint, new AzureKeyCredential(accessKey));

Clients also have the option to authenticate using a valid Active Directory token.

C#
var endpoint = new Uri("https://my-resource.communication.azure.com");
endpoint = TestEnvironment.LiveTestDynamicEndpoint;
TokenCredential tokenCredential = TestEnvironment.Credential;
var client = new CommunicationIdentityClient(endpoint, tokenCredential);

Key concepts

CommunicationIdentityClient provides the functionalities to manage user access tokens: creating new ones and revoking them.

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

<!-- CLIENT COMMON BAR -->

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

<!-- CLIENT COMMON BAR -->

Examples

Creating a new user

C#
Response<CommunicationUserIdentifier> userResponse = await client.CreateUserAsync();
CommunicationUserIdentifier user = userResponse.Value;
Console.WriteLine($"User id: {user.Id}");

Create a user with an associated customId

The CommunicationIdentityClient allows you to create users with an associated customId. This customId can be used to map your application's user identities with Azure Communication Services identities.

C#
Response<CommunicationUserIdentifier> userResponse = await client.CreateUserAsync(customId: "[email protected]");
CommunicationUserIdentifier user = userResponse.Value;
Console.WriteLine($"User id: {user.Id}");

If you call the CreateUser method again with the same customId, it will return the same user.Id. Therefore, you do not need to store this mapping yourself.

Get user detail

The CommunicationIdentityClient can be used to retrieve details about a user. This includes the user's ID, customId ID, and the last time a token was issued for the user.

C#
Response<CommunicationUserIdentifier> userResponse = await client.CreateUserAsync(customId: "[email protected]");
CommunicationUserIdentifier user = userResponse.Value;
var userDetails = await client.GetUserDetailAsync(user);
Console.WriteLine($"User id: {userDetails.Value.User.Id}");
Console.WriteLine($"Custom id: {userDetails.Value.CustomId}");
Console.WriteLine($"Last token issued at: {userDetails.Value.LastTokenIssuedAt}");

Getting a token for an existing user

C#
Response<AccessToken> tokenResponse = await client.GetTokenAsync(user, scopes: new[] { CommunicationTokenScope.Chat });
string token = tokenResponse.Value.Token;
DateTimeOffset expiresOn = tokenResponse.Value.ExpiresOn;
Console.WriteLine($"Token: {token}");
Console.WriteLine($"Expires On: {expiresOn}");

The GetToken function takes in a list of CommunicationTokenScope. Scope options include:

  • Chat (Use this for full access to Chat APIs)
  • VoIP (Use this for full access to Calling APIs)
  • ChatJoin (Access to Chat APIs but without the authorization to create, delete or update chat threads)
  • ChatJoinLimited (A more limited version of ChatJoin that doesn't allow to add or remove participants)
  • VoIPJoin (Access to Calling APIs but without the authorization to start new calls)

It's also possible to create a Communication Identity access token by customizing the expiration time. Validity period of the token must be within [1,24] hours range. If not provided, the default value of 24 hours will be used.

C#
TimeSpan tokenExpiresIn = TimeSpan.FromHours(1);
Response<AccessToken> tokenResponse = await client.GetTokenAsync(user, scopes: new[] { CommunicationTokenScope.Chat }, tokenExpiresIn);
string token = tokenResponse.Value.Token;
DateTimeOffset expiresOn = tokenResponse.Value.ExpiresOn;
Console.WriteLine($"Token: {token}");
Console.WriteLine($"Expires On: {expiresOn}");

Creating a user and a token in the same request

C#
Response<CommunicationUserIdentifierAndToken> response = await client.CreateUserAndTokenAsync(scopes: new[] { CommunicationTokenScope.Chat });
var (user, token) = response.Value;
Console.WriteLine($"User id: {user.Id}");
Console.WriteLine($"Token: {token.Token}");

It's also possible to create a Communication Identity access token by customizing the expiration time. Validity period of the token must be within [1,24] hours range. If not provided, the default value of 24 hours will be used.

C#
TimeSpan tokenExpiresIn = TimeSpan.FromHours(1);
Response<CommunicationUserIdentifierAndToken> response = await client.CreateUserAndTokenAsync(scopes: new[] { CommunicationTokenScope.Chat }, tokenExpiresIn);
var (user, token) = response.Value;
Console.WriteLine($"User id: {user.Id}");
Console.WriteLine($"Token: {token.Token}");

Revoking a user's tokens

In case a user's tokens are compromised or need to be revoked:

C#
Response revokeResponse = await client.RevokeTokensAsync(user);

Deleting a user

C#
Response deleteResponse = await client.DeleteUserAsync(user);

Exchanging Azure AD access token of a Teams User for a Communication Identity access token

The CommunicationIdentityClient can be used to exchange an Azure AD access token of a Teams user for a new Communication Identity access token with a matching expiration time.

The GetTokenForTeamsUser function accepts the following parameters wrapped into the GetTokenForTeamsUserOptions option bag:

  • teamsUserAadToken Azure Active Directory access token of a Teams user
  • clientId Client ID of an Azure AD application to be verified against the appId claim in the Azure AD access token
  • userObjectId Object ID of an Azure AD user (Teams User) to be verified against the OID claim in the Azure AD access token
C#
Response<AccessToken> tokenResponse = await client.GetTokenForTeamsUserAsync(new GetTokenForTeamsUserOptions(teamsUserAadToken, clientId, userObjectId));
string token = tokenResponse.Value.Token;
Console.WriteLine($"Token: {token}");

Troubleshooting

All User token service operations will throw a RequestFailedException on failure.

C#
// Get a connection string to our Azure Communication resource.
var connectionString = "<connection_string>";
var client = new CommunicationIdentityClient(connectionString);
client = CreateClient();

try
{
    Response<CommunicationUserIdentifier> response = await client.CreateUserAsync();
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.Message);
}

Next steps

Read more about Communication user access tokens

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

<!-- LINKS --> <!--[package]: https://www.nuget.org/packages/Azure.Communication.Identity-->