In this guide you will learn how to use signed URLs for securing video playback.
If you add an asset or start a live stream through Mux without passing a playback policy, you'll be unable to access it in your browser using a URL. This may seem counterintuitive at first, however, this gives you the ability to be explicit about who can access your content, as well as exactly how, where, or when they can access it.
There may be instances where you upload a video to Mux that is not intended to be made available for public viewing. For example, maybe you have a membership site that your users must join to access your videos, or you are offering a pay-to-access live stream.
For these scenarios, Mux offers playback policies that allow you to control the different ways users can view and interact with your content.
When you upload a video or initiate a live stream through Mux, you also have the option to define what type of fine-grained access should apply to your content. This is done by specifying a playback policy.
Mux offers two kinds of playback policies: public
and signed
.
A playback policy can be specified when you create a new asset or live stream, or can be added to an existing asset or live stream.
Once an asset or live stream has been assigned a playback policy, the asset will be issued a new playback ID that's associated with its corresponding playback policy. It's possible for each asset or live stream to have multiple playback IDs.
See Create a playback IDAPI to learn how to add a new playback policy and ID to an existing Asset or Live Stream.
Public playback policies are pretty self-explanatory, so let’s dig into the signed playback policies.
When you apply a signed playback policy to your content, there are two distinct ways you can restrict video playback:
Referrer and User-Agent Validation Playback Restrictions are supported today; Mux plans to add more types of restrictions in the future.
Let’s walk through a typical workflow for creating a valid JWT used to access a Mux asset with a signed playback policy.
Let’s start from scratch and add a new asset to our Mux account using a standard authenticated API call. Notice how we set the playback_policy
value to signed
during this Create Asset request:
// POST https://api.mux.com/video/assets
{
"input": "https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4",
"playback_policy": "signed",
"video_quality": "basic"
}
Next, we'll need to create a Mux signing key. Signing keys are used to generate valid JWTs for accessing your content. Signing keys can be managed (created, deleted, listed) from the Signing Keys settings of the Mux dashboard or via the Mux System API.
Remember: Mux signing keys are different than Mux API keys.
When you create a new signing key, the API generates a 2048-bit RSA key-pair and returns the private key and a generated key-id. You should securely store the private key for signing the token, while Mux stores the public key to validate the signed tokens.
Signing keys are created and deleted independently of assets. You probably only need one signing key active at a time, but you can create multiple to enable key rotation, creating a new key and deleting the old one only after any existing signed URLs have expired.
See Create a URL signing keyAPI for full documentation.
//POST https://api.mux.com/system/v1/signing-keys
{
"data": {
"private_key": "(base64-encoded PEM file with private key)",
"id": "(unique signing-key identifier)",
"created_at": "(UNIX Epoch seconds)"
}
}
Mux supports two types of playback restriction:
Referer
request header or when no referrer domain is specified will be allowed for playback.User-Agent
request header or when no user agent is specifed will be allowed for playback.During playback, a restriction is applied using a JWT claim, which will be covered in the next two sections.
Playback restrictions exist at the environment level. However, creating a playback restriction in an environment does not mean all assets are automatically restricted by it.
Instead, you should apply a given restriction to a playback by referencing it in the token you create for a signed playback ID.
If you don’t need to use playback restrictions for your content, feel free to jump to the next step.
Most commonly, you want all the videos on your Mux account to be watched only on your website https://example.com
. To do so, you can create a new Playback Restriction by adding example.com
domain as the only allowed domain that can play your videos.
See Playback RestrictionAPI for full documentation.
//POST https://api.mux.com/video/v1/playback-restrictions
{
"referrer": {
"allowed_domains" : [
"example.com"
],
"allow_no_referrer" : false
}
}
{
"data": {
"updated_at": "1634595679",
"referrer": {
"allowed_domains": [
"example.com"
],
},
"id": "JL88SKXTr7r2t9tovH7SoYS8iLBVsjZ2qTuFS8NGAQY",
"created_at": "1634595679"
}
}
Store the id
value from the API response above as PLAYBACK_RESTRICTION_ID
in your application for later use when generating the signed JWT.
When you create a playback restriction, you may specify the referrer domains and/or user agent restrictions in the same request. The referrer
field allows you to specify the referrer restrictions and the user_agent
field allows you to specify the user agent restrictions. For the referrer allowed_domains
list, you may specify up to 100 unique domains or subdomains where your videos will be embedded. Specify this in the referrer.allowed_domains
array using valid DNS-style wildcard syntax. For example:
{
"referrer": {
"allowed_domains": [
"*.example.com",
"foo.com"
]
"allow_no_referrer": false,
},
"user_agent": {
"allow_no_user_agent": false,
"allow_high_risk_user_agent": false,
}
}
Choose from the following options:
[]
example.com
and all the subdomains of example.com
, use the syntax: ["*.example.com", "example.com"]
*
entry to allow video playback requests from any domain: ["*"]
xyz.foo.example.com
when you include ["*.example.com"]
.Here are some things to consider when using Playback Restrictions.
You can create up to 100 different Playback Restrictions per environment on your Mux account.
You can use a Playback Restriction ID for playing a single video or a group of videos.
You have a lot of flexibility for associating Playback Restrictions with videos. For instance, you can create one Playback Restriction for each of your clients if your service or application supports multiple clients.
You can add up to 100 different domains to each Playback Restriction.
You can restrict playing video on domains added to the Playback Restriction. For instance, if you want multiple partner sites to play a video, you can add the partner site domain to the same Playback Restriction, thereby restricting playback only on those domains.
If your player supports Chromecast, like Mux Player, make sure you add the Chromecast domain (www.gstatic.com
) to your playback restrictions, otherwise casting will fail.
if your player supports Airplay, like Mux Player, you will only be able to Airplay to third party devices by adding the Airplay domain (mediaservices.cdn-apple.com
) to your playback restrictions. Because first-party Apple devices never forward the referrer header, allow_no_referrer
must be set to true in order to work on those devices, otherwise airplaying will fail.
Reach out to Mux Support if you have a use case that requires more than 100 Playback Restrictions or want to add more than 100 domains per Playback Restriction.
Referer
HTTP Header for validationWeb browsers send the website address requesting the video in the Referer
HTTP header.
Mux matches the domains configured in the Playback Restriction, with the domain in the Referer
HTTP header. No video is delivered if there is no match.
The Referer
HTTP header is only sent by web browsers, while native iOS and Android applications do not send this header. Therefore, Mux cannot perform domain validations on any requests from native iOS and Android applications. For this reason, you can configure the Playback Restrictions to allow or deny all HTTP requests without the Referer
HTTP header by setting the allow_no_referrer
boolean parameter.
First party Apple devices, like Apple TV 4K, never set a referrer header regardless of the source. Therefore if airplaying to first party Apple devices is required then allow_no_referrer
will need to be set to true
in order to succeed.
Please note that setting allow_no_referrer
to true
can result in content playback from unauthorised locations. As such, we strongly recommend creating two Playback Restriction objects, one with allow_no_referrer
set to true
, and one set to false
, and setting the appropriate Playback Restriction ID in the JWT for Web vs. native iOS and/or Android applications.
User-Agent
HTTP Header for validationThe User-Agent
HTTP header value is used to validate against a playback restriction. If the allow_no_user_agent
field is set to false, the playback will be denied if the request does not include an User-Agent
value. For the allow_high_risk_user_agent
validation, Mux maintains a list of user agents that have been known to be associated with higher risk video playback, such as playback devices that are not associated with legitimate end users of most systems. For more information, please reach out to Mux Support.
All signed requests have a JWT with the following standard claims:
Claim Code | Description | Value |
---|---|---|
sub | Subject of the JWT | Mux Video Playback ID |
aud | Audience (intended application of the token) | v (Video or Subtitles/Closed Captions) t (Thumbnail) g (GIF) s (Storyboard) d (DRM License) |
exp | Expiration time | UNIX Epoch seconds when the token expires. This should always exceed the current-time plus the duration of the video, else portions of the video may be unplayable. |
kid | Key Identifier | Key ID returned when signing key was created |
You can also include the following optional claims depending on the type of request.
Claim Code | Description | Value |
---|---|---|
playback_restriction_id | Playback Restriction Identifier | PLAYBACK_RESTRICTION_ID from the previous step. Mux performs validations when the PLAYBACK_RESTRICTION_ID is present to the JWT claims body. This claim is supported for all aud types. |
The Image (Thumbnails, Animated GIFs, Storyboard and others) API accepts several options to control image selection and transformations. More details on generating JWT for image can be found here.
For Playback IDs that use a public policy, the thumbnail options are supplied as query parameters on the request URL.
For Playback IDs that use a signed policy, the thumbnail options must be specified in the JWT claims when using signed URLs. This ensures that the thumbnail options are not altered, such as changing the timestamp or the dimensions of the thumbnail image. For example, if you uploaded a 4K video and wanted to restrict a thumbnail to a width of 600 pixels and a specific timestamp, then simply include the width
and time
keys in the JWT claims.
Expiration time should be at least the duration of the Asset or the expected duration of the Live Stream. When the signed URL expires, the URL will no longer be playable, even if playback has already started. Make sure you set the expiration to be sufficiently far in the future so that users do not experience an interruption in playback.
Your application should consider cases where the user loads a video, leaves your application, then comes back later and tries to play the video again. You will likely want to detect this behavior and make sure you fetch a new signed URL to make sure playback can start.
The steps can be summarized as:
There are dozens of software libraries for creating & reading JWTs. Whether you’re writing in Go, Elixir, Ruby, or a dozen other languages, don’t fret, there is most likely some JWT library you can rely on.
The following examples assuming you're working with either a private key returned from the Signing Keys APIAPI, or copy & pasted from the Dashboard, not when downloaded as a PEM file.
package main
import (
"encoding/base64"
"fmt"
"log"
"time"
"github.com/golang-jwt/jwt/v4"
)
func main() {
playbackId := "" // Enter your signed playback id here
keyId := "" // Enter your signing key id here
key := "" // Enter your base64 encoded private key here
decodedKey, err := base64.StdEncoding.DecodeString(key)
if err != nil {
log.Fatalf("Could not base64 decode private key: %v", err)
}
signKey, err := jwt.ParseRSAPrivateKeyFromPEM(decodedKey)
if err != nil {
log.Fatalf("Could not parse RSA private key: %v", err)
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"sub": playbackId,
"aud": "v",
"exp": time.Now().Add(time.Minute * 15).Unix(),
"kid": keyId,
})
tokenString, err := token.SignedString(signKey)
if err != nil {
log.Fatalf("Could not generate token: %v", err)
}
fmt.Println(tokenString)
}
Supply the JWT in the resource URL using the token
query parameter. The Mux Video service will inspect and validate the JWT to make sure the request is allowed.
Video URL example:
https://stream.mux.com/{playback-id}.m3u8?token={JWT}
Thumbnail options are supplied as query parameters when using a public policy. When using a signed policy, the thumbnail options must be specified as claims in the JWT following the same naming conventions as with query parameters.
Thumbnail URL example:
https://image.mux.com/{playback-id}/thumbnail.{format}?token={JWT}
Passing token
for public playback IDs will fail
If you include a token=
query parameter for a "public"
playback ID, the URL will fail. This is intentional as to not create the false appearance of security when using a public playback ID.
If your application uses a mix of "public" and "signed" playback IDs, you should save the playback policy type in your database and include the token parameter only for the signed playbacks.
When you're signing a URL, you're signing the parameters for that URL as well. After the parameters are signed for a playback ID, the resulting signed URL should only contain the token
parameter. This is important because leaving the parameters in the URL would both:
Be sure to include params
in your claims
body
While the JWT helper we expose in our Node SDK passes in additional parameters as an extra hash, when working with the JWT directly, these params
should be embedded directly in your claims
body.
Let's say we're taking the following public example and making a signed URL:
https://image.mux.com/{public_playback_id}/thumbnail.jpg?time=25
Generate a signed URL with {time: 25}
in the claims body. Using the helper example we wrote above, this would look like:
sign(signedPlaybackId, { ...requiredTokenOptions, params: { time: 25 } })
Correct Signed URL:
https://image.mux.com/{signed_playback_id}/thumbnail.jpg?token={token}
Bad Signed URL:
https://image.mux.com/{signed_playback_id}/thumbnail.jpg?time=25&token={token}
Including query parameters in the token also applies to playback modifiers like default_subtitles_lang
, redundant_streams
and roku_trick_play
. The JWT claims body must include the extra parameter:
{
"sub": "{PLAYBACK_ID}",
"aud": "{AUDIENCE_TYPE}",
"exp": "{EXPIRATION_TIME}",
"redundant_streams": true
}
With signed URLs, you can pass extra parameters via a custom
key in the claims body like the example above.
This may be useful in order to identify bad actors that share signed URLs in an unauthorized way outside of your application. If you find out that a signed URL gets shared then you can decode the parameters and trace it back to the user who shared it. When including extra parameters like this, be sure to respect the following guidelines:
"custom"
key.{
"sub": "{PLAYBACK_ID}",
"aud": "{AUDIENCE_TYPE}",
"exp": "{EXPIRATION_TIME}",
"custom": {
"session_id": "xxxx-123"
}
}