การเชื่อม OAUTH2 ของ PSU ด้วย NEXT.JS (APP ROUTE)
file app/api/callback/route.ts async function GET(request: Request) {// เมื่อทำการ SignOn ระบบจะทำการเรียก callback url โดยส่ง parameter code มา const { searchParams } = new URL(request.url); const code = searchParams.get(‘code’); const state = searchParams.get(‘state’); //เตรียมข้อมูลเพื่อรับ 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() if(show2.user_login){ return Response.redirect(‘https://xxxxxx/sussec) }else{ return Response.redirect(‘https://xxxxxx/error’)} } export {GET}