Skip to content

Instantly share code, notes, and snippets.

@henriquemeloo
Last active November 6, 2024 18:35
Show Gist options
  • Save henriquemeloo/5422e8863fce0ce2652dcc59f9743a0f to your computer and use it in GitHub Desktop.
Save henriquemeloo/5422e8863fce0ce2652dcc59f9743a0f to your computer and use it in GitHub Desktop.
Get Bing Ads refresh token
#!/bin/bash
# https://learn.microsoft.com/en-us/advertising/guides/authentication-oauth-get-tokens?view=bingads-13
set -e
# check if CLIENT_ID and CLIENT_SECRET variable are set
if [[ -z $CLIENT_ID ]]; then
echo "Environment variable CLIENT_ID is not set" 1>&2
exit 1
fi
if [[ -z $CLIENT_SECRET ]]; then
echo "Environment variable CLIENT_SECRET is not set" 1>&2
exit 1
fi
open "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=$CLIENT_ID&scope=openid%20profile%20https://ads.microsoft.com/msads.manage%20offline_access&response_type=code&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&state=ClientStateGoesHere&prompt=login" &
echo "Grant consent in the browser, and then paste the response URI here:"
read URL
code=$(echo $URL | grep -Po '(?<=code=)(.*?)(?=\&)')
# Get the initial access and refresh tokens.
response=$(curl https://login.microsoftonline.com/common/oauth2/v2.0/token -H "ContentType=application/x-www-form-urlencoded" -d "client_id=$CLIENT_ID&scope=https://ads.microsoft.com/msads.manage%20offline_access&code=$code&grant_type=authorization_code&redirect_uri=https%3A%2F%2Flogin.microsoftonline.com%2Fcommon%2Foauth2%2Fnativeclient&client_secret=$CLIENT_SECRET")
access_token=$(echo $response | jq -r '.access_token')
refresh_token=$(echo $response | jq -r '.refresh_token')
# The access token will expire e.g., after one hour.
# Use the refresh token to get new access and refresh tokens.
response=$(curl https://login.microsoftonline.com/common/oauth2/v2.0/token -H "ContentType=application/x-www-form-urlencoded" -d "client_id=$CLIENT_ID&scope=https://ads.microsoft.com/msads.manage%20offline_access&code=$code&grant_type=refresh_token&refresh_token=$refresh_token&client_secret=$CLIENT_SECRET")
# $oauthTokens = ($response.Content | ConvertFrom-Json)
echo "Access token: $(echo $response | jq -r '.access_token')"
echo "Access token expires in: $(echo $response | jq -r '.expires_in')"
echo "Refresh token: $(echo $response | jq -r '.refresh_token')"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment