Where to store DocumentDB Endpoint and Key in production - azure

I have a .Net Core website and Xamarin app that talk to Documentdb and we are preparing to go to production.
All docs I have seen on DocumentDB / CosmosDB hard copy the Key and Endpoint in a C# class. Example: https://learn.microsoft.com/en-us/azure/cosmos-db/tutorial-develop-documentdb-dotnet , http://www.dotnetcurry.com/windows-azure/1395/cosmosdb-webapi-angular-client , to list a few (!), and Azure Security in DocumentDB does not seem to address or mention this issue.
Is there a way to securely store DocuementDB EndPoint and Key in client apps?
Thank you.

You should never use the keys in applications. Azure Key Vault solve this problem.
Please check this
https://sarosh.wordpress.com/2017/11/23/cosmos-db-and-key-vault/
HTH

KeyChain.Net
A simple and unified api that enables developer to set, update, get and delete keys and passwords on the keyChain (supports iOS, Android, and WinPhone)
https://github.com/has-taiar/KeyChain.Net
iOS
var helper = new KeyChain.Net.XamarinIOS.KeyChainHelper();
var isSaved = helper.SetKey("myKey", "myKeyValue");
var keyValue = helper.GetKey("myKey");
var isDeleted = helper.DeleteKey("myKey");
Android
var helper = new KeyChain.Net.XamarinAndroid.KeyChainHelper(myActivity, "myKeyProtectionPassword");
var isSaved = helper.SetKey("myKey", "myKeyValue");
var keyValue = helper.GetKey("myKey");
var isDeleted = helper.DeleteKey("myKey");
Windows Phone
var helper = new KeyChain.Net.XamarinWinRT.KeyChainHelper();
var isSaved = helper.SetKey("myKey", "myKeyValue");
var keyValue = helper.GetKey("myKey");
var isDeleted = helper.DeleteKey("myKey");

Related

How to Get Azure Event Hub Connection String in C#?

Given a Event Hub Name, how can I get connection string in C#?
I googled a bit, but nothing useful found so far.
Thanks
Using AAD authentication for an EventHub
var credential = new DefaultAzureCredential();
// or use
// var credential = new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret");
EventHubProducerClient producerClient = new EventHubProducerClient(txtNamespace.Text, txtEventHub.Text, credential
var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, txtNamespace.Text, txtEventHub.Text, credential)
Full example and docs
Acquiring the Connection Strings of configured Access Policies
You can use these two Nuget packages:
Azure.ResourceManager.EventHubs
Azure.Identity
Then you can use the resource group name and the eventhub name to retrieve the connection string. You will need to iterate the subscriptions and resource groups if you don't have this information.
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.EventHubs;
ArmClient client = new ArmClient(new DefaultAzureCredential());
// Or use
// ArmClient client = new ArmClient(new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret"));
var subscription = await client.GetDefaultSubscriptionAsync();
var resourceGroup = await subscription.GetResourceGroupAsync("myresourcegroup");
var eventhubNamespace = await resourceGroup.Value.GetEventHubsNamespaceAsync("namespacename");
var rules = eventhubNamespace.Value.GetEventHubsNamespaceAuthorizationRules();
foreach (var rule in rules)
{
var keys = await rule.GetKeysAsync();
Console.WriteLine(keys.Value.PrimaryConnectionString);
Console.WriteLine(keys.Value.SecondaryConnectionString);
}
Not sure if this is what you mean, but if you want to access an Event Hub through C# you need to provide the EH connection string into your code. This can be retrieved by adding a Shared access policy for the Event hub that you are trying to access.
Edit: If you are trying to actually create the connection string yourself you could follow this sample where you create the SAS-token yourself. But you would still need to provide the Primary key that is set on the policy from Azure.

DocumentDB connection string

