How to set up Agora’s accesstoken service on. Net core

Time:2020-9-28

As a large number of companies change the office meeting and product release to online, the security of video communication has become the focus of attention. After version 2.1.0, the voice network platform unifies the security authentication forms of various SDKs such as video call RTC, recording and message communication RTM by using accesstoken authentication, which is more convenient for users than the original dynmickey.

. net core is a cross platform development framework of Microsoft, which can run on windows, Linux, MacOS and other operating systems. It can be easily created, compiled and run through command-line tools, and can be used with docker container, which is convenient to embed into microservice architecture.

This article describes how to build an Agora RTC token service based on. Net core 3.1, which can also be used in recording and RTM SDK.

Preparatory knowledge

  • By default, the reader understands the basic C ා programming knowledge, and can visit the C ා documentation if necessary.
  • This article requires ASP.NET Core and related web API knowledge, can be accessed if necessary ASP.NET Document.
  • There will be a little bit of GIT related use in this article, but it’s not necessary.

Tools for this article

  • . net core SDK – includes the. Net core runtime, development kit, and command-line tools.
  • Visual studio code – Microsoft’s cross platform development tool, you can also use your favorite or used development tools.
  • . net core development environment configuration – if you are new to using Visual Studio code, it is recommended to read the installation configuration in this link.
  • Git – git will be used in this article, but it is not a necessary condition, which will be explained in the corresponding section.

Project creation

  1. Open the terminal and enter your usual development directory
  2. Run the following command

dotnet new webapi -o AgoraTokenServer

code -r AgoraTokenServer
  1. If you have installed the visual studio code correctly, the system should open the visual studio code program and display the agoratokenserver project on the left, as shown in the following figure:

How to set up Agora's accesstoken service on. Net core

For convenience, the following visual studio code will be referred to as vscode for short. At this time, the directory structure of the whole project should be as shown in the following figure:

How to set up Agora's accesstoken service on. Net core

We will WeatherForecast.cs And Controllers / weather erForecastController.cs Delete, we will set up our own service later.

development

Introduce tool code

Agora provides the C ා implementation of accesstoken in agoraio in GitHub, which we can use directly.

  1. Go to agoraio in GitHub and click the green code button on the page

How to set up Agora's accesstoken service on. Net core

  1. If you know git, you can go directly to other directories,Note that do not directly in the agoratokenserver project directory created in the previous chapterClone the project.

git clone https://github.com/AgoraIO/Tools.git

If you don’t know git, you can click download zip to download it and unzip it.

How to set up Agora's accesstoken service on. Net core

  1. Enter the directory just cloned by git or downloaded and unzipped

cd Tools/DynamicKey/AgoraDynamicKey/csharp/src/AgoraIO

Copy the common, extensions, media and utils directories directly to the agoratokenserver directory you created. After that, your agoratokenserver directory structure should look like the following figure:

How to set up Agora's accesstoken service on. Net core

Resolve dependencies

You’ll find media in the picture above/ AccessToken.cs It is red, because this project depends on the package of crc32.net. If you have correctly installed the runtime and command-line tools of. Net core, we can directly use the command line to install it.

Enter the root directory of agoratokenserver project and run the following command:


dotnet add package Crc32.NET

In this way, our only external dependency package is solved.

Set appid and appcertificate

  1. In general, appcertificate should be stored in the server with high security, and should not be transmitted through client request. In. Net core, this setting can be saved in theappsetting.jsonMedium.below appsetting.json The appid and appcertificate in the code are examples. Please replace them with the corresponding appid and appcertificate you use in use.

{

"AppSettings": {

"AppID": "970CA35de60c44645bbae8a215061b33",

"AppCertificate": "5CFd2fd1755d40ecb72977518be15d3b"

},

"Logging": {

"LogLevel": {

"Default": "Information",

"Microsoft": "Warning",

"Microsoft.Hosting.Lifetime": "Information"

}

},

"AllowedHosts": "*"

}
  1. Create configuration class

In the utils directory, create a AppSettings.cs The contents of the document are as follows:


namespace AgoraTokenServer.Utils

{

public class AppSettings

{

public string AppID { get; set; }

public string AppCertificate { get; set; }

}

}
  1. Injection configuration class

ASP.NET Core uses dependency injection to solve the dependency problem of the whole program. Through this mechanism, we can easily inject the configuration defined above. Dependency injection requires Startup.cs Add a custom configuration class to the file Startup.cs The contents of the document are as follows:

using AgoraTokenServer.Utils;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

namespace AgoraTokenServer

{

public class Startup

{

public Startup(IConfiguration configuration)

{

Configuration = configuration;

}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)

{

services.AddCors (); // add cross domain request

services.AddControllers();

services.Configure <AppSettings>( Configuration.GetSection ("Appsettings"); // add program configuration

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseHttpsRedirection();

app.UseRouting();

app.UseCors(x => x

.AllowAnyOrigin()

.AllowAnyMethod()

.AllowAnyHeader());

app.UseAuthorization();

app.UseEndpoints(endpoints =>

{

endpoints.MapControllers();

});

}

}

}

Create model

We first define two objects to describe what is accepted and what is returned. First create a directory called models, and then create two files in the directory.

  1. Request object file

Path: /Models/AuthenticateRequest.cs

Create in the models directory AuthenticateRequest.cs The contents of the document are as follows:


using System.ComponentModel.DataAnnotations;

namespace AgoraTokenServer.Models

{

public class AuthenticateRequest

{

[Required]

public string channel { get; set; }

[Required]

public dynamic uid { get; set; }

public uint expiredTs { get; set; } = 0;

public int role { get; set; } = 1;

}

}

Because Agora’s user ID has two types, one is uint type and the other is string type, so dynamic type is directly used here to be compatible with both types.

  1. Response object

Path: /Models/AuthenticateResponse.cs

Create in the models directory AuthenticateResponse.cs The contents of the document are as follows:


namespace AgoraTokenServer.Models

{

public class AuthenticateResponse

{

public string channel { get; set; }

public dynamic uid { get; set; }

public string token { get; set; }

}

}
  1. The structure of the project is as follows:

How to set up Agora's accesstoken service on. Net core

Create service

  1. Now we create a controller to provide services. First, create a controller named a in the controllers directory of agoratokenserver project ccessTokenController.cs File.

Path: /Controllers/AccessTokenController.cs


using AgoraTokenServer.Models;

using Microsoft.AspNetCore.Mvc;

namespace AgoraTokenServer.Contollers

{

[ApiController]

[Route("[controller]")]

public class AccessTokenController : ControllerBase

{

}

}
  1. Add program configuration

using AgoraTokenServer.Utils;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Options;

namespace AgoraTokenServer.Contollers

{

[ApiController]

[Route("[controller]")]

public class AccessTokenController : ControllerBase

{

private readonly AppSettings appSettings;

public AccessTokenController(IOptions<AppSettings> appSettings)

{

this.appSettings = appSettings.Value;

}

}

}
  1. Add request processing section

using System.Net;

using System.Text.Json;

using AgoraIO.Media;

using AgoraTokenServer.Models;

using AgoraTokenServer.Utils;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Extensions.Options;

namespace AgoraTokenServer.Contollers

