.NET#
This is a minimal server application built for .NET with ASP.NET Core Minimal APIs that allows:
- Generating LiveKit tokens on demand for any application client.
- Receiving LiveKit webhook events.
Unfortunately there is no .NET SDK for LiveKit available, so the application has to manually build LiveKit compatible JWT tokens using the .NET library System.IdentityModel.Tokens.Jwt
, and check the validity of webhook events on its own. It is a fairly easy process.
Running this application#
Download the tutorial code:
To run this server application, you need .NET installed on your device.
- Navigate into the server directory
- Run the application
Warning
This .NET server application needs the LIVEKIT_API_SECRET
env variable to be at least 32 characters long. Make sure to update it here and in your OpenVidu Server.
Info
You can run any Application Client to test against this server right away.
Understanding the code#
The application is a simple ASP.NET Core Minimal APIs app with a single file Program.cs
that exports two endpoints:
/token
: generate a token for a given Room name and Participant name./livekit/webhook
: receive LiveKit webhook events.
Let's see the code Program.cs
file:
Program.cs | |
---|---|
|
- A
WebApplicationBuilder
instance to build the application. - The name of the CORS policy to be used in the application.
- A
IConfiguration
instance to load the configuration from theappsettings.json
file, including the required environment variables. - The port where the application will be listening.
- The API key of LiveKit Server.
- The API secret of LiveKit Server.
- Configure CORS support.
- Configure the port.
- Build the application and enable CORS support.
The Program.cs
file imports the required dependencies and loads the necessary environment variables (defined in appsettings.json
file):
SERVER_PORT
: the port where the application will be listening.LIVEKIT_API_KEY
: the API key of LiveKit Server.LIVEKIT_API_SECRET
: the API secret of LiveKit Server.
Finally the application enables CORS support and the port where the application will be listening.
Create token#
The endpoint /token
accepts POST
requests with a payload of type application/json
, containing the following fields:
roomName
: the name of the Room where the user wants to connect.participantName
: the name of the participant that wants to connect to the Room.
Program.cs | |
---|---|
|
- The endpoint obtains a Dictionary from the body request, and check if fields
roomName
andparticipantName
are available. - Create a new JWT token with the room and participant name.
- Return the token to the client.
- Return a
400
error if required fields are not available.
The endpoint obtains a Dictionary from the body request, and check if fields roomName
and participantName
are available. If not, it returns a 400
error.
If required fields are available, a new JWT token is created. Unfortunately there is no .NET SDK for LiveKit, so we need to create the JWT token manually. The CreateLiveKitJWT
method is responsible for creating the LiveKit compatible JWT token:
Program.cs | |
---|---|
|
- Create a new
JwtHeader
withLIVEKIT_API_SECRET
as the secret key and HS256 as the encryption algorithm. - Create a new Dictionary with the video grants for the participant.
roomJoin
allows the user to join a room androom
determines the specific room. Check out all Video Grants. - Set the expiration time of the token. LiveKit default's is 6 hours.
- Set the API key of LiveKit Server as the issuer (
iss
) of the token. - The
Not before
field (nbf
) sets when the token becomes valid (0 for immediately valid). - Set the participant's name in the claims
sub
andname
. - Finally, the returned token is sent back to the client.
This method uses the native System.IdentityModel.Tokens.Jwt
library to create a JWT token valid for LiveKit. The most important field in the JwtPayload is video
, which will determine the VideoGrant permissions of the participant in the Room. You can also customize the expiration time of the token by changing the exp
field, and add a metadata
field for the participant. Check out all the available claims.
Finally, the returned token is sent back to the client.
Receive webhook#
The endpoint /livekit/webhook
accepts POST
requests with a payload of type application/webhook+json
. This is the endpoint where LiveKit Server will send webhook events.
Program.cs | |
---|---|
|
- The raw string body of the request contains the webhook event.
- The
Authorization
header is required to validate the webhook event. - Verify the webhook event.
- Consume the event as you whish.
- Return a response to LiveKit Server to let it know that the webhook was received correctly.
The endpoint receives the incoming webhook event and validates it to ensure it is coming from our LiveKit Server. For that we need the raw string body and the Authorization
header of the request. After validating it, we can consume the event (in this case, we just log it), and we must also return a 200
OK response to LiveKit Server to let it know that the webhook was received correctly.
Unfortunately there is no .NET SDK for LiveKit, so we need to manually validate the webhook event. The VerifyWebhookEvent
method does that:
Program.cs | |
---|---|
|
- Use the
LIVEKIT_API_SECRET
as the secret key to validate the token. - Set the
LIVEKIT_API_KEY
as the issuer of the token. - Validate the
Authorization
header with the recently createdTokenValidationParameters
. If theLIVEKIT_API_SECRET
orLIVEKIT_API_KEY
of the LiveKit Server that sent the event do not match the ones in the application, this will throw an exception. - Calculate the SHA256 hash of the body and compare it with the
sha256
claim in the token. If they match, it means the webhook event was not tampered and we can trust it.
We need a TokenValidationParameters
object from the Microsoft.IdentityModel.Tokens
namespace. We use the LIVEKIT_API_SECRET
as the symmetric key, and the LIVEKIT_API_KEY
as the issuer of the token.
If method JwtSecurityTokenHandler#ValidateToken
does rise an exception when validating the Authorization
header, it means the webhook event was sent by a LiveKit Server with different credentials.
Finally, we calculate the SHA256 hash of the body and compare it with the sha256
claim in the token. If they match, it means the webhook event was not tampered and we can definitely trust it.
From production to a local server#
When developing locally pointing to a production deployment and webhooks events are required by your application, you might face issues because OpenVidu cannot access your local server.
To receive webhooks from OpenVidu on your local machine, you need to expose your local server to the internet. This exposure allows OpenVidu to send webhooks directly to your local server.
The following images illustrate the difference between an unreachable local server and a reachable local server:
Exposing your local server to the internet is a common practice when developing applications locally. Tools like Ngrok, LocalTunnel, LocalXpose and Zrok can help you achieve this.
These tools provide you with a public URL that forwards requests to your local server. You can use this URL to receive webhooks from OpenVidu. For information on how to add this URL as the webhook URL in the OpenVidu deployment, refer to the following documentation:
- Configure webhooks for an OpenVidu Local deployment. Learn more.
- Configure webhooks for an OpenVidu Single Node deployment. Learn more.
-
Configure webhooks for an OpenVidu Elastic On-Premises deployment. Learn more.
-
Configure webhooks for an OpenVidu Elastic AWS deployment. Learn more.
-
Configure webhooks for an OpenVidu High Availability On-Premises deployment. Learn more.
-
Configure webhooks for an OpenVidu High Availability AWS deployment. Learn more.