Wednesday, February 10, 2021

Azure/O365/Teams authentication and monitoring bash curl scripts

Authorize for teams.
Replace YOUR_TENANT_ID, YOUR_EMAIL and YOUR_PASSWORD.
Use one of these client_id’s, depending on your usecase.
1fec8e78-bce4-4aaf-ab1b-5451cc387264 (Teams mobile/desktop application)
5e3ce6c0-2b1f-4285-8d4b-75ee78787346 (Teams web application)

auth.sh:

#!/bin/bash

curl -s -X POST https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/token \
-c cookies.txt \
-o auth.blob \
-F grant_type=password \
-F resource=https://teams.microsoft.com/ \
-F client_id=1fec8e78-bce4-4aaf-ab1b-5451cc387264 \
-F username=YOUR_EMAIL \
-F password=YOUR_PASSWORD

This will save your bearer token, amongst others, to auth.blob in a json object.

Because the bearer token is only valid for a certain period of time, you’ll need to refresh it. Here’s how. You’ll need ‘jq’ installed to decompose the json object.
refresh.sh:

#!/bin/bash

REFRESHTOKEN=`cat auth.blob | jq ".refresh_token" | sed 's/"//g'`

curl -s -X POST https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/token \
-c cookies.txt \
-o auth.blob \
-F grant_type=refresh_token \
-F resource=https://teams.microsoft.com/ \
-F client_id=1fec8e78-bce4-4aaf-ab1b-5451cc387264 \
-F refresh_token=$REFRESHTOKEN

In the script you can keep repeating actions, but in order to keep your token active, you can use the following piece of code:

if [ -f "auth.blob" ]; then
  EXPIRES=`cat auth.blob | jq ".expires_on" | sed 's/"//g'`
  NOW=`date +%s`
  TTL=`expr $EXPIRES - $NOW`
  if [ $TTL -lt 60 ]; then
    echo "time for a refresh!"
    ./refresh.sh
  fi
else
  echo "no previous auth present!"
  ./auth.sh
  EXPIRES=`cat auth.blob | jq ".expires_on" | sed 's/"//g'`
  NOW=`date +%s`
  TTL=`expr $EXPIRES - $NOW`
fi

Now you can do the cool stuff like query your calendar or whatever:

#!/bin/bash

BEARER=`cat auth.blob | jq ".access_token" | sed 's/"//g'`
curl -s --write-out "%{http_code}|%{time_total}n" -o bla.txt "https://teams.microsoft.com/api/mt/emea/beta/me/calendarEvents?StartDate=2021-02-07T23:00:00.000Z&EndDate=2021-02-14T23:00:00.000Z" \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.30866 Chrome/80.0.3987.165 Electron/8.5.1 Safari/537.36" \
-H "authorization: Bearer $BEARER"

Or verify your local timezone:

#!/bin/bash

BEARER=`cat auth.blob | jq ".access_token" | sed 's/"//g'`

date "+%Y.%m.%e %T %N"
curl -v 'https://teams.microsoft.com/api/mt/part/emea-03/beta/me/calendarEvents/timeZoneSettingsWithOffset?timezone=Europe%2FAmsterdam' \
-H "authorization: Bearer $BEARER" \
-H 'authority: teams.microsoft.com'
echo ""
date "+%Y.%m.%e %T %N"