Grants
With protected playback by customer grants, your backend decides which viewers may watch: it signs each viewer's grant with a key of its own.
Only for a site on customer grants. Your backend vouches for each viewer with a grant, a one-time credential that the player exchanges for a short-lived playback session. Your backend signs each grant itself, with a key pair of its own, so signing takes no request to Spine and Spine sets no limit on how many grants you sign.
Each grant is used once, for one site, and lasts as long as you set: at least 5 minutes and at most 24 hours. It opens any channel Spine has assigned to the site, unless you limit it to one channel. Security and access explains the protection levels.
To set it up:
- Get a key pair, and give Spine its public key (Your grant key).
- Add an endpoint to your backend that signs a grant for each viewer (Your endpoint for the player, with examples).
- Have your page hand the grants to the player: see Hosted script or Iframe embed.
The flow
- Your backend is the only judge of who may watch. Spine never calls your servers.
- One grant, one use. A grant starts or renews one session, once, before it expires. Sign a new one for each viewer and each renewal; never cache or share them.
- Renewal repeats the check. The player renews about every four minutes, and each renewal needs a fresh grant from your backend. So a viewer you stop vouching for, such as one whose subscription ends, can’t renew: they stop playing when the media credentials from their last session or renewal expire, up to five minutes later. Any grants your backend already handed them still work until they’re spent or expire.
Your endpoint for the player
Your page needs an endpoint on your own backend that it can ask for a grant whenever the player needs one. Its shape is yours. A typical one:
POST /api/spine/grant (behind your own login: your session cookie or token)
{ "channel": "spor-1" }
200 { "grant": "…" } Cache-Control: no-store
401 the viewer isn't signed in
403 the viewer may not watch
503 no grant could be had; try again shortly
It should:
- Authenticate the viewer with your own login, as for any private page.
- Check the entitlement: subscription, region, age, whatever your business requires.
- Sign the grant with your private key (see The grant and the examples). Return it with
Cache-Control: no-store. - Never log the grant, nor put it in a URL.
Your page then hands the grant to the player: see Hosted script, Iframe embed or npm packages.
How often it's called, and the channel it's sent
Expect about one call per viewer every four minutes while they watch, and one each time a viewer starts or switches channel. The player also asks for a fresh grant when what it plays changes, as when Spine’s schedule moves a channel between low and standard latency, and when it restarts the stream after a failure.
The page can send the slug of the channel the player plays, as channel. Your backend needs it only if it limits grants to one channel: a grant that names no channel opens any channel your site is assigned, the one a viewer switches to with the channel selector included.
Your grant key
Your backend signs grants with the private half of a key pair, and Spine checks each one with the public half, your grant key. Use an ES256 key (elliptic curve P-256) or an Ed25519 key. If you’re not sure, use ES256: every example below signs with it, using each language’s usual libraries.
Make a key pair
Spine can make the pair for you, or you can make it yourself.
Ask Spine for a grant key, and say whether you want ES256 or Ed25519. Spine makes an ES256 key unless you ask for Ed25519. Spine sends you:
- The private key, as a file named by its key ID, such as
spine-grant-key-gkey_01jdm9t4bq6w8y0a2c4e6g8j0m.pem. It’s PEM text, as OpenSSL writes it. The examples below read and sign with an ES256 key as written; for an Ed25519 key, use your library’s EdDSA loader and signer, as the Node.js, Python and Go examples note. - Its key ID, such as
gkey_01jdm9t4bq6w8y0a2c4e6g8j0m. Each grant you sign names it.
Spine makes the pair in the browser of the admin who sends it, so the private key never reaches Spine’s servers, and Spine keeps only the public key. Agree with Spine on a secure way to receive the file, such as an item shared from a password manager, never plain email or chat: anyone who gets a copy can sign grants for your sites. Move it into your secrets manager as soon as it arrives, and delete every other copy, such as the one in your downloads folder.
Make the pair with OpenSSL, and send Spine only the public key. The private key then never leaves your servers, so nothing secret passes between you and Spine.
For an ES256 key:
# The private key: keep it on your servers, in your secrets manager.
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out spine-grant-key.pem
# The public key, for Spine.
openssl pkey -in spine-grant-key.pem -pubout -out spine-grant-key.pub.pem
cat spine-grant-key.pub.pemFor an Ed25519 key:
# The private key: keep it on your servers, in your secrets manager.
openssl genpkey -algorithm ed25519 -out spine-grant-key.pem
# The public key, for Spine.
openssl pkey -in spine-grant-key.pem -pubout -out spine-grant-key.pub.pem
cat spine-grant-key.pub.pemThe public key is a few lines of text:
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFFn/q05zCpLn2wx/GlUOMb8HOwKJ
fq14jhwpH0p0aPfjsS45FnnowIz+oIzVXwqRskQbgUUknlXkPQLUv2zl3A==
-----END PUBLIC KEY-----Send Spine the public key, its BEGIN and END lines included. A JSON Web Key (JWK) works too. Spine refuses a key with a private part, so you can’t send the wrong half by mistake. Spine sends you its key ID, such as gkey_01jdm9t4bq6w8y0a2c4e6g8j0m. Each grant you sign names it.
Check Spine has the right key
Ask Spine for its fingerprint, and compare it with the first 16 characters this prints:
openssl pkey -pubin -in spine-grant-key.pub.pem -outform DER | openssl dgst -sha256Rotate and remove keys
- One key signs grants for any of your sites.
- Two keys at most can be active, so you can rotate without downtime:
- Get a new key pair, from Spine or by making one (see Make a key pair).
- Deploy the new private key and its key ID to every server that signs grants.
- Ask Spine to confirm the old key is no longer used. Spine sees when each key last signed a grant, to within an hour.
- Ask Spine to remove the old key. A removed key stops working at once: Spine refuses every grant it signed from then on.
- If a private key leaks, ask Spine to remove its public key straight away, then rotate.
The grant
A grant is a JSON Web Token (JWT), signed with your private key. Its header:
| Field | Value |
|---|---|
alg |
ES256 for a P-256 key, EdDSA for an Ed25519 key |
kid |
the key’s ID, gkey_ and 26 characters, as Spine sent it |
Its claims:
| Claim | Value |
|---|---|
aud |
"spine:grant" |
emb |
the site’s embed ID in full: emb_ and 26 characters |
chan |
optional: the one channel the grant opens, by its slug, such as spor-1. Without it, the grant opens any channel your site is assigned. See Limit a grant to one channel. |
jti |
an ID of your own for this grant, 16 to 128 characters, that you’ve never used with this key before. A random UUID will do. |
iat |
when you signed it, in Unix seconds |
exp |
when it expires, in Unix seconds: at least 300 seconds (5 minutes) and at most 86,400 seconds (24 hours) after iat |
Sign each grant when the player asks for it, for 5 minutes unless your setup needs longer. However long it lasts, a grant opens one session, once. But a viewer you stop vouching for can keep playing on grants your backend has already handed out until they expire, so a longer grant delays when your decision takes effect. Every example below signs for 5 minutes.
A decoded grant
{ "alg": "ES256", "kid": "gkey_01jdm9t4bq6w8y0a2c4e6g8j0m", "typ": "JWT" }{
"aud": "spine:grant",
"emb": "emb_01jdm8q3vz5k7r2x9c4n6b8t0w",
"jti": "0b6f3c2e-9a41-4d7e-8f15-6c2d1e9a7b30",
"iat": 1796290200,
"exp": 1796290500
}What Spine checks
Spine takes a grant only if:
- its signature checks out with one of your keys, with the
algthat key signs with, and itskidnames that key; - the site is one of yours, and the channel the player asks for is assigned to it, and is the one
channames, if it names one; - it lasts at least 5 minutes and at most 24 hours, from
iattoexp; - it hasn’t expired, and its
iatis no more than a minute ahead of Spine’s clock, so keep your servers’ clocks in sync; - it hasn’t been used: Spine takes each grant once, and refuses its
jtiwith the same key from then on.
Examples
Each example is an endpoint like the one in Your endpoint for the player: it checks your viewer, signs a grant that opens any channel your site is assigned, and returns { grant }. They read the private key’s PEM text from SPINE_GRANT_PRIVATE_KEY, its key ID from SPINE_GRANT_KEY_ID and the site’s embed ID from SPINE_EMBED_ID.
With jose and Express, in TypeScript:
// spine-grants.ts
import { randomUUID } from "node:crypto";
import { SignJWT, importPKCS8 } from "jose";
// Your private key's PEM text and its key ID (gkey_…), from your secrets manager or environment.
const PRIVATE_KEY = importPKCS8(process.env.SPINE_GRANT_PRIVATE_KEY!, "ES256");
const KEY_ID = process.env.SPINE_GRANT_KEY_ID!;
export async function signGrant(embedId: string): Promise<string> {
const now = Math.floor(Date.now() / 1000);
return new SignJWT({ emb: embedId })
.setProtectedHeader({ alg: "ES256", kid: KEY_ID })
.setAudience("spine:grant")
.setJti(randomUUID())
.setIssuedAt(now)
.setExpirationTime(now + 300)
.sign(await PRIVATE_KEY);
}// routes/spine.ts
import express from "express";
import { signGrant } from "../spine-grants";
const EMBED_ID = process.env.SPINE_EMBED_ID!; // this site's embed ID, emb_…
export const spine = express.Router();
spine.post("/api/spine/grant", async (req, res) => {
const viewer = req.user; // from your own authentication middleware
if (!viewer) return res.status(401).end();
if (!(await mayWatch(viewer))) return res.status(403).end();
res.set("cache-control", "no-store").json({ grant: await signGrant(EMBED_ID) });
});
declare function mayWatch(viewer: unknown): Promise<boolean>; // your entitlement checkFor an Ed25519 key, write "EdDSA" for "ES256" in both places.
With PyJWT and cryptography, and Flask:
# spine_grants.py
import os
import time
import uuid
import jwt # PyJWT, with cryptography installed
# Your private key's PEM text and its key ID (gkey_…), from your secrets manager or environment.
PRIVATE_KEY = os.environ["SPINE_GRANT_PRIVATE_KEY"]
KEY_ID = os.environ["SPINE_GRANT_KEY_ID"]
def sign_grant(embed_id: str) -> str:
now = int(time.time())
claims = {
"aud": "spine:grant",
"emb": embed_id,
"jti": str(uuid.uuid4()),
"iat": now,
"exp": now + 300,
}
return jwt.encode(claims, PRIVATE_KEY, algorithm="ES256", headers={"kid": KEY_ID})# app.py
import os
from flask import Flask, abort, jsonify
from spine_grants import sign_grant
app = Flask(__name__)
EMBED_ID = os.environ["SPINE_EMBED_ID"] # this site's embed ID, emb_…
@app.post("/api/spine/grant")
def spine_grant():
viewer = current_viewer() # your own authentication
if viewer is None:
abort(401)
if not may_watch(viewer): # your entitlement check
abort(403)
response = jsonify(grant=sign_grant(EMBED_ID))
response.headers["Cache-Control"] = "no-store"
return responseFor an Ed25519 key, write algorithm="EdDSA".
With firebase/php-jwt (composer require firebase/php-jwt):
<?php
// spine_grant.php
use Firebase\JWT\JWT;
function spine_sign_grant(string $embedId): string
{
$now = time();
$claims = [
'aud' => 'spine:grant',
'emb' => $embedId,
'jti' => bin2hex(random_bytes(16)),
'iat' => $now,
'exp' => $now + 300,
];
// Your private key's PEM text and its key ID (gkey_…), from your secrets manager or environment.
return JWT::encode($claims, getenv('SPINE_GRANT_PRIVATE_KEY'), 'ES256', getenv('SPINE_GRANT_KEY_ID'));
}<?php
// api/spine/grant.php: POST, behind your own login
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../spine_grant.php';
$viewer = current_viewer(); // your own authentication
if ($viewer === null) {
http_response_code(401);
exit;
}
if (!may_watch($viewer)) { // your entitlement check
http_response_code(403);
exit;
}
header('Cache-Control: no-store');
header('Content-Type: application/json');
echo json_encode(['grant' => spine_sign_grant(getenv('SPINE_EMBED_ID'))]);With golang-jwt/jwt/v5:
package spine
import (
"crypto/ecdsa"
"crypto/rand"
"encoding/hex"
"encoding/json"
"net/http"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
// GrantSigner signs this site's grants with your private key.
type GrantSigner struct {
key *ecdsa.PrivateKey
keyID string // gkey_…, as Spine sent it
embedID string // this site's embed ID, emb_…
}
func NewGrantSigner() (*GrantSigner, error) {
// Your private key's PEM text, from your secrets manager or environment.
key, err := jwt.ParseECPrivateKeyFromPEM([]byte(os.Getenv("SPINE_GRANT_PRIVATE_KEY")))
if err != nil {
return nil, err
}
return &GrantSigner{
key: key,
keyID: os.Getenv("SPINE_GRANT_KEY_ID"),
embedID: os.Getenv("SPINE_EMBED_ID"),
}, nil
}
func (s *GrantSigner) Sign() (string, error) {
jti := make([]byte, 16)
if _, err := rand.Read(jti); err != nil {
return "", err
}
now := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
"aud": "spine:grant",
"emb": s.embedID,
"jti": hex.EncodeToString(jti),
"iat": now.Unix(),
"exp": now.Add(5 * time.Minute).Unix(),
})
token.Header["kid"] = s.keyID
return token.SignedString(s.key)
}
// ServeHTTP answers POST /api/spine/grant, behind your own login.
func (s *GrantSigner) ServeHTTP(w http.ResponseWriter, r *http.Request) {
viewer, ok := viewerFrom(r) // your own authentication
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
if !mayWatch(viewer) { // your entitlement check
w.WriteHeader(http.StatusForbidden)
return
}
grant, err := s.Sign()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"grant": grant})
}For an Ed25519 key, read it with jwt.ParseEdPrivateKeyFromPEM and sign with jwt.SigningMethodEdDSA.
Java 17 or later, with Jackson and the JDK’s own cryptography:
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
public final class SpineGrantSigner {
private static final ObjectMapper JSON = new ObjectMapper();
private static final Base64.Encoder BASE64URL = Base64.getUrlEncoder().withoutPadding();
private final PrivateKey key;
private final String keyId;
/** {@code pem}: your private key's PEM text. {@code keyId}: its key ID (gkey_…), as Spine sent it. */
public SpineGrantSigner(String pem, String keyId) throws GeneralSecurityException {
String base64 = pem.replaceAll("-----[A-Z ]+-----", "").replaceAll("\\s", "");
this.key = KeyFactory.getInstance("EC")
.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64)));
this.keyId = keyId;
}
public String sign(String embedId) throws Exception {
long now = Instant.now().getEpochSecond();
Map<String, Object> header = Map.of("alg", "ES256", "typ", "JWT", "kid", keyId);
Map<String, Object> claims = Map.of(
"aud", "spine:grant",
"emb", embedId,
"jti", UUID.randomUUID().toString(),
"iat", now,
"exp", now + 300);
String input = part(header) + "." + part(claims);
// JWS wants the signature as r and s side by side (P1363), not Java's default DER.
Signature signer = Signature.getInstance("SHA256withECDSAinP1363Format");
signer.initSign(key);
signer.update(input.getBytes(StandardCharsets.US_ASCII));
return input + "." + BASE64URL.encodeToString(signer.sign());
}
private static String part(Map<String, Object> value) throws Exception {
return BASE64URL.encodeToString(JSON.writeValueAsBytes(value));
}
}Your endpoint, with Spring:
import java.security.Principal;
import java.util.Map;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpineGrantController {
private static final String EMBED_ID = System.getenv("SPINE_EMBED_ID"); // this site's, emb_…
private final SpineGrantSigner signer;
public SpineGrantController() throws Exception {
signer = new SpineGrantSigner(
System.getenv("SPINE_GRANT_PRIVATE_KEY"), System.getenv("SPINE_GRANT_KEY_ID"));
}
@PostMapping("/api/spine/grant")
public ResponseEntity<Map<String, String>> grant(Principal viewer) throws Exception {
if (viewer == null) return ResponseEntity.status(401).build(); // your own authentication
if (!mayWatch(viewer)) return ResponseEntity.status(403).build();
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(Map.of("grant", signer.sign(EMBED_ID)));
}
private boolean mayWatch(Principal viewer) {
return true; // your entitlement check
}
}For .NET 8, with ASP.NET Core and nothing else:
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
public sealed class SpineGrantSigner : IDisposable
{
private readonly ECDsa _key = ECDsa.Create();
private readonly string _keyId;
public SpineGrantSigner(IConfiguration config)
{
// Your private key's PEM text and its key ID (gkey_…), from user secrets or your secret store.
_key.ImportFromPem(config["Spine:GrantPrivateKey"]);
_keyId = config["Spine:GrantKeyId"]!;
}
public string Sign(string embedId)
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var header = Encode(new { alg = "ES256", typ = "JWT", kid = _keyId });
var claims = Encode(new
{
aud = "spine:grant",
emb = embedId,
jti = Guid.NewGuid().ToString(),
iat = now,
exp = now + 300,
});
var input = $"{header}.{claims}";
// .NET signs ECDSA as r and s side by side (IEEE P1363), the form JWS wants.
var signature = _key.SignData(Encoding.ASCII.GetBytes(input), HashAlgorithmName.SHA256);
return $"{input}.{Base64Url(signature)}";
}
private static string Encode<T>(T value) => Base64Url(JsonSerializer.SerializeToUtf8Bytes(value));
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
public void Dispose() => _key.Dispose();
}Your endpoint, in Program.cs, with the key and IDs in configuration (Spine:GrantPrivateKey, Spine:GrantKeyId and Spine:EmbedId):
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(); // your own authentication
builder.Services.AddAuthorization();
builder.Services.AddSingleton<SpineGrantSigner>();
var app = builder.Build();
var embedId = app.Configuration["Spine:EmbedId"]!; // this site's embed ID, emb_…
app.MapPost("/api/spine/grant", (ClaimsPrincipal viewer, SpineGrantSigner signer, HttpResponse response) =>
{
if (!MayWatch(viewer)) return Results.StatusCode(403); // your entitlement check
response.Headers.CacheControl = "no-store";
return Results.Ok(new { grant = signer.Sign(embedId) });
}).RequireAuthorization();
app.Run();
static bool MayWatch(ClaimsPrincipal viewer) => true;With the jwt gem:
# spine_grants.rb
require "jwt"
require "openssl"
require "securerandom"
module Spine
# Your private key's PEM text and its key ID (gkey_…), from your secrets manager or environment.
GRANT_KEY = OpenSSL::PKey.read(ENV.fetch("SPINE_GRANT_PRIVATE_KEY"))
GRANT_KEY_ID = ENV.fetch("SPINE_GRANT_KEY_ID")
def self.sign_grant(embed_id)
now = Time.now.to_i
claims = {
aud: "spine:grant",
emb: embed_id,
jti: SecureRandom.uuid,
iat: now,
exp: now + 300
}
JWT.encode(claims, GRANT_KEY, "ES256", { kid: GRANT_KEY_ID })
end
endYour endpoint, in Rails:
# app/controllers/spine_grants_controller.rb: POST /api/spine/grant
class SpineGrantsController < ApplicationController
before_action :authenticate_user! # your own authentication
def create
return head :forbidden unless may_watch?(current_user) # your entitlement check
response.headers["Cache-Control"] = "no-store"
render json: { grant: Spine.sign_grant(ENV.fetch("SPINE_EMBED_ID")) }
end
endLimit a grant to one channel
Optional. If you sell channels separately, a grant can name the one channel it opens: add chan, with the channel’s slug. Spine then refuses it for any other channel.
Sign a grant for one channel
The player tells your page which channel it plays: getGrant and serveGrants get its slug as channel (see Iframe embed, Hosted script or npm packages). Send it to your backend, check it’s one of the channels you offer on that site, never passing a slug from the browser on unchecked, check the viewer may watch it, and sign for it. This endpoint takes the place of the one in the Node.js example above: keep one handler for the route, or the first one answers and the channel is never checked.
// spine-grants.ts: a grant for one channel, beside signGrant
export async function signChannelGrant(embedId: string, channel: string): Promise<string> {
const now = Math.floor(Date.now() / 1000);
return new SignJWT({ emb: embedId, chan: channel })
.setProtectedHeader({ alg: "ES256", kid: KEY_ID })
.setAudience("spine:grant")
.setJti(randomUUID())
.setIssuedAt(now)
.setExpirationTime(now + 300)
.sign(await PRIVATE_KEY);
}// routes/spine.ts: in place of the endpoint above, never beside it
import express from "express";
import { signChannelGrant } from "../spine-grants";
const EMBED_ID = process.env.SPINE_EMBED_ID!; // this site's embed ID, emb_…
const CHANNELS = new Set(["spor-1", "spor-2"]); // the slugs of the channels you offer on this site
export const spine = express.Router();
spine.post("/api/spine/grant", express.json(), async (req, res) => {
const viewer = req.user; // from your own authentication middleware
if (!viewer) return res.status(401).end();
const channel = req.body?.channel;
if (typeof channel !== "string" || !CHANNELS.has(channel)) return res.status(400).end();
if (!(await mayWatchChannel(viewer, channel))) return res.status(403).end();
res.set("cache-control", "no-store").json({ grant: await signChannelGrant(EMBED_ID, channel) });
});
declare function mayWatchChannel(viewer: unknown, channel: string): Promise<boolean>; // your entitlement checkIn the other languages, add chan to the claims the same way, with the slug your page sent.
- When a viewer switches channel in the channel selector, the player starts a new session and asks your page for a grant naming the new channel.
- If Spine changes a channel’s slug, grants naming the old one stop working, as embeds naming it do. Spine may later give that slug to another channel. A grant then opens that channel only if it was signed after the channel took the slug, so update the slugs your backend signs with when Spine tells you of a change.