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 = 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 CreateTestToken(IAsset _asset, CloudMediaContext _context, ContentKeyType?keytype = null, string optionid = null) { InitializeComponent(); this.Icon = Bitmaps.Azure_Explorer_ico; MyAsset = _asset; mycontext = _context; var query = from key in MyAsset.ContentKeys join autpol in _context.ContentKeyAuthorizationPolicies on key.AuthorizationPolicyId equals autpol.Id select new { keyname = key.Name, keytype = key.ContentKeyType, keyid = key.Id, aupolid = autpol.Id }; listViewAutOptions.BeginUpdate(); listViewAutOptions.Items.Clear(); foreach (var key in query) { var queryoptions = _context.ContentKeyAuthorizationPolicies.Where(a => a.Id == key.aupolid).FirstOrDefault().Options; foreach (var option in queryoptions) { if (option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted) { ListViewItem item = new ListViewItem(key.keytype.ToString()); IContentKey keyj = MyAsset.ContentKeys.Where(k => k.Id == key.keyid).FirstOrDefault(); ContentKeyDisplayed.Add(keyj); item.SubItems.Add(option.Name); item.SubItems.Add(option.Id); string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); item.SubItems.Add(tokenTemplate.TokenType == TokenType.JWT ? "JWT" : "SWT"); if (tokenTemplate.PrimaryVerificationKey != null) { item.SubItems.Add(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey) ? "Symmetric" : "Asymmetric X509"); } else if (tokenTemplate.OpenIdConnectDiscoveryDocument != null) { item.SubItems.Add("OpenID"); } } listViewAutOptions.Items.Add(item); if (optionid == option.Id) { listViewAutOptions.Items[listViewAutOptions.Items.IndexOf(item)].Selected = true; } } } } if (listViewAutOptions.Items.Count > 0 && listViewAutOptions.SelectedItems.Count == 0) // no selection, in that case, first line selected { listViewAutOptions.Items[0].Selected = true; } listViewAutOptions.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); listViewAutOptions.EndUpdate(); }
static void Main(string[] args) { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain, AzureEnvironments.AzureCloudEnvironment); AzureAdTokenProvider 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(); }
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); }
private void DoDisplayAuthorizationPolicyOption() { if (listViewAutPolOptions.SelectedItems.Count > 0 && SelectedPolicy != null) { dataGridViewAutPolOption.Rows.Clear(); dataGridViewAutPolOption.ColumnCount = 2; dataGridViewAutPolOption.Columns[0].DefaultCellStyle.BackColor = Color.Gainsboro; IContentKeyAuthorizationPolicyOption option = SelectedPolicy.Options.Skip(listViewAutPolOptions.SelectedIndices[0]).Take(1).FirstOrDefault(); if (option != null) // Token option { dataGridViewAutPolOption.Rows.Add("Name", option.Name != null ? option.Name : "<no name>"); dataGridViewAutPolOption.Rows.Add("Id", option.Id); // Key delivery configuration int i = dataGridViewAutPolOption.Rows.Add("KeyDeliveryConfiguration", "<null>"); if (option.KeyDeliveryConfiguration != null) { DataGridViewButtonCell btn = new DataGridViewButtonCell(); dataGridViewAutPolOption.Rows[i].Cells[1] = btn; dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See value"; dataGridViewAutPolOption.Rows[i].Cells[1].Tag = option.KeyDeliveryConfiguration; } dataGridViewAutPolOption.Rows.Add("KeyDeliveryType", option.KeyDeliveryType); List <ContentKeyAuthorizationPolicyRestriction> objList_restriction = option.Restrictions; foreach (var restriction in objList_restriction) { dataGridViewAutPolOption.Rows.Add("Restriction Name", restriction.Name); dataGridViewAutPolOption.Rows.Add("Restriction KeyRestrictionType", (ContentKeyRestrictionType)restriction.KeyRestrictionType); if (restriction.Requirements != null) { // Restriction Requirements i = dataGridViewAutPolOption.Rows.Add("Restriction Requirements", "<null>"); if (restriction.Requirements != null) { DataGridViewButtonCell btn2 = new DataGridViewButtonCell(); dataGridViewAutPolOption.Rows[i].Cells[1] = btn2; dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See value"; dataGridViewAutPolOption.Rows[i].Cells[1].Tag = restriction.Requirements; TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(restriction.Requirements); dataGridViewAutPolOption.Rows.Add("Token Type", tokenTemplate.TokenType); i = dataGridViewAutPolOption.Rows.Add("Primary Verification Key", "<null>"); if (tokenTemplate.PrimaryVerificationKey != null) { dataGridViewAutPolOption.Rows.Add("Token Verification Key Type", (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) ? "Symmetric" : "Asymmetric (X509)"); if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)) { var verifkey = (SymmetricVerificationKey)tokenTemplate.PrimaryVerificationKey; btn2 = new DataGridViewButtonCell(); dataGridViewAutPolOption.Rows[i].Cells[1] = btn2; dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See key value"; dataGridViewAutPolOption.Rows[i].Cells[1].Tag = Convert.ToBase64String(verifkey.KeyValue); } } foreach (var verifkey in tokenTemplate.AlternateVerificationKeys) { i = dataGridViewAutPolOption.Rows.Add("Alternate Verification Key", "<null>"); if (verifkey != null) { dataGridViewAutPolOption.Rows.Add("Token Verification Key Type", (verifkey.GetType() == typeof(SymmetricVerificationKey)) ? "Symmetric" : "Asymmetric (X509)"); if (verifkey.GetType() == typeof(SymmetricVerificationKey)) { var verifkeySym = (SymmetricVerificationKey)verifkey; btn2 = new DataGridViewButtonCell(); dataGridViewAutPolOption.Rows[i].Cells[1] = btn2; dataGridViewAutPolOption.Rows[i].Cells[1].Value = "See key value"; dataGridViewAutPolOption.Rows[i].Cells[1].Tag = Convert.ToBase64String(verifkeySym.KeyValue); } } } if (tokenTemplate.OpenIdConnectDiscoveryDocument != null) { dataGridViewAutPolOption.Rows.Add("OpenId Connect Discovery Document Uri", tokenTemplate.OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri); } dataGridViewAutPolOption.Rows.Add("Token Audience", tokenTemplate.Audience); dataGridViewAutPolOption.Rows.Add("Token Issuer", tokenTemplate.Issuer); foreach (var claim in tokenTemplate.RequiredClaims) { dataGridViewAutPolOption.Rows.Add("Required Claim, Type", claim.ClaimType); dataGridViewAutPolOption.Rows.Add("Required Claim, Value", claim.ClaimValue); } } } } } } }
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 = 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 = 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); string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey); 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(); }