public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "token/asset/{assetId}/key/{keyId}")] HttpRequestMessage req, string assetId, string keyId, TraceWriter log) { // Create and cache the Media Services credentials in a static class variable _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext _context = new CloudMediaContext(_cachedCredentials); var asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.NotFound, $"Asset {assetId} doesn't exist.")); } // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(keyId); TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken( tokenTemplate, new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)), rawkey, DateTime.UtcNow.AddDays(365) ); var tokenResponse = new TokenResponse { Token = testToken, TokenBase64 = testToken.Base64Encode() }; return(req.CreateResponse(HttpStatusCode.OK, tokenResponse)); }
public override void HandleExecute(Common.workflow.ChainRequest request) { myRequest = (ButlerProcessRequest)request; Setup(); _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey); IAsset encodedAsset = (from m in _MediaServiceContext.Assets select m).Where(m => m.Id == myRequest.AssetId).FirstOrDefault(); //Create key IContentKey key = CreateEnvelopeTypeContentKey(encodedAsset); //Create Token Template string tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); Trace.TraceInformation("Added authorization policy: {0}", key.AuthorizationPolicyId); //create Delivery Policy CreateAssetDeliveryPolicy(encodedAsset, key); if (!String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey); Trace.TraceInformation("The authorization token is:\n{0}", testToken); myRequest.Log.Add("The authorization token"); myRequest.Log.Add(testToken); myRequest.Log.Add(""); } }
private void FetchKeyWithSWTToken(string audience, string issuer) { IContentKey contentKey = null; IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null; IContentKeyAuthorizationPolicyOption policyOption = null; try { byte[] expectedKey = null; contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey); var contentKeyId = Guid.Parse(contentKey.Id.Replace("nb:kid:UUID:", String.Empty)); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.SWT); tokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(); // the default constructor automatically generates a random key tokenRestrictionTemplate.Audience = audience; tokenRestrictionTemplate.Issuer = issuer; tokenRestrictionTemplate.TokenType = TokenType.SWT; tokenRestrictionTemplate.RequiredClaims.Add(new TokenClaim(TokenClaim.ContentKeyIdentifierClaimType, contentKeyId.ToString())); string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithSWTAuthentication"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); ContentKeyRestrictionType restrictionType = ContentKeyRestrictionType.TokenRestricted; var _testOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, restrictionType); List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption> { _testOption }; contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId)); KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed); string swtTokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenRestrictionTemplate, tokenRestrictionTemplate.PrimaryVerificationKey, contentKeyId, DateTime.Now.AddDays(2)); byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, swtTokenString); string expectedString = GetString(expectedKey); string fetchedString = GetString(key); Assert.AreEqual(expectedString, fetchedString); } finally { CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption); } }
public static IProgram CreateAndStartProgram(IChannel channel) { IAsset asset = _context.Assets.Create(AssetlName, AssetCreationOptions.None); IContentKey key = CreateCommonTypeContentKey(asset); Console.WriteLine("Created key {0} for the asset {1} ", key.Id, asset.Id); Console.WriteLine(); bool tokenRestriction = false; string tokenTemplateString = null; if (tokenRestriction) { tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); } else { AddOpenAuthorizationPolicy(key); } Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); CreateAssetDeliveryPolicy(asset, key); Console.WriteLine("Created asset delivery policy. \n"); Console.WriteLine(); if (tokenRestriction && !String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365)); Console.WriteLine("The authorization token is:\n{0}", testToken); Console.WriteLine(); } // Create a Program on the Channel. You can have multiple Programs that overlap or are sequential; // however each Program must have a unique name within your Media Services account. IProgram program = channel.Programs.Create(ProgramlName, TimeSpan.FromHours(4), asset.Id); program.Start(); Console.WriteLine("Starting Program " + Program.ProgramlName); return(program); }
public static async Task <object> Run([HttpTrigger("post", WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log) { log.Info("GetToken requested."); var tRequest = await req.Content.ReadAsAsync <TokenRequest>(); // Sanity checks #region Sanity checks if (tRequest == null || tRequest.AssetId == null || tRequest.KeyId == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Invalid token request." })); } #endregion // Create and cache the Media Services credentials in a static class variable _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext _context = new CloudMediaContext(_cachedCredentials); var asset = _context.Assets.Where(a => a.Id == tRequest.AssetId).FirstOrDefault(); if (asset == null) { return(req.CreateResponse(HttpStatusCode.NotFound, new { error = $"Asset {tRequest.AssetId} doesn't exist." })); } // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(tRequest.KeyId); TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken( tokenTemplate, new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)), rawkey, DateTime.UtcNow.AddDays(365) ); var tokenResponse = new TokenResponse { Token = testToken, TokenBase64 = testToken.Base64Encode() }; return(req.CreateResponse(HttpStatusCode.OK, tokenResponse)); }
public static string GetTestToken(string assetid, IAsset asset = null) { if (asset == null) { asset = GetAssetById(assetid); } IContentKey key = asset.ContentKeys.FirstOrDefault(); if (key != null && key.AuthorizationPolicyId != null) { IContentKeyAuthorizationPolicy policy = context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault(); if (policy != null) { IContentKeyAuthorizationPolicyOption option = null; option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault(); if (option != null) { string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); if (tokenTemplate.TokenType == TokenType.SWT) //SWT { return("Bearer " + TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(1))); } } } } } return(null); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the chached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); bool tokenRestriction = true; string tokenTemplateString = null; IAsset asset = UploadFileAndCreateAsset(_singleMP4File); Console.WriteLine("Uploaded asset: {0}", asset.Id); IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset); Console.WriteLine("Encoded asset: {0}", encodedAsset.Id); IContentKey key = CreateEnvelopeTypeContentKey(encodedAsset); Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id); Console.WriteLine(); if (tokenRestriction) { tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); } else { AddOpenAuthorizationPolicy(key); } Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); CreateAssetDeliveryPolicy(encodedAsset, key); Console.WriteLine("Created asset delivery policy. \n"); Console.WriteLine(); if (tokenRestriction && !String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); //The GenerateTestToken method returns the token without the word “Bearer” in front //so you have to add it in front of the token string. string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365)); Console.WriteLine("The authorization token is:\nBearer {0}", testToken); Console.WriteLine(); } // You can use the bit.ly/aesplayer Flash player to test the URL // (with open authorization policy). // Paste the URL and click the Update button to play the video. // string URL = GetStreamingOriginLocator(encodedAsset); Console.WriteLine("Smooth Streaming Url: {0}/manifest", URL); Console.WriteLine(); Console.WriteLine("HLS Url: {0}/manifest(format=m3u8-aapl)", URL); Console.WriteLine(); Console.ReadLine(); }
public static TokenResult GetTestToken(IAsset MyAsset, CloudMediaContext _context, ContentKeyType?keytype = null, SigningCredentials signingcredentials = null, string optionid = null, bool displayUI = false) { TokenResult MyResult = new TokenResult(); /// WITH UI if (displayUI) { CreateTestToken form = new CreateTestToken(MyAsset, _context, keytype, optionid) { StartDate = DateTime.Now.AddMinutes(-5), EndDate = DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration) }; if (form.ShowDialog() == DialogResult.OK) { if (form.GetOption != null) { string tokenTemplateString = form.GetOption.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(form.GetContentKeyFromSelectedOption.Id); TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); if (tokenTemplate.OpenIdConnectDiscoveryDocument == null) { MyResult.TokenType = tokenTemplate.TokenType; MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)); MyResult.ContentKeyType = form.GetContentKeyFromSelectedOption.ContentKeyType; if (tokenTemplate.TokenType == TokenType.SWT) //SWT { MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, form.EndDate); } else // JWT { IList <Claim> myclaims = null; myclaims = form.GetTokenRequiredClaims; if (form.PutContentKeyIdentifier) { myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString())); } if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) { InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue); signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); } else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey)) { X509Certificate2 cert = form.GetX509Certificate; if (cert != null) { signingcredentials = new X509SigningCredentials(cert); } } JwtSecurityToken token = new JwtSecurityToken(issuer: form.GetIssuerUri, audience: form.GetAudienceUri, notBefore: form.StartDate, expires: form.EndDate, signingCredentials: signingcredentials, claims: myclaims); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); MyResult.TokenString = handler.WriteToken(token); } } } } } } /////////////////////////////// NO UI else if (keytype != null) { IContentKey key = MyAsset.ContentKeys.Where(k => k.ContentKeyType == keytype).FirstOrDefault(); if (key != null && key.AuthorizationPolicyId != null) { IContentKeyAuthorizationPolicy policy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault(); if (policy != null) { IContentKeyAuthorizationPolicyOption option = null; if (optionid == null) // user does not want a specific option { option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault(); } else { option = policy.Options.Where(o => o.Id == optionid).FirstOrDefault(); // user wants a token for a specific option } if (option != null) // && option.Restrictions.FirstOrDefault() != null && option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted) { string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); if (tokenTemplate.OpenIdConnectDiscoveryDocument == null) { MyResult.TokenType = tokenTemplate.TokenType; MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)); MyResult.ContentKeyType = (ContentKeyType)keytype; if (tokenTemplate.TokenType == TokenType.SWT) //SWT { MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration)); } else // JWT { List <Claim> myclaims = null; myclaims = new List <Claim>(); myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString())); if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) { InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue); signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); } else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey)) { if (signingcredentials == null) { X509Certificate2 cert = DynamicEncryption.GetCertificateFromFile(true); if (cert != null) { signingcredentials = new X509SigningCredentials(cert); } } } JwtSecurityToken token = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration), signingCredentials: signingcredentials, claims: myclaims); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); MyResult.TokenString = handler.WriteToken(token); } } } } } } } return(MyResult); }
public ActionResult Index() { _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); myContext = new CloudMediaContext(_cachedCredentials); // Use a LINQ Select query to get an asset. var assetInstance = from a in myContext.Assets where a.Name == assetName select a; // Reference the asset as an IAsset. IAsset myAsset = assetInstance.FirstOrDefault(); IContentKey key = myAsset.ContentKeys[0]; IContentKeyAuthorizationPolicy AutPol = myContext.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.AuthorizationPolicyId).FirstOrDefault(); //IContentKeyAuthorizationPolicyOption AutPolOption = AutPol.Options.Skip(0).FirstOrDefault(); IContentKeyAuthorizationPolicyOption AutPolOption = AutPol.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault(); string tokenTemplateString = AutPolOption.Restrictions.FirstOrDefault().Requirements; TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); DateTime StartDate = DateTime.Now.AddMinutes(-5); DateTime EndDate = DateTime.Now.AddMinutes(TokenDuration); if (tokenTemplate.TokenType == TokenType.SWT) //SWT { tokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, EndDate); } else // JWT { IList <Claim> myclaims = null; bool IsAddContentKeyIdentifierClaim = false; myclaims = GetTokenRequiredClaims(tokenTemplate, out IsAddContentKeyIdentifierClaim); //List<Claim> myclaims = null; //myclaims = new List<Claim>(); //myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString())); SigningCredentials signingcredentials = null; if (IsAddContentKeyIdentifierClaim) { myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString())); } //if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) //{ InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue); signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest); //} //else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey)) //{ //X509Certificate2 cert = form.GetX509Certificate; //if (cert != null) signingcredentials = new X509SigningCredentials(cert); //} string AudienceUri = tokenTemplate.Audience.ToString(); //JwtSecurityToken token = new JwtSecurityToken(issuer: IssuerUri, audience: AudienceUri, notBefore: StartDate, expires: EndDate, signingCredentials: signingcredentials, claims: myclaims); JwtSecurityToken token = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: StartDate, expires: EndDate, signingCredentials: signingcredentials, claims: myclaims); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); //ViewBag.TokenString = HttpUtility.UrlEncode("Bearer " + handler.WriteToken(token)); ViewBag.TokenString = "Bearer " + handler.WriteToken(token); } return(View()); }
static void Main(string[] args) { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain, new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret), AzureEnvironments.AzureCloudEnvironment); var tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider); bool tokenRestriction = false; string tokenTemplateString = null; IAsset asset = UploadFileAndCreateAsset(_singleMP4File); Console.WriteLine("Uploaded asset: {0}", asset.Id); IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset); Console.WriteLine("Encoded asset: {0}", encodedAsset.Id); IContentKey key = CreateCommonCBCTypeContentKey(encodedAsset); Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id); Console.WriteLine("FairPlay License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.FairPlay)); Console.WriteLine(); if (tokenRestriction) { tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); } else { AddOpenAuthorizationPolicy(key); } Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); CreateAssetDeliveryPolicy(encodedAsset, key); Console.WriteLine("Created asset delivery policy. \n"); Console.WriteLine(); if (tokenRestriction && !String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365)); Console.WriteLine("The authorization token is:\nBearer {0}", testToken); Console.WriteLine(); } string url = GetStreamingOriginLocator(encodedAsset); Console.WriteLine("Encrypted HLS URL: {0}/manifest(format=m3u8-aapl)", url); Console.ReadLine(); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); bool tokenRestriction = false; string tokenTemplateString = null; IAsset asset = UploadFileAndCreateAsset(_singleMP4File); Console.WriteLine("Uploaded asset: {0}", asset.Id); IAsset encodedAsset = EncodeToAdaptiveBitrateMP4Set(asset); Console.WriteLine("Encoded asset: {0}", encodedAsset.Id); IContentKey key = CreateCommonTypeContentKey(encodedAsset); Console.WriteLine("Created key {0} for the asset {1} ", key.Id, encodedAsset.Id); Console.WriteLine("PlayReady License Key delivery URL: {0}", key.GetKeyDeliveryUrl(ContentKeyDeliveryType.PlayReadyLicense)); Console.WriteLine(); if (tokenRestriction) { tokenTemplateString = AddTokenRestrictedAuthorizationPolicy(key); } else { AddOpenAuthorizationPolicy(key); } Console.WriteLine("Added authorization policy: {0}", key.AuthorizationPolicyId); Console.WriteLine(); CreateAssetDeliveryPolicy(encodedAsset, key); Console.WriteLine("Created asset delivery policy. \n"); Console.WriteLine(); if (tokenRestriction && !String.IsNullOrEmpty(tokenTemplateString)) { // Deserializes a string containing an Xml representation of a TokenRestrictionTemplate // back into a TokenRestrictionTemplate class instance. TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); // Generate a test token based on the the data in the given TokenRestrictionTemplate. // Note, you need to pass the key id Guid because we specified // TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate. Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.UtcNow.AddDays(365)); Console.WriteLine("The authorization token is:\nBearer {0}", testToken); Console.WriteLine(); } // You can use the http://smf.cloudapp.net/healthmonitor player // to test the smoothStreamURL URL. // string url = GetStreamingOriginLocator(encodedAsset); Console.WriteLine("Encrypted Smooth Streaming URL: {0}/manifest", url); Console.ReadLine(); }