Skip to main content

Secure authentication with tokens

Authentication is the act of validating the identity of each user before they access a system. Agora uses digital tokens to authenticate users and their privileges before they access Agora SD-RTN™ to join Cloud Recording. Each token is valid for a limited period and works only for a specific channel. For example, you cannot use the token generated for a channel called AgoraChannel to join the AppTest channel.

This page shows you how to quickly set up an authentication token server, retrieve a token from the server, and use it to connect securely to a specific Cloud Recording channel. You use this server for development purposes. To see how to develop your own token generator and integrate it into your production IAM system, read Token generators.

Understand the tech

An authentication token is a dynamic key that is valid for a maximum of 24 hours. On request, a token server returns an authentication token that is valid to join a specific channel.

When users attempt to connect to an Agora channel from your app, your app retrieves a token from the token server in your security infrastructure. Your app then sends this token to Agora SD-RTN™ for authentication. Agora SD-RTN™ validates the token and reads the user and project information stored in the token. A token contains the following information:

  • The App ID of your Agora project

  • The App certificate of your Agora project

  • The channel name

  • The user ID of the user to be authenticated (optional)

  • The privilege of the user, either as a publisher or a subscriber

  • The Unix timestamp showing when the token will expire

The following figure shows the call flow you need to implement to create step-up-authentication with Agora Cloud Recording:

token authentication flow

Project setup

To integrate token authentication into your app, do the following:

  1. Open the project you wish to implement the authentication workflow to.
  1. Log in to your Railway account.

Implement the authentication workflow

In the SDK quickstart project you implemented, the app uses an authentication token obtained manually from Agora Console to join a channel. In a production environment, your app retrieves this token from a token server. This section shows you how to:

  1. Create and run a token server
  1. Retrieve and use tokens from a token server

Create and run a token server

This section shows you how to deploy a token server on Railway.

  1. Click here and deploy a token server to Railway.

    Railway retrieves the project code and necessary files from Github, then takes you to the Deploy Agora Token Deployment page. On this page, fill in the following information:

    1. Github account: The GitHub account where Railway should clone the token deployment repository.

    2. Repository name: The name of the cloned repository, the default is agora-token-service.

    3. Private repository: Select this option to hide this repoisitory.

    4. APP_CERTIFICATE: The obtained from Agora Console.

    5. APP_ID: The App ID obtained from Agora Console.

  2. Click Deploy. Railway configures and builds the token server.

    The deployment turn green once it is complete.

  3. Click the URL.

    Railway opens the token server URL in your browser. The URL is of the form agora-token-service-production-<id>.up.railway.app, where <id> is a random alphanumeric string.

    Don’t worry if you see 404 page not found in your browser. Follow the next steps and test your server.

  4. Test your server

    1. Retrieve a token

      To retrieve an Video SDK token, send a request to the token server using a URL based on the Token server GET request structure:

      /rtc/:channelName/:role/:tokentype/:uid/?expiry=expireTime
      Copy

      For example: https://agora-token-service-production-92ff.up.railway.app/rtc/MyChannel/1/uid/1/?expiry=300

      Your token server returns a JSON object containing the encyrpted token:

      {"rtcToken":"ThisIsAnExampleTokenThisIsAnExampleTokenThisIsAnExampleTokenThisIsAnExampleTokenThisIsAnExampleToken"}
      Copy

Authentication using UI Kit

To retrieve tokens from the token server and use them to authenticate your app with Agora SD-RTN™ using UI Kit

  1. Specify the token server URL

    In the MainActivity class, declare the following variable to hold the token server URL.

    // The base URL to your token server.
    // For example, "https://agora-token-service-production-92ff.up.railway.app"
    private String serverUrl = "<Token Server URL>";
    Copy

    Make sure you specify the token-server URL in exactly the same format as shown in the example.

  2. Set the token URL for AgoraVideoViewer

    To set the token URL, you create an AgoraSettings object, set its TokenURL property and pass this object to the constructor when initializing AgoraVideoViewer. To do this, replace the code in the try {…​} block of the initializeAndJoinChannel() method with the following:

    AgoraSettings settings = new AgoraSettings();
    settings.setTokenURL(serverUrl);
    agView = new AgoraVideoViewer(this, new AgoraConnectionData(appId, null),
    AgoraVideoViewer.Style.FLOATING, settings, null);
    Copy
  3. Fetch a token from the server when you join a channel

    In the joinChannel() method, replace the agView.join call with the following:

    agView.join(channelName, true, Constants.CLIENT_ROLE_BROADCASTER, 0);
    Copy

Authentication using Video SDK

