diff --git a/foursquare.html b/foursquare.html deleted file mode 100644 index 581657af772d00d60081fe426859f47d385dd352..0000000000000000000000000000000000000000 --- a/foursquare.html +++ /dev/null @@ -1,45 +0,0 @@ -<html> -<head> - <title>Example App</title> - <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> -</head> -<body> - - <div id="login"> - <a href="https://foursquare.com/oauth2/authenticate?client_id=IFMKONPESAZI2NG3D2QWFTJISPVEITNB2IEKTZ0WVLGZKEFI&response_type=token&redirect_uri=http://localhost/foursquare.html">Log In</a> - </div> - - <div id="signed-in" style="display: none;"> - <h2 id="header">Your last 10 checkins</h2> - <div id="checkins"> - </div> - </div> - - <script> - $(function(){ - var token; - if(window.location.hash - && (token=window.location.hash.match("access_token=([^&]+)")[1])) { - - $("#login").hide(); - - var checkins_url = "https://api.foursquare.com/v2/users/self/checkins" - + "?v=20150201&limit=10&oauth_token="+token; - - $.getJSON(checkins_url, function(data){ - var checkins = data.response.checkins.items; - var html = ''; - $(checkins).each(function(i,c){ - html += '<a href="https://foursquare.com/_/checkin/' + c.id + '">' - + c.venue.name + '</a><br>'; - }); - $("#checkins").html(html); - $("#signed-in").show(); - }); - - } - }); - </script> - -</body> -</html> diff --git a/google.php b/google.php deleted file mode 100644 index 387832a1e30287b0bcf92ab6766658e7c102ee71..0000000000000000000000000000000000000000 --- a/google.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php -// Fill these out with the values you got from Google -$googleClientID = ''; -$googleClientSecret = ''; - -// This is the URL we'll send the user to first to get their authorization -$authorizeURL = 'https://accounts.google.com/o/oauth2/v2/auth'; - -// This is Google's OpenID Connect token endpoint -$tokenURL = 'https://www.googleapis.com/oauth2/v4/token'; - -// The URL for this script, used as the redirect URL -$baseURL = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']; - -// Start a session so we have a place to store things between redirects -session_start(); - - - -// Start the login process by sending the user -// to Google's authorization page -if(isset($_GET['action']) && $_GET['action'] == 'login') { - unset($_SESSION['user_id']); - - // Generate a random hash and store in the session - $_SESSION['state'] = bin2hex(random_bytes(16)); - - $params = array( - 'response_type' => 'code', - 'client_id' => $googleClientID, - 'redirect_uri' => $baseURL, - 'scope' => 'openid email', - 'state' => $_SESSION['state'] - ); - - // Redirect the user to Google's authorization page - header('Location: ' . $authorizeURL . '?' . http_build_query($params)); - die(); -} - -if(isset($_GET['action']) && $_GET['action'] == 'logout') { - unset($_SESSION['user_id']); - header('Location: '.$baseURL); - die(); -} - -// When Google redirects the user back here, there will be a "code" and "state" -// parameter in the query string -if(isset($_GET['code'])) { - // Verify the state matches our stored state - if(!isset($_GET['state']) || $_SESSION['state'] != $_GET['state']) { - header('Location: ' . $baseURL . '?error=invalid_state'); - die(); - } - - // Exchange the auth code for a token - $ch = curl_init($tokenURL); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ - 'grant_type' => 'authorization_code', - 'client_id' => $googleClientID, - 'client_secret' => $googleClientSecret, - 'redirect_uri' => $baseURL, - 'code' => $_GET['code'] - ])); - $response = curl_exec($ch); - $data = json_decode($response, true); - - // Note: You'd probably want to use a real JWT library - // but this will do in a pinch. This is only safe to do - // because the ID token came from the https connection - // from Google rather than an untrusted browser redirect - - // Split the JWT string into three parts - $jwt = explode('.', $data['id_token']); - - // Extract the middle part, base64 decode it, then json_decode it - $userinfo = json_decode(base64_decode($jwt[1]), true); - - $_SESSION['user_id'] = $userinfo['sub']; - $_SESSION['email'] = $userinfo['email']; - - // While we're at it, let's store the access token and id token - // so we can use them later - $_SESSION['access_token'] = $data['access_token']; - $_SESSION['id_token'] = $data['id_token']; - $_SESSION['userinfo'] = $userinfo; - - header('Location: ' . $baseURL); - die(); -} - - - -// If there is a user ID in the session -// the user is already logged in -if(!isset($_GET['action'])) { - if(!empty($_SESSION['user_id'])) { - echo '<h3>Logged In</h3>'; - echo '<p>User ID: '.$_SESSION['user_id'].'</p>'; - echo '<p>Email: '.$_SESSION['email'].'</p>'; - echo '<p><a href="?action=logout">Log Out</a></p>'; - - echo '<h3>ID Token</h3>'; - echo '<pre>'; - print_r($_SESSION['userinfo']); - echo '</pre>'; - - echo '<h3>User Info</h3>'; - echo '<pre>'; - $ch = curl_init('https://www.googleapis.com/oauth2/v3/userinfo'); - curl_setopt($ch, CURLOPT_HTTPHEADER, [ - 'Authorization: Bearer '.$_SESSION['access_token'] - ]); - curl_exec($ch); - echo '</pre>'; - - } else { - echo '<h3>Not logged in</h3>'; - echo '<p><a href="?action=login">Log In</a></p>'; - } - die(); -} - diff --git a/github.php b/oauth2.php similarity index 82% rename from github.php rename to oauth2.php index 52a1270e2f47d4fdd5e018b5e3c36a95384eb6dd..3f17674644a887a72b12361b23405791701c8c36 100644 --- a/github.php +++ b/oauth2.php @@ -1,5 +1,4 @@ <?php - // Remplir ces champs avec les valeurs obtenues sur AriseID Connect $clientId = 'f97b146f-121a-4400-a79c-7c2ecbbd87f8'; $clientSecret = 'y6hsryRm6P~QSen~Xs0UtvkEcK'; @@ -14,7 +13,7 @@ $tokenURL = "{$oauthURLBase}/oauth2/token"; $apiURLBase = 'http://api.127.0.0.1.nip.io:5000'; // L'URL de ce script, utilisé comme URL de redirection -$baseURL = 'http://php.127.0.0.1.nip.io:8000'; +$baseURL = 'http://php.127.0.0.1.nip.io:8000/'; // On lance une session afin d'avoir un endroit où stocker les données entre les redirections session_start(); @@ -57,30 +56,26 @@ if (isset($_GET['code'])) { } // Échange le code d'authentification contre un jeton d'accès - $query_data = array( + $ch = curl_init($tokenURL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'grant_type' => 'authorization_code', 'client_id' => $clientId, 'client_secret' => $clientSecret, 'redirect_uri' => $baseURL, 'code' => $_GET['code'] - ); - - $ch = curl_init($tokenURL); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query_data)); + ])); $response = curl_exec($ch); + $tokens = json_decode($response, true); - $token = json_decode($response, true); - - $_SESSION['access_token'] = $token['access_token']; + $_SESSION['access_token'] = $tokens['access_token']; header("Location: $baseURL"); die(); } -function graphql_request($query) +function graphql_request($apiURLBase, $query) { - global $apiURLBase; $endpoint = "$apiURLBase/graphql/v0"; $headers = []; @@ -106,6 +101,8 @@ function graphql_request($query) $profile_query = '{"query":"{ profile { id name civilName givenName middleName forenames familyName nickname preferredUsername preferredNickname gender birthdate profile picture { url } website zoneinfo locale updatedAt promotion year groups { role group { name } } } }"}'; +$jsonFlags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES; + ?> <html lang="fr"> @@ -124,20 +121,13 @@ $profile_query = '{"query":"{ profile { id name civilName givenName middleName f <a href="?action=login"><button>Se connecter</button></a> <?php else: ?> <!-- S'il y a un jeton d'accès dans la session l'utilisateur est connecté --> - <?php if (isset($_GET['action']) && $_GET['action'] == 'profile'): ?> - <p><a href=".">Retour</a></p> - <pre> - <code> -<?php echo json_encode(graphql_request($profile_query), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?> - </code> - </pre> - <?php endif; ?> - - <?php if (!isset($_GET['action'])): ?> - <h3>Connecté</h3> - <p><a href="?action=profile">Voir le profil</a></p> - <a href="?action=logout"><button>Se déconnecter</button></a> - <?php endif; ?> + <h3>Connecté</h3> + <a href="?action=logout"><button>Se déconnecter</button></a> + + <h3>Profil (via API)</h3> + <pre><code> +<?php echo json_encode(graphql_request($apiURLBase, $profile_query), $jsonFlags); ?> + </code></pre> <?php endif; ?> </main> </body> \ No newline at end of file diff --git a/oidc.php b/oidc.php new file mode 100644 index 0000000000000000000000000000000000000000..980cefa105f627923fcac1e485c15bfab670383c --- /dev/null +++ b/oidc.php @@ -0,0 +1,149 @@ +<?php +// Remplir ces champs avec les valeurs obtenues sur AriseID Connect +$clientId = 'f97b146f-121a-4400-a79c-7c2ecbbd87f8'; +$clientSecret = 'y6hsryRm6P~QSen~Xs0UtvkEcK'; + +$oauthURLBase = 'http://oidc.127.0.0.1.nip.io:4444'; +// L'URL à laquelle on enverra d'abord l'utilisateur pour obtenir son autorisation +$authorizeURL = "{$oauthURLBase}/oauth2/auth"; +// Le point d'accès à partir duquel notre serveur demandera un jeton d'accès +$tokenURL = "{$oauthURLBase}/oauth2/token"; +// Le point d'accès à partir duquel notre serveur demandera un jeton d'identité +$userinfoURL = "{$oauthURLBase}/userinfo"; + +// L'URL racine à utiliser pour effectuer des demandes d'API authentifiées +$apiURLBase = 'http://api.127.0.0.1.nip.io:5000'; + +// L'URL de ce script, utilisé comme URL de redirection +$baseURL = 'http://php.127.0.0.1.nip.io:8000/'; + +// On lance une session afin d'avoir un endroit où stocker les données entre les redirections +session_start(); + +// Commence le processus de connexion en envoyant l'utilisateur +// à la page d'autorisation d'AriseID Connect +if (isset($_GET['action']) && $_GET['action'] == 'login') { + unset($_SESSION['access_token']); + + // Génère un hash aléatoire et le stocke dans la session + $_SESSION['state'] = bin2hex(random_bytes(16)); + + $params = [ + 'response_type' => 'code', + 'client_id' => $clientId, + 'redirect_uri' => $baseURL, + 'scope' => 'openid profile email', + 'state' => $_SESSION['state'] + ]; + + // Redirige l'utilisateur vers la page d'autorisation d'AriseID Connect + header('Location: ' . $authorizeURL . '?' . http_build_query($params)); + die(); +} + +if (isset($_GET['action']) && $_GET['action'] == 'logout') { + unset($_SESSION['user_id']); + header("Location: $baseURL"); + die(); +} + +// Quand AriseID Connect redirige l'utilisateur ici, il y aura +// un paramètre "code" et "state" dans la chaîne de requête +if (isset($_GET['code'])) { + // Certifie que l'état correspond à l'état stocké + if (!isset($_GET['state']) || $_SESSION['state'] != $_GET['state']) { + + header("Location: $baseURL?error=invalid_state"); + die(); + } + + // Échange le code d'authentification contre un jeton d'accès + $ch = curl_init($tokenURL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ + 'grant_type' => 'authorization_code', + 'client_id' => $clientId, + 'client_secret' => $clientSecret, + 'redirect_uri' => $baseURL, + 'code' => $_GET['code'] + ])); + $response = curl_exec($ch); + $tokens = json_decode($response, true); + + // Note: You'd probably want to use a real JWT library + // but this will do in a pinch. This is only safe to do + // because the ID token came from the https connection + // from Google rather than an untrusted browser redirect + + // Split the JWT string into three parts + $jwt = explode('.', $tokens['id_token']); + + // Extract the middle part, base64 decode it, then json_decode it + $userinfo = json_decode(base64_decode($jwt[1]), true); + + $_SESSION['user_id'] = $userinfo['sub']; + $_SESSION['email'] = $userinfo['email']; + + // While we're at it, let's store the access token and id token + // so we can use them later + $_SESSION['access_token'] = $tokens['access_token']; + $_SESSION['id_token'] = $tokens['id_token']; + $_SESSION['userinfo'] = $userinfo; + + header('Location: ' . $baseURL); + die(); +} + +function userinfo_request($userinfoURL) +{ + $ch = curl_init($userinfoURL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'Authorization: Bearer ' . $_SESSION['access_token'] + ]); + $response = curl_exec($ch); + + if (curl_errno($ch)) { + echo 'Error:' . curl_error($ch); + } + + return json_decode($response, true); +} + +$jsonFlags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES; + +?> +<html lang="fr"> + +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <meta name="color-scheme" content="light dark"> + <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.classless.min.css"> + <title>OpenID Connect Demo</title> +</head> + +<body> + <main> + <?php if (empty($_SESSION['user_id'])): ?> + <h3>Non connecté</h3> + <a href="?action=login"><button>Se connecter</button></a> + <?php else: ?> + <!-- S'il y a un ID utilisateur dans la session l'utilisateur est connecté --> + <h3>Connecté</h3> + <p>User ID: <code><?php echo $_SESSION['user_id']; ?></code></p> + <p>Email: <code><?php echo $_SESSION['email']; ?></code></p> + <a href="?action=logout"><button>Se déconnecter</button></a> + + <h3>ID Token</h3> + <pre><code> +<?php echo json_encode($_SESSION['userinfo'], $jsonFlags); ?> + </code></pre> + + <h3>User Info</h3> + <pre><code> +<?php echo json_encode(userinfo_request($userinfoURL), $jsonFlags); ?> + </code></pre> + <?php endif; ?> + </main> +</body> \ No newline at end of file