Используйте bash curl с oauth для возврата данных учетной записи пользователя google apps? [закрытый]

Я ищу довольно простой способ использовать curl для возврата информации о пакете учетных записей пользователей (например, createddate или lastlogin) в приложениях google. Я очень неопытен в curl и api приложений Google.

кто-нибудь знает хорошую вводную статью о том, как использовать curl с Oauth для запроса данных учетной записи пользователя?

спасибо заранее!

2 ответов


Это нелегко достичь, так как OAuth 2.0 и JSON не легко обрабатываются Bash. Сказав, что вот это базовая версия, которая даст вам данные, которые вы ищете. Greps может использовать некоторую очистку, но опять же, интерпретация JSON с grep плохая идея в любом случае. Это прекрасный пример того, почему библиотеки API Google существуют и должны использоваться.


# Store our credentials in our home directory with a file called .
my_creds=~/.`basename `

# create your own client id/secret
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#creatingcred
client_id='YOUR OWN CLIENT ID'
client_secret='YOUR OWN SECRET'

if [ -s $my_creds ]; then
  # if we already have a token stored, use it
  . $my_creds
  time_now=`date +%s`
else
  scope='https://www.googleapis.com/auth/admin.directory.user.readonly'
  # Form the request URL
  # https://developers.google.com/identity/protocols/OAuth2InstalledApp#step-2-send-a-request-to-googles-oauth-20-server
  auth_url="https://accounts.google.com/o/oauth2/v2/auth?client_id=$client_id&scope=$scope&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"

  echo "Please go to:"
  echo
  echo "$auth_url"
  echo
  echo "after accepting, enter the code you are given:"
  read auth_code

  # exchange authorization code for access and refresh tokens
  # https://developers.google.com/identity/protocols/OAuth2InstalledApp#exchange-authorization-code
  auth_result=$(curl -s "https://www.googleapis.com/oauth2/v4/token" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d code=$auth_code \
    -d client_id=$client_id \
    -d client_secret=$client_secret \
    -d redirect_uri=urn:ietf:wg:oauth:2.0:oob \
    -d grant_type=authorization_code)
  access_token=$(echo -e "$auth_result" | \
                 grep -Po '"access_token" *: *.*?[^\]",' | \
                 awk -F'"' '{ print  }')
  refresh_token=$(echo -e "$auth_result" | \
                  grep -Po '"refresh_token" *: *.*?[^\]",*' | \
                  awk -F'"' '{ print  }')
  expires_in=$(echo -e "$auth_result" | \
               grep -Po '"expires_in" *: *.*' | \
               awk -F' ' '{ print  }' | awk -F',' '{ print }')
  time_now=`date +%s`
  expires_at=$((time_now + expires_in - 60))
  echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi

# if our access token is expired, use the refresh token to get a new one
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#offline
if [ $time_now -gt $expires_at ]; then
  refresh_result=$(curl -s "https://www.googleapis.com/oauth2/v4/token" \
   -H "Content-Type: application/x-www-form-urlencoded" \
   -d refresh_token=$refresh_token \
   -d client_id=$client_id \
   -d client_secret=$client_secret \
   -d grant_type=refresh_token)
  access_token=$(echo -e "$refresh_result" | \
                 grep -Po '"access_token" *: *.*?[^\]",' | \
                 awk -F'"' '{ print  }')
  expires_in=$(echo -e "$refresh_result" | \
               grep -Po '"expires_in" *: *.*' | \
               awk -F' ' '{ print  }' | awk -F',' '{ print  }')
  time_now=`date +%s`
  expires_at=$(($time_now + $expires_in - 60))
  echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi

# call the Directory API list users endpoint, may be multiple pages
# https://developers.google.com/admin-sdk/directory/v1/reference/users/list
while :
do
  api_data=$(curl -s --get https://www.googleapis.com/admin/directory/v1/users \
    -d customer=my_customer \
    -d prettyPrint=true \
    `if [ -n "$next_page" ]; then echo "-d pageToken=$next_page"; fi` \
    -d maxResults=500 \
    -d "fields=users(primaryEmail,creationTime,lastLoginTime),nextPageToken" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $access_token")
  echo -e "$api_data" | grep -v 'nextPageToken'
  next_page=$(echo $api_data | \
    grep -Po '"nextPageToken" *: *.*?[^\]"' | \
    awk -F'"' '{ print  }')
  if [ -z "$next_page" ]
  then
    break
  fi
done

спасибо Джей Ли, Я хотел бы поделиться измененным скриптом для доступа к обычному userinfo (без приложений google). Просто не забудьте включить Google + API на консоли Google API:

# Store our credentials in our home directory with a file called .<script name>
my_creds=~/.`basename `
client_id='********PUT YOURS**********.apps.googleusercontent.com'
client_secret='' # not really a secret
if [ -s $my_creds ]; then
  # if we already have a token stored, use it
  . $my_creds
  time_now=`date +%s`
else
  scope='profile'
  # Form the request URL
  # http://goo.gl/U0uKEb
  auth_url="https://accounts.google.com/o/oauth2/auth?client_id=$client_id&scope=$scope&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"

  echo "Please go to:"
  echo
  echo "$auth_url"
  echo
  echo "after accepting, enter the code you are given:"
  read auth_code

  # swap authorization code for access and refresh tokens
  # http://goo.gl/Mu9E5J
  auth_result=$(curl -s https://accounts.google.com/o/oauth2/token \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d code=$auth_code \
    -d client_id=$client_id \
    -d client_secret=$client_secret \
    -d redirect_uri=urn:ietf:wg:oauth:2.0:oob \
    -d grant_type=authorization_code)
  access_token=$(echo -e "$auth_result" | \
                 grep -Po '"access_token" *: *.*?[^\]",' | \
                 awk -F'"' '{ print  }')
  refresh_token=$(echo -e "$auth_result" | \
                  grep -Po '"refresh_token" *: *.*?[^\]",*' | \
                  awk -F'"' '{ print  }')
  expires_in=$(echo -e "$auth_result" | \
               grep -Po '"expires_in" *: *.*' | \
               awk -F' ' '{ print  }' | awk -F',' '{ print }')
  time_now=`date +%s`
  expires_at=$((time_now + expires_in - 60))
  echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi

# if our access token is expired, use the refresh token to get a new one
# http://goo.gl/71rN6V
if [ $time_now -gt $expires_at ]; then
  refresh_result=$(curl -s https://accounts.google.com/o/oauth2/token \
   -H "Content-Type: application/x-www-form-urlencoded" \
   -d refresh_token=$refresh_token \
   -d client_id=$client_id \
   -d client_secret=$client_secret \
   -d grant_type=refresh_token)
  access_token=$(echo -e "$refresh_result" | \
                 grep -Po '"access_token" *: *.*?[^\]",' | \
                 awk -F'"' '{ print  }')
  expires_in=$(echo -e "$refresh_result" | \
               grep -Po '"expires_in" *: *.*' | \
               awk -F' ' '{ print  }' | awk -F',' '{ print  }')
  time_now=`date +%s`
  expires_at=$(($time_now + $expires_in - 60))
  echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi

# call the Directory API list users endpoint, may be multiple pages
# http://goo.gl/k0jnQJ
  api_data=$(curl -s --get https://www.googleapis.com/plus/v1/people/me \
    -d prettyPrint=true \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $access_token")
  echo -e "$api_data"