To retrieve tokens from the token server and use them to authenticate your app with Agora SD-RTN™ using Video SDK

  1. Add the necessary dependencies

    In order to make HTTPS calls to a token server and interpret the JSON return parameters, integrate the OkHttp client and Gson library into your Android project. In /Gradle Scripts/build.gradle (Module: <projectname>.app), add the following lines under dependencies.

    ...
    dependencies
    {
    ...
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    implementation 'com.google.code.gson:gson:2.9.0'
    ...
    }
    Copy
  2. Allow cleartext network traffic

    Add the following line in /app/Manifests/AndroidManifest.xml, under <application:

    android:usesCleartextTraffic = "true"
    Copy
  3. Enable the user to specify a channel name

    Add a text box to the user interface. In /app/res/layout/activity_main.xml add the following lines before </RelativeLayout>:

    <EditText
    android:id="@+id/editChannelName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/JoinButton"
    android:layout_alignStart="@id/JoinButton"
    android:layout_alignEnd="@id/LeaveButton"
    android:hint="Type the channel name here"
    android:inputType="text"
    android:text="" />
    Copy
  4. Add the required import statements

    In /app/java/com.example.<projectname>/MainActivity, add the following lines after the last import statement:

    import android.util.Log;
    import android.widget.EditText;

    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    import okhttp3.Call;
    import okhttp3.Callback;

    import com.google.gson.Gson;

    import java.io.IOException;
    import java.util.Map;
    Copy
  5. Add variables for your connection to the token server

    Declare the variables you need to specify the user id, token role, token server URL and the token expire time. Add the following declarations to the MainActivity class after private RtcEngine agoraEngine;

    private int tokenRole; // The token role: Broadcaster or Audience
    private String serverUrl = "<Token Server URL>"; // The base URL to your token server, for example, "https://agora-token-service-production-92ff.up.railway.app".
    private int tokenExpireTime = 40; // Expire time in Seconds.
    private EditText editChannelName; // To read the channel name from the UI.
    Copy

    Make sure you specify the token server URL in exactly the same format as shown in the example.

  6. Set up access to the channel name text box from code

    Add the following line at the end of the onCreate method,.

    editChannelName = (EditText) findViewById(R.id.editChannelName);
    Copy
  7. Retrieve a token from the server

    Use a GET request to retrieve an authentication token for a specific channel from the token server, then decode the return parameters.

    In the MainActivity class, add the following fetchToken method:

    // Fetch the <Vg k="VSDK" /> token
    private void fetchToken(int uid, String channelName, int tokenRole) {
    // Prepare the Url
    String URLString = serverUrl + "/rtc/" + channelName + "/" + tokenRole + "/"
    + "uid" + "/" + uid + "/?expiry=" + tokenExpireTime;

    OkHttpClient client = new OkHttpClient();

    // Instantiate the RequestQueue.
    Request request = new Request.Builder()
    .url(URLString)
    .header("Content-Type", "application/json; charset=UTF-8")
    .get()
    .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {

    @Override
    public void onFailure(Call call, IOException e) {
    Log.e("IOException", e.toString());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    if (response.isSuccessful()) {
    Gson gson = new Gson();
    String result = response.body().string();
    Map map = gson.fromJson(result, Map.class);
    String _token = map.get("rtcToken").toString();
    setToken(_token);
    Log.i("Token Received", token);
    }
    }
    });
    }
    Copy
  8. Join a channel using the token

    Use the retrieved token to either join a channel or to renew an expiring token.

    In the MainActivity class, add the following setToken method:

  9. Handle the event triggered by Agora SD-RTN™ when the token is about to expire

    A token expires after the expireTime specified in the call to the token server or expires after 24 hours, if the time is not specified. The onTokenPrivilegeWillExpire event receives a callback when the current token is about to expire so that a fresh token may be retrieved and used.

    In the MainActivity class, add the following method after private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {

    // Listen for the event that the token is about to expire
    @Override
    public void onTokenPrivilegeWillExpire(String token) {
    Log.i("i", "Token Will expire");
    fetchToken(uid, channelName, tokenRole);
    super.onTokenPrivilegeWillExpire(token);
    }
    Copy
  10. Update the joinChannel method to fetch a token

    In the MainActivity class, replace the joinChannel method with the following:

Test your implementation

To ensure that you have implemented Agora token authentication workflow in your app:

  1. Generate a token in Agora Console.

    Users communicate securely using channels in the same project. The App ID you use to generate this token must be the same one you supplied to Railway.

  2. In your browser, navigate to the Agora web demo and update App ID, Channel, and Token with the values for your temporary token, then click Join.

  1. Set the variables in your app:

    1. Update appID in the declarations to the value from Agora Console.

    2. Set token to an empty string in the declarations.

    3. Update serverUrl in the declarations to the base address of your token server, for example, https://agora-token-service-production-92ff.up.railway.app.

    4. If you are developing with UI Kit: set channelName to the same Channel you specified in the web demo app.

  2. Connect a physical Android device to your development device.

  3. In Android Studio, click Run app. A moment later you see the project installed on your device.

    If this is the first time you run the project, grant microphone and camera access to your app.

  4. If you are developing with Video SDK: enter the same channel name in the UI text box that you used to connect to the Agora web demo.

  5. Click Join to connect your Android app to the web demo app.

Your app magically connects to the same channel you used in web demo. You don’t need to hardcode a token in your app; each channel is secured with a specific token, and each token is refreshed automatically. That’s pretty cool!

Reference

This section contains information that completes the information in this page, or points you to documentation that explains other aspects to this product.

Source code for a token server

The token server RESTful web service used in this page is written in Golang using the Gin framework. Want to use the code in your authentication service? Download the token server source code and binaries for various platforms from Github.

To see how to create a token generator inside your IAM system, see Integrate a token generator.

Token server GET request structure

A token server GET request has the following structure:

/rtc/:channelName/:role/:tokentype/:uid/?expiry=expireTime
Copy
  • :channelName is the name of the Agora Channel you wish to join

    A channel name may contain numbers with both upper and lower case letters. The name length must be less than 64 characters.

  • :role is the user role

    Use publisher for publisher, subscriber for subscriber.

  • :tokentype is the type of token

    Agora SD-RTN™ supports both integer user IDs and string user accounts for token generation. To ensure smooth communication, all the users in a channel must use the same type of ID, that is, either the integer uid, or a string userAccount. Best practice is to use the uid.

  • :uid is the user ID

    User Id can be any 32-bit unsigned integer. It can be set to 0, if you do not need to authenticate the user based on the user ID.

  • expireTime (optional) is the number of seconds after which the token will expire

    By default, a token expires after 24 hours unless a shorter life span is explicitly specified in the token request.