Azure application settings (for azure function) has a option for a DocumentDB connection string
Anyone have any idea how this should be populated/formatted?
i currently use:
var documentDbEndpointUri = new Uri(ConfigurationManager.AppSettings["DocumentDbEndpointUri"]);
var documentDbAuthKey = ConfigurationManager.AppSettings["DocumentDbAuthKey"];
return new DocumentClient(documentDbEndpointUri, documentDbAuthKey);
Although I'd like to switch to a single value connection string.
Try AccountEndpoint=https://accountname.documents.azure.com:443/‌​;AccountKey=accountk‌​ey==;Database=database
Firstly, as #Gaurav Mantri said in comment, currently DocumentClient does not have constructor overloads using connection string, you cannot directly use a connection string to create an instance of DocumentClient even if you provide/add connection string for DocumentDB in Azure application settings.
Note: here is a feedback for this issue, if you have same feature request, you can vote for it.
Secondly, If you’d like to access the DocumentDB service via DocumentClient, you can add both DocumentDbEndpointUri and DocumentDbAuthKey in App settings, and then read them in function code.
var serviceEndpoint = System.Configuration.ConfigurationManager.AppSettings["DocumentDbEndpointUri"];
var authKey = System.Configuration.ConfigurationManager.AppSettings["DocumentDbAuthKey"];
//or
//var serviceEndpoint = Environment.GetEnvironmentVariable("DocumentDbEndpointUri");
//var authKey = Environment.GetEnvironmentVariable("DocumentDbAuthKey");

How to Authenticate and Authorize Asp.Net Web application through QuickBooks?

how to Authenticate and Authorize Asp.Net Web application through QuickBooks.
I want to integrate QuickBooks Accounts System in ASP.NET web Application I have successfully make developer account on quickbooks and make an app and got consumer key, consumer Secret and App Token and all URL's
Know I need some asp.net web api code snipped to successfully authenticate and authorize my web user's and than show there accounting detail
Please help me i Google alot but have no success.
I'm Strange this form is 0% active related to quickbooks API's or etc, after alot of struggling i found an answer of above mention question,
Download Quickbooks IPP.NET SDK it will provide you different classes for CURD.
var appToken = "";
var consumerKey = "";
var consumerSecret = "";
// the above 3 fields you can get when create your app on quickbook go to My app----> select youre app--->goto KEYS
var accessToken = "";
var accessTokenSecret = "";
// this two tookens you will get from URL on the same above page
var realmId = "1400728630"; //1400728630
// this is youre company ID which can be used when you create youre //company on freshbook
var serviceType = IntuitServicesType.QBO;
var validator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
var context = new ServiceContext(appToken,realmId, serviceType, validator);
var service = new DataService(context);
try
{
Customer customer = new Customer();
//Mandatory Fields
customer.GivenName = "Mary";
customer.Title = "Ms.";
customer.MiddleName = "Jayne";
customer.FamilyName = "Cooper";
service.AddAsync(customer);
//service.Add(entity);
}catch(Exception ex)
{
System.Console.WriteLine(ex);
}

Change Azure website app settings from code

Is it possible to change the app settings for a website from the app itself?
This is not meant to be an everyday operation, but a self-service reconfiguration option. A non-developer can change a specific setting, which should cause a restart, just like I can do manually on the website configuration page (app setting section)
You can also use the Azure Fluent Api.
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
...
public void UpdateSetting(string key, string value)
{
string tenantId = "a5fd91ad-....-....-....-............";
string clientSecret = "8a9mSPas....................................=";
string clientId = "3030efa6-....-....-....-............";
string subscriptionId = "a4a5aff6-....-....-....-............";
var azureCredentials = new AzureCredentials(new
ServicePrincipalLoginInformation
{
ClientId = clientId,
ClientSecret = clientSecret
}, tenantId, AzureEnvironment.AzureGlobalCloud);
var _azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(azureCredentials)
.WithSubscription(subscriptionId);
var appResourceId = "/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Web/sites/xxx"; //Get From WebApp -> Properties -> Resource ID
var webapp = _azure.WebApps.GetById(appResourceId);
//Set App Setting Key and Value
webapp.Update()
.WithAppSetting(key, value)
.Apply();
}
It wasn't that hard once I found the right lib to do it, Microsoft Azure Web Sites Management Library.
var credentials = GetCredentials(/*using certificate*/);
using (var client = new WebSiteManagementClient(credentials))
{
var currentConfig = await client.WebSites.GetConfigurationAsync(webSpaceName,
webSiteName);
var newConfig = new WebSiteUpdateConfigurationParameters
{
ConnectionStrings = null,
DefaultDocuments = null,
HandlerMappings = null,
Metadata = null,
AppSettings = currentConfig.AppSettings
};
newConfig.AppSettings[mySetting] = newValue;
await client.WebSites.UpdateConfigurationAsync(webSpaceName, webSiteName,
newConfig);
}
Have you read into the Service Management REST API? The documentation mentions that it allows you to perform most the actions that are available via the Management Portal programmatically.
In addition to Diego answer, to use the Azure Management Librairies within a WebApp (WebSites and/or WebJobs), you need to configure SSL which is a little bit tricky:
Using Azure Management Libraries from Azure Web Jobs

