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(""); } }
public void RoundTripTest() { TokenRestrictionTemplate template = new TokenRestrictionTemplate(); template.PrimaryVerificationKey = new SymmetricVerificationKey(); template.AlternateVerificationKeys.Add(new SymmetricVerificationKey()); template.Audience = _sampleAudience; template.Issuer = _sampleIssuer; template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); template.RequiredClaims.Add(new TokenClaim("Rental", "true")); string serializedTemplate = TokenRestrictionTemplateSerializer.Serialize(template); Assert.IsFalse(String.IsNullOrWhiteSpace(serializedTemplate)); TokenRestrictionTemplate template2 = TokenRestrictionTemplateSerializer.Deserialize(serializedTemplate); Assert.IsNotNull(template2); Assert.AreEqual(template.Issuer, template2.Issuer); Assert.AreEqual(template.Audience, template2.Audience); SymmetricVerificationKey fromTemplate = (SymmetricVerificationKey)template.PrimaryVerificationKey; SymmetricVerificationKey fromTemplate2 = (SymmetricVerificationKey)template2.PrimaryVerificationKey; Assert.IsTrue(fromTemplate.KeyValue.SequenceEqual(fromTemplate2.KeyValue)); }
static private string GenerateTokenRequirements(TokenType mytokentype, string _sampleAudience, string _sampleIssuer, IList <TokenClaim> tokenclaimslist, bool AddContentKeyIdentifierClaim, TokenVerificationKey mytokenverificationkey, string openIdDiscoveryURL = null) { TokenRestrictionTemplate TokenrestrictionTemplate = new TokenRestrictionTemplate(mytokentype) { Audience = _sampleAudience, Issuer = _sampleIssuer, }; if (AddContentKeyIdentifierClaim) { TokenrestrictionTemplate.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); } if (openIdDiscoveryURL != null) { TokenrestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(openIdDiscoveryURL); } else { TokenrestrictionTemplate.PrimaryVerificationKey = mytokenverificationkey; } foreach (var t in tokenclaimslist) { TokenrestrictionTemplate.RequiredClaims.Add(t); } return(TokenRestrictionTemplateSerializer.Serialize(TokenrestrictionTemplate)); }
public void KnownGoodInputForSWT() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys /><Audience>http://sampleissuerurl/</Audience><Issuer>http://sampleaudience/</Issuer><PrimaryVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>2OvxltHKwILn5PCRD8H+63sK98LBs1yF+ZdZbwzmToWYm29pLyqIMuCvMRGpLOv5DYh3NmpzWMAciu4ncW8VTg==</KeyValue></PrimaryVerificationKey><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims><TokenType>SWT</TokenType></TokenRestrictionTemplate>"; TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.IsNotNull(template); Assert.AreEqual(TokenType.SWT, template.TokenType); }
public void KnownGoodInputTest() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys><TokenVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><Issuer>http://sampleissuerurl/</Issuer><PrimaryVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>2OvxltHKwILn5PCRD8H+63sK98LBs1yF+ZdZbwzmToWYm29pLyqIMuCvMRGpLOv5DYh3NmpzWMAciu4ncW8VTg==</KeyValue></PrimaryVerificationKey><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims></TokenRestrictionTemplate>"; TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.IsNotNull(template); }
public void KnownGoodInputForJWT() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys /><Audience>http://sampleissuerurl/</Audience><Issuer>http://sampleaudience/</Issuer><PrimaryVerificationKey i:type=\"X509CertTokenVerificationKey\"><RawBody>MIIDAzCCAeugAwIBAgIQ2cl0q8oGkaFG+ZTZYsilhDANBgkqhkiG9w0BAQ0FADARMQ8wDQYDVQQDEwZDQVJvb3QwHhcNMTQxMjAxMTg0NzI5WhcNMzkxMjMxMjM1OTU5WjARMQ8wDQYDVQQDEwZDQVJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDjgMbtZcLtKNdJXHSGQ7l6xJBtNCVhjF4+BLZq+D2RmubKTAnGXhNGY4FO2LrPjfkWumdnv5DOlFuwHy2qrsZu1TFZxxQzU9/Yp3VAD1Afk7ShUOxniPpIO9vfkUH+FEX1Taq4ncR/TkiwnIZLy+bBa0DlF2MsPGC62KbiN4xJqvSIuecxQvcN8MZ78NDejtj1/XHF7VBmVjWi5B79GpTvY9ap39BU8nM0Q8vWb9DwmpWLz8j7hm25f+8laHIE6U8CpeeD/OrZT8ncCD0hbhR3ZGGoFqJbyv2CLPVGeaIhIxBH41zgrBYR53NjkRLTB4IEUCgeTGvSzweqlb+4totdAgMBAAGjVzBVMA8GA1UdEwEB/wQFMAMBAf8wQgYDVR0BBDswOYAQSHiCUWtQlUe79thqsTDbbqETMBExDzANBgNVBAMTBkNBUm9vdIIQ2cl0q8oGkaFG+ZTZYsilhDANBgkqhkiG9w0BAQ0FAAOCAQEABa/2D+Rxo6tp63sDFRViikNkDa5GFZscQLn4Rm35NmUt35Wc/AugLaTJ7iP5zJTYIBUI9DDhHbgFqmYpW0p14NebJlBzrRFIaoHBOsHhy4VYrxIB8Q/OvSGPgbI2c39ni/odyTYKVtJacxPrIt+MqeiFMjJ19cJSOkKT2AFoPMa/L0++znMcEObSAHYMy1U51J1njpQvNJ+MQiR8y2gvmMbGEcMgicIJxbLB2imqJWCQkFUlsrxwuuzSvNaLkdd/HyhsR1JXc+kOREO8gWjhT6MAdgGKC9+neamR7sqwJHPNfcLYTDFOhi6cJH10z74mU1Xa5uLsX+aZp2YYHUFw4Q==</RawBody></PrimaryVerificationKey><RequiredClaims /><TokenType>JWT</TokenType></TokenRestrictionTemplate>"; TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.IsNotNull(template); Assert.AreEqual(TokenType.JWT, template.TokenType); }
public IContentKey AddAuthorizationPolicyToContentKey(string assetID, CloudMediaContext mediaContext, IContentKey objIContentKey, string claimType, string claimValue, JwtSecurityToken token) { //we name auth policy same as asset var policy = mediaContext.ContentKeyAuthorizationPolicies.Where(c => c.Name == assetID).FirstOrDefault(); // Create ContentKeyAuthorizationPolicy with restrictions and create authorization policy if (policy == null) { policy = mediaContext.ContentKeyAuthorizationPolicies.CreateAsync(assetID).Result; } //naming policyOption same as asset var policyOption = mediaContext.ContentKeyAuthorizationPolicyOptions.Where(name => name.Name == assetID).FirstOrDefault(); if (policyOption == null) { List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>(); TokenRestrictionTemplate template = new TokenRestrictionTemplate(); template.TokenType = TokenType.JWT; //Using Active Directory Open ID discovery spec to use Json Web Keys during token verification template.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration"); //Ignore Empty claims if (!String.IsNullOrEmpty(claimType) && !String.IsNullOrEmpty(claimValue)) { template.RequiredClaims.Add(new TokenClaim(claimType, claimValue)); } var audience = token.Audiences.First(); template.Audience = audience; template.Issuer = token.Issuer; string requirements = TokenRestrictionTemplateSerializer.Serialize(template); ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction { Name = "Authorization Policy with Token Restriction", KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted, Requirements = requirements }; restrictions.Add(restriction); policyOption = mediaContext.ContentKeyAuthorizationPolicyOptions.Create(assetID, ContentKeyDeliveryType.BaselineHttp, restrictions, null); policy.Options.Add(policyOption); policy.UpdateAsync(); } // Add ContentKeyAutorizationPolicy to ContentKey objIContentKey.AuthorizationPolicyId = policy.Id; IContentKey IContentKeyUpdated = objIContentKey.UpdateAsync().Result; return(IContentKeyUpdated); }
public void InputMissingRequiredClaimsOkay() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys><TokenVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><Issuer>http://sampleissuerurl/</Issuer><PrimaryVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>2OvxltHKwILn5PCRD8H+63sK98LBs1yF+ZdZbwzmToWYm29pLyqIMuCvMRGpLOv5DYh3NmpzWMAciu4ncW8VTg==</KeyValue></PrimaryVerificationKey></TokenRestrictionTemplate>"; TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.IsNotNull(template); Assert.AreEqual(TokenType.SWT, template.TokenType); }
private void FetchKeyWithJWTAuth(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 templatex509Certificate2 = new X509Certificate2("amscer.pfx", "AMSGIT"); SigningCredentials cred = new X509SigningCredentials(templatex509Certificate2); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenRestrictionTemplate.PrimaryVerificationKey = new X509CertTokenVerificationKey(templatex509Certificate2); tokenRestrictionTemplate.Audience = audience; tokenRestrictionTemplate.Issuer = issuer; string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted); JwtSecurityToken token = new JwtSecurityToken(issuer: tokenRestrictionTemplate.Issuer, audience: tokenRestrictionTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(5), signingCredentials: cred); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); string jwtTokenString = handler.WriteToken(token); List <IContentKeyAuthorizationPolicyOption> options = new List <IContentKeyAuthorizationPolicyOption> { policyOption }; contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); // Enable once all accounts are enabled for per customer Key Delivery Urls //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId)); KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed); byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString); string expectedString = GetString(expectedKey); string fetchedString = GetString(key); Assert.AreEqual(expectedString, fetchedString); } finally { CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption); } }
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 void RSATokenVerificationKeySerializeShouldIncudePrpoperTypeAttribbute() { TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT); RsaTokenVerificationKey tokenVerificationKey = new RsaTokenVerificationKey(); template.PrimaryVerificationKey = tokenVerificationKey; var templateAsString = TokenRestrictionTemplateSerializer.Serialize(template); Assert.IsTrue(templateAsString.Contains("<PrimaryVerificationKey i:type=\"RsaTokenVerificationKey\">")); }
static private string GenerateTokenRequirements(Uri _sampleAudience, Uri _sampleIssuer) { TokenRestrictionTemplate template = new TokenRestrictionTemplate(); template.PrimaryVerificationKey = new SymmetricVerificationKey(); template.AlternateVerificationKeys.Add(new SymmetricVerificationKey()); template.Audience = _sampleAudience; template.Issuer = _sampleIssuer; template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); return(TokenRestrictionTemplateSerializer.Serialize(template)); }
static private string GenerateTokenRequirements() { TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.SWT); template.PrimaryVerificationKey = new SymmetricVerificationKey(); template.AlternateVerificationKeys.Add(new SymmetricVerificationKey()); template.Audience = ConfigurationManager.AppSettings["Audience"]; template.Issuer = ConfigurationManager.AppSettings["Issuer"]; template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); return(TokenRestrictionTemplateSerializer.Serialize(template)); }
public void InputMissingIssuerShouldThrow() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys><TokenVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><PrimaryVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>2OvxltHKwILn5PCRD8H+63sK98LBs1yF+ZdZbwzmToWYm29pLyqIMuCvMRGpLOv5DYh3NmpzWMAciu4ncW8VTg==</KeyValue></PrimaryVerificationKey><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims></TokenRestrictionTemplate>"; try { TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.Fail("Should throw"); } catch (SerializationException e) { Assert.IsTrue(e.Message.Contains("Expecting element 'Issuer'.")); } }
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)); }
private List <ContentKeyAuthorizationPolicyRestriction> CreateContentKeyAuthPolicyRestrictions(string policyName, ContentProtection contentProtection) { List <ContentKeyAuthorizationPolicyRestriction> policyRestrictions = new List <ContentKeyAuthorizationPolicyRestriction>(); if (contentProtection.ContentAuthTypeAddress) { ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyAddressRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.IPRestricted); policyRestriction.Requirements = GetAddressRangeXml(contentProtection.ContentAuthAddressRange); policyRestrictions.Add(policyRestriction); } if (contentProtection.ContentAuthTypeToken) { string settingKey = Constant.AppSettingKey.DirectoryTenantId; settingKey = string.Format(settingKey, contentProtection.DirectoryId); string directoryTenantId = AppSetting.GetValue(settingKey); settingKey = Constant.AppSettingKey.DirectoryTenantDomain; settingKey = string.Format(settingKey, contentProtection.DirectoryId); string directoryTenantDomain = AppSetting.GetValue(settingKey); string discoveryUrl = Account.GetDiscoveryUrl(contentProtection.DirectoryId, directoryTenantDomain); if (string.Equals(contentProtection.DirectoryId, Constant.DirectoryService.B2C, StringComparison.OrdinalIgnoreCase)) { settingKey = Constant.AppSettingKey.DirectoryPolicyIdSignUpIn; string policyIdSignUpIn = AppSetting.GetValue(settingKey); discoveryUrl = string.Concat(discoveryUrl, "?p=", policyIdSignUpIn); } TokenRestrictionTemplate tokenTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(discoveryUrl); tokenTemplate.Issuer = Account.GetIssuerUrl(contentProtection.DirectoryId, directoryTenantId); tokenTemplate.Audience = contentProtection.Audience; ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyTokenRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.TokenRestricted); policyRestriction.Requirements = TokenRestrictionTemplateSerializer.Serialize(tokenTemplate); policyRestrictions.Add(policyRestriction); } if (policyRestrictions.Count == 0) { ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constant.Media.ContentProtection.AuthPolicyOpenRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.Open); policyRestrictions.Add(policyRestriction); } return(policyRestrictions); }
private static string GetJwtRequirements() { var primaryVerificationKey = ConfigurationManager.AppSettings["JWTRestrictionPrimaryVerificationKeyBase64"]; var audience = ConfigurationManager.AppSettings["JWTRestrictionAudience"]; var issuer = ConfigurationManager.AppSettings["JWTRestrictionIssuer"]; var template = new TokenRestrictionTemplate(TokenType.JWT) { PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primaryVerificationKey)), Audience = audience, Issuer = issuer }; return(TokenRestrictionTemplateSerializer.Serialize(template)); }
public void InputMissingPrimaryKeyShouldThrow() { string tokenTemplate = "<TokenRestrictionTemplate xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1\"><AlternateVerificationKeys><TokenVerificationKey i:type=\"SymmetricVerificationKey\"><KeyValue>GG07fDPZ+HMD2vcoknMqYjEJMb7LSq8zUmdCYMvRCevnQK//ilbhODO/FydMrHiwZGmI6XywvOOU7SSzRPlI3Q==</KeyValue></TokenVerificationKey></AlternateVerificationKeys><Audience>http://sampleaudience/</Audience><Issuer>http://sampleissuerurl/</Issuer><RequiredClaims><TokenClaim><ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType><ClaimValue i:nil=\"true\" /></TokenClaim><TokenClaim><ClaimType>urn:myservice:claims:rental</ClaimType><ClaimValue>true</ClaimValue></TokenClaim></RequiredClaims></TokenRestrictionTemplate>"; try { TokenRestrictionTemplate template = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplate); Assert.Fail("Should throw"); } catch (InvalidDataContractException e) { Assert.IsTrue(e.Message.Contains("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null")); throw; } }
public void TokenRestrictionTemplateDeserializeNilOpenConnectIdDocumentUriNoPrimaryKey() { string body = @"<TokenRestrictionTemplate xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1"" ><AlternateVerificationKeys /><Audience>http://sampleissuerurl/</Audience><Issuer>http://sampleaudience/</Issuer><OpenIdConnectDiscoveryDocument ><OpenIdDiscoveryUri i:nil=""true""></OpenIdDiscoveryUri></OpenIdConnectDiscoveryDocument></TokenRestrictionTemplate>"; try { var template = TokenRestrictionTemplateSerializer.Deserialize(body); } catch (Exception ex) { Assert.AreEqual("OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri string value is null or empty", ex.Message); throw; } }
public void TokenRestrictionTemplateDeserializeNotAbsoluteDiscoveryUri() { string body = @"<TokenRestrictionTemplate xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1"" ><AlternateVerificationKeys /><Audience>http://sampleissuerurl/</Audience><Issuer>http://sampleaudience/</Issuer><OpenIdConnectDiscoveryDocument ><OpenIdDiscoveryUri >RelativeUri</OpenIdDiscoveryUri></OpenIdConnectDiscoveryDocument></TokenRestrictionTemplate>"; try { var template = TokenRestrictionTemplateSerializer.Deserialize(body); } catch (Exception ex) { Assert.AreEqual("String representation of OpenIdConnectDiscoveryDocument.OpenIdDiscoveryUri is not valid absolute Uri.", ex.Message); throw; } }
private void listViewAutOptions_SelectedIndexChanged(object sender, EventArgs e) { bool NoVerifKey = false; if (listViewAutOptions.SelectedIndices.Count > 0) { var it = listViewAutOptions.SelectedItems[0]; string stringoptionid = it.SubItems[2].Text; SelectedOption = mycontext.ContentKeyAuthorizationPolicyOptions.Where(p => p.Id == stringoptionid).FirstOrDefault(); KeyFromSelectedOption = ContentKeyDisplayed[listViewAutOptions.SelectedItems[0].Index]; string tokenTemplateString = SelectedOption.Restrictions.FirstOrDefault().Requirements; if (!string.IsNullOrEmpty(tokenTemplateString)) { TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString); textBoxAudience.Text = tokenTemplate.Audience.ToString(); textBoxIssuer.Text = tokenTemplate.Issuer.ToString(); checkBoxAddContentKeyIdentifierClaim.Checked = false; groupBoxStartDate.Enabled = (tokenTemplate.TokenType == TokenType.JWT); if (tokenTemplate.PrimaryVerificationKey != null) { panelJWTX509Cert.Enabled = !(tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey)); } else { NoVerifKey = true; // Case for OpenId for example. No way to create a test token.... } TokenClaimsList.Clear(); foreach (var claim in tokenTemplate.RequiredClaims) { if (claim.ClaimType == TokenClaim.ContentKeyIdentifierClaimType) { checkBoxAddContentKeyIdentifierClaim.Checked = true; } else { TokenClaimsList.Add(new MyTokenClaim() { Type = claim.ClaimType, Value = claim.ClaimValue }); } } } UpdateButtonOk(NoVerifKey); } }
public void TokenRestrictionTemplateSerializeNotPrimaryKeyAndNoOpenConnectIdDocument() { TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT); template.Audience = _sampleAudience; template.Issuer = _sampleIssuer; try { TokenRestrictionTemplateSerializer.Serialize(template); } catch (Exception ex) { Assert.AreEqual("Both PrimaryVerificationKey and OpenIdConnectDiscoveryDocument are null", ex.Message); throw; } }
/*This code generates the following XML: * <TokenRestrictionTemplate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1"> * <AlternateVerificationKeys> * <TokenVerificationKey i:type="SymmetricVerificationKey"> * <KeyValue>hhv74VzJ+pOiuYw1z2wxh6ZkX4tRl/WVhBTvM6T/vUo=</KeyValue> * </TokenVerificationKey> * </AlternateVerificationKeys> * <Audience>urn:test</Audience> * <Issuer>https://willzhanacs.accesscontrol.windows.net/</Issuer> * <PrimaryVerificationKey i:type="SymmetricVerificationKey"> * <KeyValue>7V1WtGGAylmZTMKA8RlVMrPNhukYBF2sW04UMpuD8bw=</KeyValue> * </PrimaryVerificationKey> * <RequiredClaims> * <TokenClaim> * <ClaimType>urn:microsoft:azure:mediaservices:contentkeyidentifier</ClaimType> * <ClaimValue i:nil="true" /> * </TokenClaim> * </RequiredClaims> * </TokenRestrictionTemplate> * * <TokenRestrictionTemplate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/Azure/MediaServices/KeyDelivery/TokenRestrictionTemplate/v1"> * <AlternateVerificationKeys> * <TokenVerificationKey i:type="SymmetricVerificationKey"> * <KeyValue>hhv74VzJ+pOiuYw1z2wxh6ZkX4tRl/WVhBTvM6T/vUo=</KeyValue> * </TokenVerificationKey> * </AlternateVerificationKeys> * <Audience>urn:test</Audience> * <Issuer>https://willzhanacs.accesscontrol.windows.net/</Issuer> * <PrimaryVerificationKey i:type="SymmetricVerificationKey"> * <KeyValue>7V1WtGGAylmZTMKA8RlVMrPNhukYBF2sW04UMpuD8bw=</KeyValue> * </PrimaryVerificationKey> * <RequiredClaims /> * </TokenRestrictionTemplate> */ //Sample code: https://raw.githubusercontent.com/Azure/azure-media-services-samples/master/KDWithACS/ConsoleApplication6/Program.cs public static string CreateRestrictionRequirements() { string primarySymmetricKey = System.Configuration.ConfigurationManager.AppSettings["PrimarySymmetricKey"]; string secondarySymmetricKey = System.Configuration.ConfigurationManager.AppSettings["SecondarySymmetricKey"]; string scope = System.Configuration.ConfigurationManager.AppSettings["AcsScope"]; string issuer = System.Configuration.ConfigurationManager.AppSettings["AcsIssuer"]; TokenRestrictionTemplate objTokenRestrictionTemplate = new TokenRestrictionTemplate(); objTokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primarySymmetricKey)); objTokenRestrictionTemplate.AlternateVerificationKeys.Add(new SymmetricVerificationKey(Convert.FromBase64String(secondarySymmetricKey))); objTokenRestrictionTemplate.Audience = new Uri(scope); objTokenRestrictionTemplate.Issuer = new Uri(issuer); //objTokenRestrictionTemplate.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); objTokenRestrictionTemplate.TokenType = TokenType.SWT; //new change: the default is JWT, a "gotcha" return(TokenRestrictionTemplateSerializer.Serialize(objTokenRestrictionTemplate)); }
private string GenerateTokenRequirements() { //TokenRestrictionTemplate template = new TokenRestrictionTemplate(); //template.PrimaryVerificationKey = new SymmetricVerificationKey(); //template.AlternateVerificationKeys.Add(new SymmetricVerificationKey()); //template.Audience = new Uri( myConfig.sampleAudience); //template.Issuer = new Uri( myConfig.sampleIssuer) ; //template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); //return TokenRestrictionTemplateSerializer.Serialize(template); string primarySymmetricKey = "8sAEcbUnsHJOnMpRU0f7z4gAROCoQ3ailkK5ARIt12iDxOu5KTf5mihIbims0uJHTTQQSkO/W+WDTEdFFH7rug=="; string secondarySymmetricKey = "vga/o4PJT+IQAaH1Po0uhBrL7aoUu0prBTO9jmWsk71CFtPwBJiwwBiWMN45NGXp3rDIIi81E3QU0dXg7pmDxw=="; TokenRestrictionTemplate objTokenRestrictionTemplate = new TokenRestrictionTemplate(); objTokenRestrictionTemplate.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(primarySymmetricKey)); objTokenRestrictionTemplate.AlternateVerificationKeys.Add(new SymmetricVerificationKey(Convert.FromBase64String(secondarySymmetricKey))); objTokenRestrictionTemplate.Audience = new Uri(myConfig.sampleAudience); objTokenRestrictionTemplate.Issuer = new Uri(myConfig.sampleIssuer); return(TokenRestrictionTemplateSerializer.Serialize(objTokenRestrictionTemplate)); }
private List <ContentKeyAuthorizationPolicyRestriction> CreateContentKeyAuthPolicyRestrictions(string policyName, ContentProtection contentProtection) { List <ContentKeyAuthorizationPolicyRestriction> policyRestrictions = new List <ContentKeyAuthorizationPolicyRestriction>(); if (contentProtection.ContentAuthTypeAddress) { ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyAddressRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.IPRestricted); policyRestriction.Requirements = GetAddressRangeXml(contentProtection.ContentAuthAddressRange); policyRestrictions.Add(policyRestriction); } if (contentProtection.ContentAuthTypeToken) { string settingKey = Constants.AppSettingKey.DirectoryDiscoveryUrl; string discoveryUrl = AppSetting.GetValue(settingKey); settingKey = Constants.AppSettingKey.DirectoryIssuerUrl; string issuerUrl = AppSetting.GetValue(settingKey); settingKey = Constants.AppSettingKey.DirectoryClientId; string clientId = AppSetting.GetValue(settingKey); TokenRestrictionTemplate tokenTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument(discoveryUrl); tokenTemplate.Issuer = issuerUrl; tokenTemplate.Audience = clientId; ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyTokenRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.TokenRestricted); policyRestriction.Requirements = TokenRestrictionTemplateSerializer.Serialize(tokenTemplate); policyRestrictions.Add(policyRestriction); } if (policyRestrictions.Count == 0) { ContentKeyAuthorizationPolicyRestriction policyRestriction = new ContentKeyAuthorizationPolicyRestriction(); policyRestriction.Name = string.Concat(policyName, Constants.Media.ContentProtection.AuthPolicyOpenRestrictionName); policyRestriction.SetKeyRestrictionTypeValue(ContentKeyRestrictionType.Open); policyRestrictions.Add(policyRestriction); } return(policyRestrictions); }
public void RSATokenVerificationKeyRoundTrip() { TokenRestrictionTemplate template = new TokenRestrictionTemplate(TokenType.JWT); RsaTokenVerificationKey tokenVerificationKey = new RsaTokenVerificationKey(); RSAParameters inputRsaParameters; using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider()) { inputRsaParameters = provider.ExportParameters(true); tokenVerificationKey.InitFromRsaParameters(inputRsaParameters); } Assert.IsNotNull(tokenVerificationKey.RawBody); template.Audience = _sampleAudience; template.Issuer = _sampleIssuer; template.PrimaryVerificationKey = tokenVerificationKey; var templateAsString = TokenRestrictionTemplateSerializer.Serialize(template); Assert.IsTrue(templateAsString.Contains("<PrimaryVerificationKey i:type=\"RsaTokenVerificationKey\">")); TokenRestrictionTemplate output = TokenRestrictionTemplateSerializer.Deserialize(templateAsString); Assert.AreEqual(TokenType.JWT, output.TokenType); Assert.IsNotNull(output.PrimaryVerificationKey); Assert.IsNotNull(output.PrimaryVerificationKey as RsaTokenVerificationKey); RsaTokenVerificationKey key = output.PrimaryVerificationKey as RsaTokenVerificationKey; Assert.IsNotNull(key.RawBody); RSAParameters outputRsaParametersutParameters = key.GetRsaParameters(); Assert.IsNotNull(outputRsaParametersutParameters); Assert.IsNotNull(outputRsaParametersutParameters.Exponent); Assert.IsNotNull(outputRsaParametersutParameters.Modulus); //Check that we are storing only public signing key Assert.IsNull(outputRsaParametersutParameters.P); Assert.IsNull(outputRsaParametersutParameters.Q); Assert.IsNull(outputRsaParametersutParameters.D); Assert.IsNull(outputRsaParametersutParameters.DP); Assert.IsNull(outputRsaParametersutParameters.DQ); //Checking that public key matching Assert.IsTrue(inputRsaParameters.Exponent.SequenceEqual(outputRsaParametersutParameters.Exponent), "Exponent value mismatch"); Assert.IsTrue(inputRsaParameters.Modulus.SequenceEqual(outputRsaParametersutParameters.Modulus), "Modulus value mismatch"); }
private static string GenerateTokenRequirements() { TokenType tType = TokenType.SWT; if (_isTokenTypeJWT) { tType = TokenType.JWT; } TokenRestrictionTemplate template = new TokenRestrictionTemplate(tType); template.PrimaryVerificationKey = new SymmetricVerificationKey(Convert.FromBase64String(_symmetricVerificationKey)); //template.AlternateVerificationKeys.Add(new SymmetricVerificationKey()); template.Audience = _sampleAudience.ToString(); template.Issuer = _sampleIssuer.ToString(); if (_enableKidClaim) { template.RequiredClaims.Add(TokenClaim.ContentKeyIdentifierClaim); } return(TokenRestrictionTemplateSerializer.Serialize(template)); }
private static void CreatePolicyOption(string assetID, CloudMediaContext mediaContext, string claimType, string claim, IContentKeyAuthorizationPolicy policy) { IContentKeyAuthorizationPolicyOption policyOption; List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>(); List <X509Certificate2> certs = GetX509Certificate2FromADMetadataEndpoint(); JwtSecurityToken token = GetJwtSecurityToken(); TokenRestrictionTemplate template = new TokenRestrictionTemplate(); template.TokenType = TokenType.JWT; template.PrimaryVerificationKey = new X509CertTokenVerificationKey(certs[0]); certs.GetRange(1, certs.Count - 1) .ForEach(c => template.AlternateVerificationKeys.Add(new X509CertTokenVerificationKey(c))); //Ignore Empty claims if (!String.IsNullOrEmpty(claimType) && !String.IsNullOrEmpty(claim)) { template.RequiredClaims.Add(new TokenClaim(claimType, claim)); } var audience = token.Audiences.First(); template.Audience = new Uri(audience); template.Issuer = new Uri(token.Issuer); string requirements = TokenRestrictionTemplateSerializer.Serialize(template); ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction { Name = "Authorization Policy with Token Restriction", KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted, Requirements = requirements }; restrictions.Add(restriction); policyOption = mediaContext.ContentKeyAuthorizationPolicyOptions.Create(assetID + "_group:" + claim, ContentKeyDeliveryType.BaselineHttp, restrictions, null); policy.Options.Add(policyOption); }