การเชื่อม OPENID ของ PSU ด้วย PHP
1. เขียนแบบฟอร์มขอใช้บริการ OPENID ที่ https://ccform.psu.ac.th/th/forms/auth-system-openid
2. หลังจากอนุมัติแล้วจะได้ Client ID และ Client Secret มา
3. สร้าง file สำหรับ redirect ไปยัง openid โดยมีรายละเอียดดังนี้
<?php
session_start();
$state = random_bytes(128 / 8);
$state = bin2hex($state);
$state = $payload;
$_SESSION['state_code'] = $state;
$queryStrings = array(
"response_type" => "code",
"client_id" => CLIENT ID ตามข้อ 2
"scope" => "openid psu_profile profile email",
"redirect_uri" => OpenID URL Redirect ตามข้อ 1 ,
"state" => $state,
"nonce" => "",
);
$qs = http_build_query($queryStrings);
$authorization_endpoint = "https://psusso.psu.ac.th:8443/application/o/authorize/";
$url = "$authorization_endpoint?$qs";
header("location: $url");
?>
4. สร้าง file OpenID URL Redirect ตามข้อ 1
<?php
session_start();
$code = $_GET['code'];
$state = $_GET['state'];
if ($state != $_SESSION['state_code']) {
echo '401: Invalid state parameter';
}
$headers = array(
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
);
$token_endpoint="https://psusso.psu.ac.th/application/o/token/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_endpoint);
curl_setopt($ch, CURLOPT_POST, true);
$curl_post_data = array(
"grant_type" => "authorization_code",
"code" => $code,
"client_id" => CLIENT ID ตามข้อ 2
"client_secret" => CLIENT SECRET ตามข้อ 2 ,
"redirect_uri" => OpenID URL Redirect ตามข้อ 1 ,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS,$curl_post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT,20);
$json = json_decode(curl_exec($ch));
$_SESSION['token'] = $json;
/////////////////////ดึงข้อมูลของ user
$token=$_SESSION['token'];
$token_endpoint="https://psusso.psu.ac.th/application/o/userinfo/";
$headers = array("Authorization: Bearer $token->access_token");
$end_point="https://psusso.psu.ac.th/application/o/userinfo/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $end_point);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
//// ข้อมูล user ทั้งหมดจะอยู่ในตัว $json สามารถ ใช้ print_r($json) เพื่อดูได้
$json = json_decode(curl_exec($ch));
$_SESSION["LOGIN"] = 1;
$_SESSION["psu_id"] = $json->psu_id;
$_SESSION["username"] = $json->username;
$_SESSION["display_name_th"] = $json->display_name_th;
$_SESSION["email"] = $json->email;
$url="https://xxxx";
header("location: $url");
?>
- Log in to post comments
- 12 views
Comments
ยอดเยี่ยม
จะลองนำไปใช้งานครับ