{

[ApiController]

[Route("[controller]")]

public class AccessTokenController : ControllerBase

{

private readonly AppSettings appSettings;

public AccessTokenController(IOptions<AppSettings> appSettings)

{

this.appSettings = appSettings.Value;

}

[HttpPost]

public ActionResult<AuthenticateResponse> index(AuthenticateRequest request)

{

if (string.IsNullOrEmpty(appSettings.AppID) || string.IsNullOrEmpty(appSettings.AppCertificate))

{

return new StatusCodeResult((int)HttpStatusCode.PreconditionFailed);

}

var uid = request.uid.ValueKind == JsonValueKind.Number ? request.uid.GetUInt64().ToString() : request.uid.GetString();

var tokenBuilder = new AccessToken(appSettings.AppID, appSettings.AppCertificate, request.channel, uid);

tokenBuilder.addPrivilege(Privileges.kJoinChannel, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishAudioStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishVideoStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishDataStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kRtmLogin, request.expiredTs);

return Ok(new AuthenticateResponse

{

channel = request.channel,

uid = request.uid,

token = tokenBuilder.build()

});

}

}

}

In the request processing, the code downloaded from agoraio is called directly, and a 412 error will be reported when appid and appcertificate are not configured.

At the same time, the permission of [kjoinchannel, kpublishaudiostream, kpublishvideostream, kpublishdatastream, krtmlogin] is directly given in the sample code. You can add the permission application field in the authenticaterequest according to the direct needs to realize the permission application function.


[HttpPost]

public ActionResult<AuthenticateResponse> index(AuthenticateRequest request)

{

if (string.IsNullOrEmpty(appSettings.AppID) || string.IsNullOrEmpty(appSettings.AppCertificate))

{

return new StatusCodeResult((int)HttpStatusCode.PreconditionFailed);

}

var uid = request.uid.ValueKind == JsonValueKind.Number ? request.uid.GetUInt64().ToString() : request.uid.GetString();

var tokenBuilder = new AccessToken(appSettings.AppID, appSettings.AppCertificate, request.channel, uid);

tokenBuilder.addPrivilege(Privileges.kJoinChannel, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishAudioStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishVideoStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kPublishDataStream, request.expiredTs);

tokenBuilder.addPrivilege(Privileges.kRtmLogin, request.expiredTs);

return Ok(new AuthenticateResponse

{

channel = request.channel,

uid = request.uid,

token = tokenBuilder.build()

});

}

Compile and run

The compilation and operation of. Net core can only be solved through the command line. It can be run directly in the command line under the agoratokenserver directory


dotnet build

You can compile the entire project.

It is also very direct, running directly from the command line


dotnet run

You can go to https://localhost : 5001 and http://localhost : 5000.

If you want to change the default run port, it is recommended to modify it directlyPath: /Properties/launchSettings.jsonThe applicationurl parameter of agoratokenserver section in the file is as follows:


"AgoraTokenServer": {

"commandName": "Project",

"launchBrowser": true,

"launchUrl": "weatherforecast",

"applicationUrl": "https://localhost:5001;http://localhost:5000",

"environmentVariables": {

"ASPNETCORE_ENVIRONMENT": "Development"

}

}

Because of the changes launchSettings.json It will also be published as a configuration file in the final run directory, so that you don’t need to write the port to the source code, or in the Program.cs Additional code has been added to.

test result

In this article, using postman to test the service, you can use the tools you are used to. In specific requests, due to the default values of expiredts and role in the program, they can be ignored in the request. At this stage, role has only one value, so it is recommended to ignore this temporarily. For the specific usage of expiredts, please refer to the instructions in the article “token generation” on Agora’s official website.

How to set up Agora's accesstoken service on. Net core

The specific postman request results are shown in the figure below.

How to set up Agora's accesstoken service on. Net core

If you use postman to send a request, the following error occurs:

How to set up Agora's accesstoken service on. Net core

The reason is that the certificate used by the HTTPS link you are accessing is invalid. In actual use, you need to deploy a real certificate. In the test phase, you can close the first enable SSL certificate verification by using the settings button in the figure below

How to set up Agora's accesstoken service on. Net core

complete

Up to now, Agora token service based on. Net core has been developed. In actual use, you also need to add security mechanism, which can be improved according to your own specific architecture.

For the docker of. Net core, please refer to the article “docker container” of Microsoft.

All the code in this article can be downloaded from GitHub.