Skip to content

Instantly share code, notes, and snippets.

@clivefoley
Created January 30, 2019 15:16
Show Gist options
  • Save clivefoley/fa52f4fbd82fb4f0701a25b708639c82 to your computer and use it in GitHub Desktop.
Save clivefoley/fa52f4fbd82fb4f0701a25b708639c82 to your computer and use it in GitHub Desktop.
using System;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System.Linq;
namespace CosmosDbSecurityDemo
{
class Program
{
private const string EndpointUrl = "<put your endpoint here>";
private const string MasterKey = "<put your master key here>";
static void Main(string[] args)
{
Console.WriteLine("Welcome to the CosmosDb demo");
Console.WriteLine("Lets login to Azure, press any key when you're ready");
Console.WriteLine();
Console.ReadLine();
try
{
using (var client = new DocumentClient(new Uri(EndpointUrl), MasterKey))
{
var database = client.CreateDatabaseQuery().Where(db => db.Id == "TestDatabase").AsEnumerable().FirstOrDefault();
if (database != null)
{
Console.WriteLine("We found the database called: " + database.Id);
Console.WriteLine("Creating new user...");
var user = createUser(client, database.SelfLink);
var token = giveUserPermissions(client, database.Id, user);
Console.WriteLine("User created with token: " + token);
}
else
{
Console.WriteLine("Database not found :(");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadLine();
}
static User createUser(DocumentClient client, string databaseLink)
{
User docUser = new User { Id = "user" + Guid.NewGuid().ToString() }; //This creates a random user that can be given permissions
var task = client.CreateUserAsync(databaseLink, docUser);
task.Wait();
Console.WriteLine(task.Result.Resource.Id);
return task.Result.Resource;
}
static string giveUserPermissions(DocumentClient client, string databaseId, User user)
{
var link = UriFactory.CreateDocumentCollectionUri(databaseId, "TestCollection");
//This permission gives the user permission to read items in the resource 'TestCollection'
Permission docPermission = new Permission
{
PermissionMode = PermissionMode.Read,
ResourceLink = link.ToString(),
Id = Guid.NewGuid().ToString()
};
Console.WriteLine("Giving user permissions...");
var task = client.CreatePermissionAsync(user.SelfLink, docPermission);
task.Wait();
return task.Result.Resource.Token;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment