I am working on open source community project Azure Media Services Upload and Play Videos in MVC since 2015. I was not using any delivery encryption earlier, so I started working on AES.
In all the source code/samples by Azure Media Services Team, i noticed test token was being generated just after uploading the content and this works well in my case too. But, how do I generate test token next time onward for playback?
What I understood is that, we need token each time player requests playback. Technically, player creates a request to key service provider and received updated token.
So to get updated token, I tried couple of ways n not able to fix this, i see error "A ContentKey (Id = '...', Type = 'EnvelopeEncryption') which contains the same type already links to this asset".
This looks like a valid error message because key of type EnvelopeEncryption was already added and associated with asset after uploading content, and upon requesting again this pops-up.
The code given below is copied from here.
public ActionResult Index()
{
var model = new List<VideoViewModel>();
var videos = db.Videos.OrderByDescending(o => o.Id).ToList();
foreach (var video in videos)
{
var viewModel = new VideoViewModel();
viewModel.Id = video.Id;
viewModel.EncodedAssetId = video.EncodedAssetId;
viewModel.IsEncrypted = video.IsEncrypted;
viewModel.LocatorUri = video.LocatorUri;
// If encrypted content, then get token to play
if (video.IsEncrypted)
{
IAsset asset = GetAssetById(video.EncodedAssetId);
IContentKey key = CreateEnvelopeTypeContentKey(asset);
viewModel.Token = GenerateToken(key);
}
model.Add(viewModel);
}
return View(model);
}
Above method calls media service key service provider.
How do I fix this?
You can look into AMS explorer sources
when you creating a restriction policy yo are doing something like this:
//Initilizing ContentKeyAuthorizationPolicyRestriction
ContentKeyAuthorizationPolicyRestriction restriction = new ContentKeyAuthorizationPolicyRestriction
{
Name = "Authorization Policy with Token Restriction",
KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
Requirements = TokenRestrictionTemplateSerializer.Serialize(restrictionTemplate)};
restrictions.Add(restriction);
//Saving IContentKeyAuthorizationPolicyOption on server so it can be associated with IContentKeyAuthorizationPolicy
IContentKeyAuthorizationPolicyOption policyOption = objCloudMediaContext.ContentKeyAuthorizationPolicyOptions.Create("myDynamicEncryptionPolicy", ContentKeyDeliveryType.BaselineHttp, restrictions, String.Empty);
policy.Options.Add(policyOption);
//Saving Policy
policy.UpdateAsync();
Key field here is irements = TokenRestrictionTemplateSerializer.Serialize(restriction.Requirements)};
You need to fetch corresponding asset restriction you created first place and desirialize TokenRestriction Template back with
TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);
Based on what type of key and encryption you use
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).Certificate;
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();
string token = handler.WriteToken(token);
Related
I am using Dialogflow and would like to know if through the questions of a user to a bot it is possible to identify which user is asking this question.
Attached is a section of the code for reading the data already received.
I tried using the google documentation ('' https://developers.google.com/assistant/identity/google-sign-in#java "), but was unsuccessful.
WebhookRequest request;
using (var reader = new StreamReader(Request.Body))
{
request = jsonParser.Parse<WebhookRequest>(reader);
}
var pas = request.QueryResult.Parameters;
var queryText = request.QueryResult.QueryText;
var response = new WebhookResponse();
StringBuilder sb = new StringBuilder();
//interactionDAO.SaveInteration(new Interaction(Guid.NewGuid(), "google", queryText));
var intent = request.QueryResult.Intent.DisplayName;
var listaObjetos = await _service.DetectIntentAsync(new[] { queryText }, intent);
foreach (var item in listaObjetos)
{
var convertItem = JsonConvert.DeserializeObject<Fulfillment>(item.ToString());
if (!String.IsNullOrWhiteSpace(convertItem.FulfillmentText))
{
sb.Append(convertItem.FulfillmentText);
}
if (convertItem.Parameters != null && convertItem.Parameters.ContainsKey("date-time"))
{
sb.Append(convertItem.Parameters["date-time"]);
}
//sb.Append(item);
}
response.FulfillmentText = sb.ToString();
return Json(response);
Look for "session" in the JSON you receive in your webhook from DialogFlow, it is a unique identifier for the conversation.
Usually it has a format like this:
"session": "projects/${PROJECTID}/agent/sessions/${SESSIONID}"
Just extract the SESSIONID from the last part.
You can find more about DialogFlow Webhook JSON format here:
https://developers.google.com/assistant/actions/build/json/dialogflow-webhook-json
DialogFlow generally only identifies the session. Providing data to uniquely identify the user is part of the client and usually included in the payload.
For example, a signed in user from Google Assistant can be extracted like this (requires the System.IdentityModel.Tokens.Jwt package):
WebhookRequest request;
if (!request.OriginalDetectIntentRequest.Payload.Fields.ContainsKey("user"))
{
throw new ArgumentException("Payload does not contain user.");
}
string idToken = request.OriginalDetectIntentRequest.Payload.Fields["user"]
.StructValue.Fields["idToken"].StringValue;
var userInfo = new JwtSecurityTokenHandler().ReadJwtToken(idToken).Payload;
if (!userInfo["iss"].ToString().EndsWith("accounts.google.com")
|| !userInfo["aud"].ToString().Equals("((your_action_id))")
{
throw new SecurityException("Issuer or authentication token do not match expected value.");
}
string accountName = userInfo["email"].ToString();
if (string.IsNullOrEmpty(accountName))
{
throw new ArgumentException("Id token does not contain mail address.");
}
return accountName;
You need to configure the project as detailed in the article you already linked. It is then possible to mark any DialogFlow intent as "Sign-in required" via the Google Assistant integration settings or use the helper intent for optional sign-in (see this question for details on implementing the helper).
I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!
We have set the Azure AD as a identity provider in our application. We want to display profile picture that should come from Azure AD, in the application.
In order to test, I have added one Windows Live Id account (which has a profile picture) in the Azure AD. We then tried it using Graph Explorer, but no luck.
How do we get the profile picture from Azure AD?
You can use Azure Active Directory Graph Client to get user thumbnail photo
var servicePoint = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(servicePoint, "<your tenant>"); //e.g. xxx.onmicrosoft.com
const string clientId = "<clientId>";
const string secretKey = "<secretKey>";// ClientID and SecretKey are defined when you register application with Azure AD
var authContext = new AuthenticationContext("https://login.windows.net/<tenant>/oauth2/token");
var credential = new ClientCredential(clientId, secretKey);
ActiveDirectoryClient directoryClient = new ActiveDirectoryClient(serviceRoot, async () =>
{
var result = await authContext.AcquireTokenAsync("https://graph.windows.net/", credential);
return result.AccessToken;
});
var user = await directoryClient.Users.Where(x => x.UserPrincipalName == "<username>").ExecuteSingleAsync();
DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync();
using (MemoryStream s = new MemoryStream())
{
photo.Stream.CopyTo(s);
var encodedImage = Convert.ToBase64String(s.ToArray());
}
Azure AD returns user's photo in binary format, you need to convert to Base64 string
Getting photos through Graph Explorer is not supported. Assuming that "signedInUser" already contains the signed in user entity, then this code snippet using the client library should work for you...
#region get signed in user's photo
if (signedInUser.ObjectId != null)
{
IUser sUser = (IUser)signedInUser;
IStreamFetcher photo = (IStreamFetcher)sUser.ThumbnailPhoto;
try
{
DataServiceStreamResponse response =
photo.DownloadAsync().Result;
Console.WriteLine("\nUser {0} GOT thumbnailphoto", signedInUser.DisplayName);
}
catch (Exception e)
{
Console.WriteLine("\nError getting the user's photo - may not exist {0} {1}", e.Message,
e.InnerException != null ? e.InnerException.Message : "");
}
}
#endregion
Alternatively you can do this through REST and it should look like this:
GET https://graph.windows.net/myorganization/users//thumbnailPhoto?api-version=1.5
Hope this helps,
According to the Azure AD Graph API Docs, Microsoft recommends transitioning to Microsoft Graph, as the Azure AD Graph API is being phased out.
However, to easily grab the photo via Azure AD, for now, use this URL template:
https://graph.windows.net/myorganization/users/{user_id}/thumbnailPhoto?api-version={version}
For example (this is a fake user id):
https://graph.windows.net/myorganization/users/abc1d234-01ab-1a23-12ab-abc0d123e456/thumbnailPhoto?api-version=1.6
The code below assumes you already have an authenticated user, with a token. This is a simplistic example; you'll want to change the return value to suit your needs, add error checking, etc.
const string ThumbUrl = "https://graph.windows.net/myorganization/users/{0}/thumbnailPhoto?api-version=1.6";
// Attempts to retrieve the thumbnail image for the specified user, with fallback.
// Returns: Fully formatted string for supplying as the src attribute value of an img tag.
private string GetUserThumbnail(string userId)
{
string thumbnail = "some base64 encoded fallback image";
string mediaType = "image/jpg"; // whatever your fallback image type is
string requestUrl = string.Format(ThumbUrl, userId);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetToken());
HttpResponseMessage response = client.GetAsync(requestUrl).Result;
if (response.IsSuccessStatusCode)
{
// Read the response as a byte array
var responseBody = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
// The headers will contain information on the image type returned
mediaType = response.Content.Headers.ContentType.MediaType;
// Encode the image string
thumbnail = Convert.ToBase64String(responseBody);
}
return $"data:{mediaType};base64,{thumbnail}";
}
// Factored out for use with other calls which may need the token
private string GetToken()
{
return HttpContext.Current.Session["Token"] == null ? string.Empty : HttpContext.Current.Session["Token"].ToString();
}
TL;DR : Is there any way to use the auth=CREDENTIALS with the Simple Login (Email/Password) in Firebase?
I am trying to connect my C# Application's users to my Firebase. I could set up pretty much all calls using my Secret Token, but now I need to be able to, at least, get the current user UID so I know where the data should be sent to.
The way I went with my PUSH, PUT, GET request was something like this, using my secret token as login:
var authToken = "SECRET";
url = "https://MyLocation.firebaseio.com/" + url + ".json?auth=" + authToken;
return WebRequest.Create(url);
But now I'd like to get something supporting the Email/Password simple login, something like this:
var authToken = "{email:an#email.com, password:thePassword}";
url = "https://MyLocation.firebaseio.com/" + url + ".json?auth=" + authToken;
return WebRequest.Create(url);
My tries using CURL weren't successful... Maybe there's no way to do that? or any suggestions?
Thanks for the help!
I spoke with the support at Firebase and found a temporary solution, and a real solution.
Real solution: Manage the user and their password manually in all environments, using Firebase as "Database". That was basically what I was trying to do with my question. That resolve in using Firebase custom auth.
Temporary solution: (And what I did as I do not need as much security as the real solution offers)
Get something that identify the current user. Here I can get the current user email without even asking him.
Base64 the identifier:
byte[] result = System.Text.Encoding.UTF8.GetBytes(email);
email = Convert.ToBase64String(result);
Put, push, patch the required information via REST to firebaseio.com/Base64
In the user interface, that uses JavaScript, do the same process to read/write data at the user, using something like base64.min.js
var ref = new Firebase("https://aFirebase.firebaseio.com");
//Things happen
...
//We register a user
function createUser(email, password){
//Allows us to create a user within firebase
ref.createUser({
email : email,
password : password
}, function(error, userData){
if (error) {
//The creation of the user failed
alert(error);
} else {
//The creation of the user succeeded
console.log("Successfully created user account with uid:", userData.uid);
//We make sure we are at the correct position in our firebase
ref = ref.root().child(base64.encode(email));
//We check if the child exist
if(ref == ref.root()){
//The child doesn't exist
//We have to create it
user = {};
//Set the child with a value for the UID, that will fit with the rules
user[base64.encode(email)] = {uid:userData.uid};
//We set the new child with his value in firebase
ref.set(user);
}else{
//The child exist, we can update his information to go accordingly with our rules
ref.update({uid:userData.uid});
}
//Who wants to register and then not be logged in?
//We can add something upon login if his email is not validated...
login(email, password);
}
}
);
}
Now we have to update our rules in Firebase:
{
"rules": {
"$uid":{
".read":"!(data.child('uid').exists() == true) || data.child('uid').val() == auth.uid",
".write":"!(data.child('uid').exists() == true) || data.child('uid').val() == auth.uid"
}
}
}
With this, the application is somehow secure (as long as the user use the C# application and the JS application, where the rules will be set).
In case of a WebApi application a JWT token could be used along with OWIN pipeline.
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { FirebaseValidAudience },
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = OnValidateIdentity
},
TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKeys = issuerSigningKeys,
ValidAudience = FirebaseValidAudience,
ValidIssuer = FirebaseValidIssuer,
IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => issuerSigningKeys
}
});
Here is the sample of Firebase ASP.NET WebApi Authentication application: https://github.com/PavelDumin/firebase-webapi-auth
My session expires every hour and I can't find documentation on how to refresh token when I'm using service accounts authentication method. For installed applications I'm able to get RefreshToken from state object
AuthorizationState state = new AuthorizationState(new[]
{
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.readonly"
})
{
Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl)
}
state = client.ProcessUserAuthorization(GetAuthorizationCode(), state);
Console.WriteLine(state.RefreshToken);
but how to do that for service accounts?
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "mysecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
ServiceAccountUser = "myemail#mydomain.com",
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DriveService service = DriveService(auth);
from Google SDK source codes I found that AssertionFlowClient.GetState function performs the following
IAuthorizationState state = new AuthorizationState(provider.Scope.Split(' '));
if (provider.RefreshToken(state, null)) {
return state;
} else {
return null;
}
So looks like it does token refresh. I added this function call to my token refresh timer, but it doesn't help. I still continue to get Invalid credentials exception after one hour.
Service accounts do not use refresh tokens. You simply need to request another access token using the same procedure you used the first time. See Google's documentation on what to do when access tokens expire.