Skip to content

Instantly share code, notes, and snippets.

@ivarprudnikov
Created September 21, 2022 15:57
Show Gist options
  • Save ivarprudnikov/42ec3c6a0273d6ab32949bfc791afa11 to your computer and use it in GitHub Desktop.
Save ivarprudnikov/42ec3c6a0273d6ab32949bfc791afa11 to your computer and use it in GitHub Desktop.
Create CosmosDB authorization token
#!/bin/env bash
set -e
# Generate Cosmos DB authorization header
# and create a database in the emulator
# HTTP-date
# https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
ISSUE_DATE=$(TZ=GMT date '+%a, %d %b %Y %T %Z')
# Issue date will go into one header
echo "x-ms-date: $ISSUE_DATE"
# The date needs to be lowercased before the signature
ISSUE_DATE_LOWER=$(echo -n "$ISSUE_DATE" | tr '[:upper:]' '[:lower:]')
# Base64 encoded master key
MASTER_KEY_BASE64="awdawdwadawdawdadadawdawdaawdawdawawdawd/Jw=="
# Database operations: dbs
# Container operations: colls
# Stored Procedures: sprocs
# User Defined Functions: udfs
# Triggers: triggers
# Users: users
# Permissions: permissions
# Item level operations: docs
RESOURCE_TYPE="dbs"
# Empty when creating a new database
RESOURCE_LINK=""
# Verb needs to be lowercase
# get, post, ...
VERB="post"
# Get key bytes
KEY=$(echo -n "$MASTER_KEY_BASE64" | base64 -d)
# Generate signature
SIG=$(printf "%s\n%s\n%s\n%s\n\n" "$VERB" "$RESOURCE_TYPE" "$RESOURCE_LINK" "$ISSUE_DATE_LOWER" | openssl sha256 -hmac "$KEY" -binary | base64)
# encode the query
AUTH=$(printf %s "type=master&ver=1.0&sig=$SIG"|jq -sRr @uri)
echo "Authorization: $AUTH"
curl -k -d '{"id":"foobar"}' 'https://localhost:8081/dbs' \
-H 'x-ms-date: $ISSUE_DATE' \
-H 'Authorization: $AUTH' \
-H "x-ms-version: 2015-08-06"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment