This post offers a detailed description and even an example how to handle users and permissions in CosmosDB.
Alternatively, if you just want to get the oid from the received token and use this as the partition key, I'd go for an approach as shown here and then just create queries based on the value.
Setup (Nuget) for Azure Functions v3, .NET Core 3.1:
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.8" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.9" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.CosmosDB" Version="3.0.7" />
[FunctionName("CosmosDBAccess")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
[CosmosDB(ConnectionStringSetting = "CosmosDBConnection")]DocumentClient client,
ILogger log)
{
// Get oid from your token
var token = string.Empty;
var hasToken = req.Headers.TryGetValue("Authorization", out var tokenHeader);
if (hasToken)
{
// Assuming token is in header as "Bearer <token>"
token = tokenHeader[0].Split(" ")[1];
}
var handler = new JwtSecurityTokenHandler();
var tokenS = handler.ReadToken(token) as JwtSecurityToken;
var jti = tokenS.Claims.First(claim => claim.Type == "oid").Value;
// Create query
var uri = UriFactory.CreateDocumentCollectionUri("db", "collection");
using (var query = client.CreateDocumentQuery(uri,
new FeedOptions() { PartitionKey = new Microsoft.Azure.Documents.PartitionKey(jti) })
.AsDocumentQuery())
{
while (query.HasMoreResults)
{
// Get results
FeedResponse<Document> recordSet = await query.ExecuteNextAsync<Document>();
}
}
// more stuff
This returns all documents where the partition key equals the oid from the authorized calling user.
// Edit: Here I've added a sample for JS. However, I don't have any clue how to get the oid from the token. If you manage to obtain it, I think this might work. Please excuse my "bad practice" when it comes to JS, I don't use that at all.
module.exports = async function (context, req) {
const { CosmosClient } = require("@azure/cosmos");
const endpoint = "<your-cosmosdb-connection>";
const key = "<your-key>"
const client = new CosmosClient({ endpoint, key });
var results = []
async function main() {
// Get oid
var oid = req.headers.authorization.split(" ")[1]
console.log(oid)
// Get Database
const { database } = await client.databases.createIfNotExists({ id: "db" });
console.log(database.id);
// Get Collection
const { container } = await database.containers.createIfNotExists({ id: "collection" });
console.log(container.id);
// Query items
const { resources } = await container.items
.query("SELECT * from c", { partitionKey: oid })
.fetchAll();
for (var r of resources)
{
results.push(r)
console.log(r.id)
}
}
main().catch((error) => {
console.error(error);
});
await main()
// Return response
context.res = {
// status: 200, /* Defaults to 200 */
body: results
};
}