การเชื่อม OAUTH2 ของ PSU ด้วย NEXT.JS (PAGE ROUTE)
file : pages/challback.js const inter = Inter({ subsets: [“latin”] }); export default function Home({show2}) { return ( <> <div className=”container”> <h1>Check OAuth</h1> <p>Code: {JSON.stringify(show2)}</p> </div> </> );} export async function getServerSideProps(context) {// เมื่อทำการ SignOn ระบบจะทำการเรียก callback url โดยส่ง parameter code มา const { query } = context; const code = query.code; //เตรียมข้อมูลเพื่อรับ access token const pData1 = { grant_type: ‘authorization_code’, client_id: ‘XXXXXXXX’, // ได้มาจากสำนักนวัตถกรรม client_secret: ‘XXXXXXXX’, // ได้มาจากสำนักนวัตถกรรม code: code, response_type: ‘code’, redirect_uri: ‘CALL BACK URL’ }; //ส่งคำร้องเพื่อขอ access token//เมื่อส่งคำร้องขอ access token แล้ว code ที่ได้มาจะหมดอายุทันที const resP1 = await fetch(‘https://oauth.psu.ac.th/?oauth=token’, { method: ‘POST’, body: JSON.stringify(pData1), headers: { ‘content-type’: ‘application/json’ }, }); const show1 = await resP1.json(); //เมื่อได้ access token//ส่งคำร้องเพื่อขอ user profile โดยต้องส่ง access token ไปด้วย//ซึ่ง access token จะมีอายุ 1 ชั่วโมง const resP2 = await fetch(‘https://oauth.psu.ac.th?oauth=me’,{ method: ‘GET’, headers: { ‘content-type’: ‘application/json’, ‘Authorization’: ‘Bearer ‘+show1.access_token }, }); const show2 = await resP2.json(); return { props: {show2} }}