Extend functionality of Azure Mobile Services using ASP.NET Identity

I have a .Net Mobile Services back end (i.e. not the JavaScript one) which out of the box supports authentication with the common Identity Providers (facebook, twitter, etc) through the windows azure portal. However I would like users to be able to create their own username/password accounts as they can do with the ASP.NET Web Api implementation of ASP.NET Identity (using AccountController).
The question is if this is possible and if so what is the best way of achieving it?
My first thought was to just copy the appropriate classes (AccountController, Startup.Auth, ApplicationOAuthProvider, etc) from a template ASP.NET MVC Web Api project and add a reference to Microsoft.AspNet.Identity.EntityFramework and System.Web.MVC but I don't know what impact this would have. If it worked would I have just taken control of the Authentication logic with the portal "Identity" no longer having any effect?
The other option is to simply start with a Web Api project and add the Mobile Services functionality to that instead (Although I couldn't see how to create a Web Api project without MVC but that is a different question).
Thanks for any help.
UPDATE 11 April 2014
In the end we decided to manage our own username and passwords and generate a JWT token so that the client could use the standard IMobileServiceClient. To do this we used two resources. The first was from the joy of code:
http://www.thejoyofcode.com/Exploring_custom_identity_in_Mobile_Services_Day_12_.aspx
and the second was from content master:
http://www.contentmaster.com/azure/creating-a-jwt-token-to-access-windows-azure-mobile-services/
Although we made some small changes to the code as per this Mobile Services team blog post:
[Don't have enough reputation points to add a third link so just google "changes-in-the-azure-mobile-services-jwt-token"]
So here is the code if useful. (it might be better to write an implementation using JwtSecurityTokenHandler but this works for us)
public static string GetSecurityToken(TimeSpan periodBeforeExpires, string aud, string userId, string masterKey)
{
var now = DateTime.UtcNow;
var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var payload = new
{
exp = (int)now.Add(periodBeforeExpires).Subtract(utc0).TotalSeconds,
iss = "urn:microsoft:windows-azure:zumo",
ver = 2,
aud = "urn:microsoft:windows-azure:zumo",
uid = userId
};
var keyBytes = Encoding.UTF8.GetBytes(masterKey + "JWTSig");
var segments = new List<string>();
//kid changed to a string
var header = new { alg = "HS256", typ = "JWT", kid = "0" };
byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
segments.Add(Base64UrlEncode(headerBytes));
segments.Add(Base64UrlEncode(payloadBytes));
var stringToSign = string.Join(".", segments.ToArray());
var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
SHA256Managed hash = new SHA256Managed();
byte[] signingBytes = hash.ComputeHash(keyBytes);
var sha = new HMACSHA256(signingBytes);
byte[] signature = sha.ComputeHash(bytesToSign);
segments.Add(Base64UrlEncode(signature));
return string.Join(".", segments.ToArray());
}
// from JWT spec
private static string Base64UrlEncode(byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.Split('=')[0]; // Remove any trailing '='s
output = output.Replace('+', '-'); // 62nd char of encoding
output = output.Replace('/', '_'); // 63rd char of encoding
return output;
}
This is possible but not quite as simple as we would like (we have a bug on improving it). In general it boils down to that you can inject things into the OWIN pipeline including auth providers.
If you are familiar with the OWIN pipeline and ASP.NET Identity Framework then here's roughly what you do:
1) Crate your own OWIN App Builder which sets up the OWIN pipeline for the .NET backend.
2) Register your App Builder with the Dependency Injection engine which will get called as part of the initialization.
Here is a gist of what it looks like (using the latest NuGets from nuget.org):
https://gist.github.com/HenrikFrystykNielsen/9835526
It won't automatically get hooked into the "login" controller we have a work item to enable this but I think it should work if you are careful.
Btw, you can find some good information from Filip W's blog: http://www.strathweb.com/2014/02/running-owin-pipeline-new-net-azure-mobile-services/
Hope this helps!
Henrik

Resources