OAuth2 - Script de demande d'un jeton
The snippet can be accessed without any authentication.
Authored by
erwan.salmon
Script autour de curl pour obtenir un jeton de session oauth2 dans le flow client credentials utilisé par les API manager. Validé sur les services Wso2 MTE et Piste.
Requête curl
La requête de base, sans la gestion des I/O et des erreurs :
$ curl -d "grant_type=client_credentials" -u "[CLIENT_ID]:[CLIENT_SECRET]" [URL_TOKEN]
Prérequis du script :
- curl
- jq (https://stedolan.github.io/jq/)
Informations d'authentification
L'adresse d'authentification (token), l'identifiant et le secret peuvent être transmis de 2 façon
- En arguments directs du script
- Syntaxe : oauth2_token.sh [CLIENT_ID] [CLIENT_SECRET] [URL_TOKEN]
-
[CLIENT_ID]
: identifiant d'authentification oauth2 -
[CLIENT_SECRET]
: secret d'authentification oauth2 -
[URL_TOKEN]
: adresse du endpoint d'authentification
- Via un fichier profil fourni en unique argument définissant les 3 variables ci-dessus
- Syntaxe : oauth2_token.sh [PROFIL]
-
[PROFIL]
: chemin complet vers le fichier ou un identifiant résolu en$HOME/.config/o2token/[PROFIL].o2rc
.
#!/bin/sh
# Authentification Oauth2 en flow client_credentials
#
# Usage :
# oauth2_token.sh [CLIENT_ID] [CLIENT_SECRET] [URL_TOKEN]
# oauth2_token.sh [PROFIL]
#
# Le script est essentiellement un emballage sur une simple requête curl :
# curl -d "grant_type=client_credentials" -u "CLIENT_ID:CLIENT_SECRET" URL_TOKEN
err() {
echo $1 >&2
}
usage() {
echo "Usage :"
echo " $(basename $0) [CLIENT_ID] [CLIENT_SECRET] [URL_TOKEN]"
echo " $(basename $0) [PROFIL]"
}
# Récupération des informations d'authentification
CONFIG_DIR=$HOME/.config/o2token
if [ $# -eq 1 ]; then
# En fichier de profil
[ -f "$1" ] && . $1
[ -f "$CONFIG_DIR/$1.o2rc" ] && . "$CONFIG_DIR/$1.o2rc"
[ -z "$O2_CLIENT_ID" ] && err "Configuration incorrecte : $1" && exit 1
else
# En ligne de commande
if [ $# -ge 3 ]; then
O2_CLIENT_ID=$1
O2_CLIENT_SECRET=$2
O2_URL_TOKEN=$3
else
usage && exit 1
fi
fi
# Capture de la réponse Json
O2_TOKEN_JSON=$(curl -s -S $O2_URL_TOKEN \
-d "grant_type=client_credentials" \
-u "$O2_CLIENT_ID:$O2_CLIENT_SECRET" \
)
[ -z "$O2_TOKEN_JSON" ] && err "Erreur d'authentification" && exit 2
# Extraction du token, code error si inexistant (-e)
O2_TOKEN=$(echo $O2_TOKEN_JSON | jq -re .access_token)
# Restitution
if [ $? -eq 0 ]; then
echo "$O2_TOKEN"
else
err "Echec d'authentification"
err "$O2_TOKEN_JSON"
exit 3
fi
Please register or sign in to comment