APIهای OAuth 2.0 Google را می توان هم برای احراز هویت و هم برای مجوز استفاده کرد. این سند پیادهسازی OAuth 2.0 ما را برای احراز هویت توصیف میکند که با مشخصات OpenID Connect مطابقت دارد و دارای گواهی OpenID است. اسناد موجود در استفاده از OAuth 2.0 برای دسترسی به APIهای Google در این سرویس نیز اعمال می شود. اگر میخواهید این پروتکل را به صورت تعاملی کاوش کنید، Google OAuth 2.0 Playground را توصیه میکنیم. برای دریافت راهنمایی در مورد Stack Overflow ، سؤالات خود را با «google-oauth» تگ کنید.
راه اندازی OAuth 2.0
قبل از اینکه برنامه شما بتواند از سیستم احراز هویت Google OAuth 2.0 برای ورود به سیستم کاربر استفاده کند، باید پروژه ای را در Google API Console راه اندازی کنید تا اعتبار OAuth 2.0 را دریافت کنید، یک URI تغییر مسیر تنظیم کنید، و (به صورت اختیاری) اطلاعات نام تجاری را که کاربران شما در آن می بینند سفارشی کنید. صفحه رضایت کاربر همچنین می توانید از API Console برای ایجاد یک حساب سرویس، فعال کردن صورتحساب، تنظیم فیلتر و انجام کارهای دیگر استفاده کنید. برای جزئیات بیشتر، به راهنمایGoogle API Console مراجعه کنید.
اعتبارنامه OAuth 2.0 را دریافت کنید
برای احراز هویت کاربران و دسترسی به APIهای Google، به اعتبارنامه OAuth 2.0، از جمله شناسه مشتری و راز سرویس گیرنده نیاز دارید.
برای مشاهده شناسه مشتری و راز مشتری برای اعتبار OAuth 2.0 داده شده ، روی متن زیر کلیک کنید: اعتبار را انتخاب کنید . در پنجره ای که باز می شود ، پروژه خود و اعتبار مورد نظر خود را انتخاب کرده و سپس بر روی View کلیک کنید.
یا ، شناسه مشتری و راز مشتری خود را از صفحه اعتبارنامه در API Console :
- Go to the Credentials page.
- بر روی نام اعتبار خود یا نماد مداد ( create ) کلیک create . شناسه مشتری و راز شما در بالای صفحه قرار دارند.
یک URI تغییر مسیر را تنظیم کنید
URI تغییر مسیری که در API Console تنظیم میکنید، تعیین میکند که Google پاسخها را به درخواستهای احراز هویت شما کجا ارسال میکند.
برای ایجاد ، مشاهده و یا ویرایش URI های تغییر مسیر برای اعتبار OAuth 2.0 داده شده ، موارد زیر را انجام دهید:
- Go to the Credentials page.
- در بخش شناسه های مشتری OAuth 2.0 از صفحه ، روی اعتبار نامه کلیک کنید.
- URI های تغییر مسیر را مشاهده یا ویرایش کنید.
اگر در صفحه شناسنامه ها هیچ بخش شناسه مشتری OAuth 2.0 وجود ندارد ، پروژه شما هیچ اعتبار OAuth ندارد. برای ایجاد یک ، روی ایجاد اعتبارنامه کلیک کنید.
صفحه رضایت کاربر را سفارشی کنید
برای کاربران شما، تجربه احراز هویت OAuth 2.0 شامل یک صفحه رضایت است که اطلاعاتی را که کاربر منتشر می کند و شرایط اعمال شده را توضیح می دهد. برای مثال، زمانی که کاربر وارد سیستم میشود، ممکن است از او خواسته شود به برنامه شما اجازه دسترسی به آدرس ایمیل و اطلاعات اولیه حساب خود را بدهد. شما درخواست دسترسی به این اطلاعات را با استفاده از پارامتر scope
، که برنامه شما در درخواست احراز هویت خود دارد، دریافت میکنید. همچنین میتوانید از scope برای درخواست دسترسی به سایر APIهای Google استفاده کنید.
صفحه رضایت کاربر همچنین اطلاعات برند مانند نام محصول، لوگو و URL صفحه اصلی را نشان می دهد. شما اطلاعات نام تجاری را در API Consoleکنترل می کنید.
برای فعال کردن صفحه رضایت پروژه خود:
- Consent Screen page در Google API Console .
- If prompted, select a project, or create a new one.
- فرم را پر کنید و روی ذخیره کلیک کنید.
گفتگوی رضایت زیر نشان میدهد که وقتی ترکیبی از دامنههای OAuth 2.0 و Google Drive در درخواست وجود دارد، کاربر چه چیزی را میبیند. (این گفتگوی عمومی با استفاده از Google OAuth 2.0 Playground ایجاد شده است، بنابراین شامل اطلاعات نام تجاری نمی شود که در API Consoleتنظیم شود.)

دسترسی به سرویس
Google و اشخاص ثالث کتابخانههایی را ارائه میکنند که میتوانید از آنها برای مراقبت از بسیاری از جزئیات پیادهسازی احراز هویت کاربران و دسترسی به APIهای Google استفاده کنید. به عنوان مثال میتوان به سرویسهای هویت Google و کتابخانههای مشتری Google اشاره کرد که برای پلتفرمهای مختلف در دسترس هستند.
اگر تصمیم گرفتید از کتابخانه استفاده نکنید، دستورالعملهای باقیمانده این سند را دنبال کنید، که جریانهای درخواست HTTP را که زیربنای کتابخانههای موجود است، توضیح میدهد.
احراز هویت کاربر
احراز هویت کاربر مستلزم دریافت رمز شناسه و اعتبارسنجی آن است. نشانههای ID یک ویژگی استاندارد OpenID Connect هستند که برای استفاده در اشتراکگذاری ادعاهای هویت در اینترنت طراحی شدهاند.
متداولترین روشهای مورد استفاده برای احراز هویت یک کاربر و بهدست آوردن یک شناسه رمز، جریان «سرور» و جریان «ضمنی» نامیده میشوند. جریان سرور به سرور پشتیبان یک برنامه اجازه می دهد تا هویت شخص را با استفاده از مرورگر یا دستگاه تلفن همراه تأیید کند. جریان ضمنی زمانی استفاده میشود که یک برنامه سمت سرویس گیرنده (معمولاً یک برنامه جاوا اسکریپت که در مرورگر اجرا میشود) نیاز به دسترسی مستقیم به APIها به جای سرور بکاند خود داشته باشد.
این سند نحوه اجرای جریان سرور برای احراز هویت کاربر را شرح می دهد. جریان ضمنی به دلیل خطرات امنیتی در مدیریت و استفاده از توکن ها در سمت مشتری، به طور قابل توجهی پیچیده تر است. اگر نیاز به پیادهسازی یک جریان ضمنی دارید، به شدت توصیه میکنیم از سرویسهای هویت Google استفاده کنید.
جریان سرور
مطمئن شوید که برنامه خود را در API Consoleراه اندازی کرده اید تا بتواند از این پروتکل ها استفاده کند و کاربران شما را احراز هویت کند. وقتی کاربری سعی می کند با گوگل وارد شود، باید:
- یک نشانه حالت ضد جعل ایجاد کنید
- یک درخواست احراز هویت به Google ارسال کنید
- رمز حالت ضد جعل را تأیید کنید
- تبادل
code
برای توکن دسترسی و شناسه - اطلاعات کاربر را از توکن ID دریافت کنید
- احراز هویت کاربر
1. یک توکن حالت ضد جعل ایجاد کنید
شما باید با جلوگیری از حملات جعل درخواست از امنیت کاربران خود محافظت کنید. اولین مرحله ایجاد یک نشانه جلسه منحصر به فرد است که بین برنامه شما و مشتری کاربر حالت نگه می دارد. بعداً این نشانه جلسه منحصر به فرد را با پاسخ احراز هویتی که توسط سرویس ورود به سیستم Google OAuth برگردانده شده است مطابقت می دهید تا تأیید کنید که کاربر درخواست را ارائه می دهد و نه یک مهاجم مخرب. این توکنها اغلب به عنوان توکنهای جعل درخواست متقابل ( CSRF ) شناخته میشوند.
یک انتخاب خوب برای یک نشانه وضعیت، رشته ای از 30 کاراکتر یا بیشتر است که با استفاده از یک تولید کننده اعداد تصادفی با کیفیت بالا ساخته شده است. دیگری هش است که با امضای برخی از متغیرهای وضعیت جلسه شما با کلیدی که در بکاند مخفی نگه داشته میشود، ایجاد میشود.
کد زیر تولید نشانه های جلسه منحصر به فرد را نشان می دهد.
PHP
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای PHP دانلود کنید.
// Create a state token to prevent request forgery. // Store it in the session for later validation. $state = bin2hex(random_bytes(128/8)); $app['session']->set('state', $state); // Set the client ID, token state, and application name in the HTML while // serving it. return $app['twig']->render('index.html', array( 'CLIENT_ID' => CLIENT_ID, 'STATE' => $state, 'APPLICATION_NAME' => APPLICATION_NAME ));
جاوا
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای جاوا دانلود کنید.
// Create a state token to prevent request forgery. // Store it in the session for later validation. String state = new BigInteger(130, new SecureRandom()).toString(32); request.session().attribute("state", state); // Read index.html into memory, and set the client ID, // token state, and application name in the HTML before serving it. return new Scanner(new File("index.html"), "UTF-8") .useDelimiter("\\A").next() .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID) .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state) .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME);
پایتون
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای پایتون دانلود کنید.
# Create a state token to prevent request forgery. # Store it in the session for later validation. state = hashlib.sha256(os.urandom(1024)).hexdigest() session['state'] = state # Set the client ID, token state, and application name in the HTML while # serving it. response = make_response( render_template('index.html', CLIENT_ID=CLIENT_ID, STATE=state, APPLICATION_NAME=APPLICATION_NAME))
2. یک درخواست احراز هویت به Google ارسال کنید
مرحله بعدی تشکیل یک درخواست HTTPS GET
با پارامترهای URI مناسب است. به استفاده از HTTPS به جای HTTP در تمام مراحل این فرآیند توجه داشته باشید. اتصالات HTTP رد می شود. شما باید URI پایه را از سند Discovery با استفاده از مقدار فراداده authorization_endpoint
بازیابی کنید. در بحث زیر فرض میشود که URI پایه https://accounts.google.com/o/oauth2/v2/auth
است.
برای درخواست اولیه، پارامترهای زیر را مشخص کنید:
-
client_id
، که از API ConsoleCredentials pageبه دست می آورید. -
response_type
که در یک درخواست جریان کد مجوز اولیه بایدcode
باشد. (بیشتر درresponse_type
بخوانید.) -
scope
که در یک درخواست اولیه بایدopenid email
باشد. (درscope
بیشتر بخوانید.) -
redirect_uri
باید نقطه پایانی HTTP در سرور شما باشد که پاسخ را از Google دریافت می کند. مقدار باید دقیقاً با یکی از URI های مجاز تغییر مسیر برای مشتری OAuth 2.0 مطابقت داشته باشد که در API ConsoleCredentials pageپیکربندی کرده اید. اگر این مقدار با یک URI مجاز مطابقت نداشته باشد، درخواست با خطایredirect_uri_mismatch
ناموفق خواهد بود. -
state
باید شامل مقدار نشانه جلسه منحصربفرد ضد جعل، و همچنین هر اطلاعات دیگری که برای بازیابی زمینه زمانی که کاربر به برنامه شما بازمی گردد، باشد، به عنوان مثال، URL شروع. (ادامه مطلب را درstate
بخوانید.) -
nonce
یک مقدار تصادفی است که توسط برنامه شما ایجاد می شود و در صورت وجود، محافظت از پخش مجدد را فعال می کند. -
login_hint
می تواند آدرس ایمیل کاربر یا رشتهsub
باشد که معادل شناسه گوگل کاربر است. اگر یکlogin_hint
ارائه نکنید و کاربر در حال حاضر وارد سیستم شده است، صفحه رضایت شامل درخواستی برای تایید برای انتشار آدرس ایمیل کاربر در برنامه شما است. (درlogin_hint
بیشتر بخوانید.) - از پارامتر
hd
برای بهینه سازی جریان OpenID Connect برای کاربران یک دامنه خاص مرتبط با یک سازمان Google Cloud استفاده کنید. (ادامه مطلب را درhd
بخوانید.)
در اینجا یک نمونه از یک URI احراز هویت OpenID Connect کامل، با خطوط شکسته و فاصله برای خوانایی آورده شده است:
https://accounts.google.com/o/oauth2/v2/auth? response_type=code& client_id=424911365001.apps.googleusercontent.com& scope=openid%20email& redirect_uri=https%3A//oauth2.example.com/code& state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2-login-demo.example.com%2FmyHome& login_hint=jsmith@example.com& nonce=0394852-3190485-2490358& hd=example.com
اگر برنامه شما اطلاعات جدیدی در مورد آنها درخواست می کند یا اگر برنامه شما درخواست دسترسی به حسابی که قبلاً تأیید نکرده اند، از کاربران خواسته می شود رضایت خود را اعلام کنند.
3. رمز حالت ضد جعل را تأیید کنید
پاسخ به redirect_uri
که در درخواست مشخص کرده اید ارسال می شود. تمام پاسخ ها در رشته query برگردانده می شوند، همانطور که در زیر نشان داده شده است:
https://oauth2.example.com/code?state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foa2cb.example.com%2FmyHome&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&scope=openid%20email%20https://www.googleapis.com/auth/userinfo.email
در سرور، باید تأیید کنید که state
دریافتی از Google با نشانه جلسه ای که در مرحله 1 ایجاد کرده اید مطابقت دارد. این تأیید رفت و برگشت کمک می کند تا اطمینان حاصل شود که کاربر، نه یک اسکریپت مخرب، درخواست را ارسال می کند.
کد زیر نشان دهنده تایید توکن های جلسه ای است که در مرحله 1 ایجاد کرده اید:
PHP
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای PHP دانلود کنید.
// Ensure that there is no request forgery going on, and that the user // sending us this connect request is the user that was supposed to. if ($request->get('state') != ($app['session']->get('state'))) { return new Response('Invalid state parameter', 401); }
جاوا
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای جاوا دانلود کنید.
// Ensure that there is no request forgery going on, and that the user // sending us this connect request is the user that was supposed to. if (!request.queryParams("state").equals( request.session().attribute("state"))) { response.status(401); return GSON.toJson("Invalid state parameter."); }
پایتون
برای استفاده از این نمونه باید کتابخانه سرویس گیرنده Google APIs را برای پایتون دانلود کنید.
# Ensure that the request is not a forgery and that the user sending # this connect request is the expected user. if request.args.get('state', '') != session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response
4. تبادل code
برای توکن دسترسی و شناسه
پاسخ شامل یک پارامتر code
، یک کد مجوز یک بار مصرف است که سرور شما می تواند با یک نشانه دسترسی و شناسه مبادله کند. سرور شما این تبادل را با ارسال یک درخواست HTTPS POST
انجام می دهد. درخواست POST
به نقطه پایانی نشانه ارسال می شود که باید آن را از سند Discovery با استفاده از مقدار فراداده token_endpoint
بازیابی کنید. بحث زیر فرض میکند که نقطه پایانی https://oauth2.googleapis.com/token
است. درخواست باید شامل پارامترهای زیر در بدنه POST
باشد:
زمینه های | |
---|---|
code | کد مجوزی که از درخواست اولیه بازگردانده می شود. |
client_id | شناسه سرویس گیرنده ای که از API ConsoleCredentials pageدریافت می کنید، همانطور که در دریافت اعتبارنامه OAuth 2.0 توضیح داده شده است. |
client_secret | راز مشتری که از API ConsoleCredentials pageبه دست می آورید، همانطور که در دریافت اعتبارنامه OAuth 2.0 توضیح داده شده است. |
redirect_uri | یک URI تغییر مسیر مجاز برای client_id مشخص شده در API ConsoleCredentials page، همانطور که در Set a Redirect URI توضیح داده شده است. |
grant_type | این فیلد باید حاوی مقدار authorization_code باشد که در مشخصات OAuth 2.0 تعریف شده است . |
درخواست واقعی ممکن است مانند مثال زیر باشد:
POST /token HTTP/1.1 Host: oauth2.googleapis.com Content-Type: application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=your-client-id& client_secret=your-client-secret& redirect_uri=https%3A//oauth2.example.com/code& grant_type=authorization_code
پاسخ موفقیت آمیز به این درخواست شامل فیلدهای زیر در آرایه JSON است:
زمینه های | |
---|---|
access_token | نشانه ای که می تواند به یک API Google ارسال شود. |
expires_in | طول عمر باقیمانده رمز دسترسی در ثانیه. |
id_token | JWT که حاوی اطلاعات هویتی کاربر است که به صورت دیجیتالی توسط Google امضا شده است. |
scope | دامنه دسترسی اعطا شده توسط access_token به صورت لیستی از رشته های حساس به حروف کوچک و کوچک با فاصله بیان می شود. |
token_type | نوع توکن برگشتی را مشخص می کند. در این زمان، این فیلد همیشه دارای مقدار Bearer است. |
refresh_token | (اختیاری) این فیلد فقط در صورتی وجود دارد که پارامتر |
5. اطلاعات کاربر را از توکن ID بدست آورید
رمز شناسه یک JWT (JSON Web Token) است، یعنی یک شیء JSON کدگذاری شده با Base64 رمزگذاری شده است. به طور معمول، مهم است که قبل از استفاده از یک کد شناسه اعتبارسنجی کنید ، اما از آنجایی که شما مستقیماً از طریق یک کانال HTTPS بدون واسطه با Google ارتباط برقرار میکنید و از رمز مشتری خود برای تأیید اعتبار خود در Google استفاده میکنید، میتوانید مطمئن باشید که توکن شما دریافت واقعاً از Google می آید و معتبر است. اگر سرور شما کد ID را به سایر اجزای برنامه شما ارسال می کند، بسیار مهم است که سایر مؤلفه ها قبل از استفاده از توکن آن را تأیید کنند .
از آنجایی که اکثر کتابخانههای API اعتبار سنجی را با کار رمزگشایی مقادیر کدگذاری شده با base64url و تجزیه JSON در داخل ترکیب میکنند، احتمالاً با دسترسی به ادعاهای موجود در شناسه شناسه، به اعتبار توکن پایان میدهید.
محموله یک رمز شناسه
یک نشانه ID یک شی JSON است که شامل مجموعه ای از جفت نام/مقدار است. در اینجا یک مثال برای خوانایی فرمت شده است:
{ "iss": "https://accounts.google.com", "azp": "1234987819200.apps.googleusercontent.com", "aud": "1234987819200.apps.googleusercontent.com", "sub": "10769150350006150715113082367", "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q", "hd": "example.com", "email": "jsmith@example.com", "email_verified": "true", "iat": 1353601026, "exp": 1353604926, "nonce": "0394852-3190485-2490358" }
توکنهای Google ID ممکن است حاوی فیلدهای زیر باشند (که به عنوان ادعا شناخته میشوند):
مطالبه | ارائه شده است | شرح |
---|---|---|
aud | همیشه | مخاطبی که این کد شناسه برای آنها در نظر گرفته شده است. این باید یکی از شناسه های مشتری OAuth 2.0 برنامه شما باشد. |
exp | همیشه | زمان انقضا در تاریخ یا پس از آن رمز ID نباید پذیرفته شود. نشان داده شده در زمان یونیکس (ثانیه عدد صحیح). |
iat | همیشه | زمان صدور شناسنامه نشان داده شده در زمان یونیکس (ثانیه عدد صحیح). |
iss | همیشه | شناسه صادرکننده برای صادرکننده پاسخ. همیشه https://accounts.google.com یا accounts.google.com برای کدهای Google ID. |
sub | همیشه | یک شناسه برای کاربر، منحصر به فرد در بین تمام حساب های Google و هرگز استفاده مجدد نشده است. یک حساب Google می تواند چندین آدرس ایمیل در مقاطع زمانی مختلف داشته باشد، اما مقدار sub آن هرگز تغییر نمی کند. از sub در برنامه خود به عنوان کلید شناسه یکتا برای کاربر استفاده کنید. حداکثر طول 255 نویسه ASCII حساس به حروف کوچک و بزرگ. |
at_hash | دسترسی به هش رمز. اعتبار سنجی را ارائه می دهد که نشانه دسترسی به نشانه هویت گره خورده است. اگر توکن ID با یک مقدار access_token در جریان سرور صادر شود، این ادعا همیشه شامل می شود. این ادعا می تواند به عنوان یک مکانیسم جایگزین برای محافظت در برابر حملات جعل درخواست های متقابل استفاده شود، اما اگر مراحل 1 و گام 3 را دنبال کنید، لازم نیست رمز دسترسی را تأیید کنید. | |
azp | client_id ارائه دهنده مجاز. این ادعا تنها زمانی مورد نیاز است که طرف درخواست کننده شناسه توکن با مخاطبان شناسه یکسان نباشد. ممکن است این مورد در Google برای برنامههای ترکیبی باشد که در آن یک برنامه وب و برنامه Android دارای یک OAuth 2.0 client_id متفاوت هستند اما پروژه Google APIs یکسانی دارند. | |
email | آدرس ایمیل کاربر. این مقدار ممکن است مختص این کاربر نباشد و برای استفاده به عنوان کلید اصلی مناسب نباشد. فقط در صورتی ارائه می شود که محدوده شما شامل مقدار دامنه email باشد. | |
email_verified | درست است اگر آدرس ایمیل کاربر تأیید شده باشد. در غیر این صورت نادرست | |
family_name | نام یا نام خانوادگی یا نام خانوادگی کاربر. ممکن است در صورت وجود ادعای name ارائه شود. | |
given_name | نام (های) یا نام (های) کوچک کاربر. ممکن است در صورت وجود ادعای name ارائه شود. | |
hd | دامنه مرتبط با سازمان Google Cloud کاربر. تنها در صورتی ارائه می شود که کاربر متعلق به یک سازمان Google Cloud باشد. | |
locale | محل کاربر، که توسط یک برچسب زبان BCP 47 نشان داده شده است. ممکن است در صورت وجود ادعای name ارائه شود. | |
name | نام کامل کاربر، به صورت قابل نمایش. ممکن است زمانی ارائه شود که:
وقتی ادعاهای | |
nonce | مقدار nonce ارائه شده توسط برنامه شما در درخواست احراز هویت. شما باید با اطمینان از اینکه فقط یک بار ارائه می شود، محافظت در برابر حملات تکراری را اعمال کنید. | |
picture | آدرس عکس پروفایل کاربر. ممکن است زمانی ارائه شود که:
وقتی ادعاهای | |
profile | آدرس صفحه نمایه کاربر. ممکن است زمانی ارائه شود که:
هنگامی که ادعاهای |
6. احراز هویت کاربر
پس از به دست آوردن اطلاعات کاربر از رمز شناسه، باید پایگاه داده کاربر برنامه خود را پرس و جو کنید. اگر کاربر از قبل در پایگاه داده شما وجود دارد، اگر پاسخ Google API همه الزامات ورود به سیستم را برآورده کند، باید یک جلسه برنامه را برای آن کاربر شروع کنید.
اگر کاربر در پایگاه داده کاربر شما وجود ندارد، باید کاربر را به جریان ثبت نام کاربر جدید خود هدایت کنید. ممکن است بتوانید کاربر را بر اساس اطلاعاتی که از Google دریافت میکنید بهطور خودکار ثبت کنید، یا حداقل ممکن است بتوانید بسیاری از فیلدهای مورد نیاز خود را در فرم ثبت نام خود از قبل پر کنید. علاوه بر اطلاعات موجود در کد شناسه، میتوانید اطلاعات اضافی نمایه کاربر را در نقاط پایانی نمایه کاربر ما دریافت کنید.
موضوعات پیشرفته
بخشهای زیر Google OAuth 2.0 API را با جزئیات بیشتری توضیح میدهند. این اطلاعات برای توسعه دهندگان با الزامات پیشرفته در مورد احراز هویت و مجوز در نظر گرفته شده است.
دسترسی به سایر API های Google
یکی از مزایای استفاده از OAuth 2.0 برای احراز هویت این است که برنامه شما می تواند همزمان با احراز هویت کاربر، مجوز استفاده از سایر API های Google (مانند YouTube، Google Drive، Calendar یا Contacts) را از طرف کاربر دریافت کند. برای انجام این کار، سایر حوزههای مورد نیاز خود را در درخواست احراز هویتی که به Google ارسال میکنید، وارد کنید. به عنوان مثال، برای افزودن گروه سنی کاربر به درخواست احراز هویت، یک پارامتر scope از openid email https://www.googleapis.com/auth/profile.agerange.read
ارسال کنید. در صفحه رضایت به طور مناسب از کاربر خواسته می شود. رمز دسترسی که از Google دریافت میکنید به شما امکان میدهد به تمام APIهای مرتبط با دامنه دسترسیای که درخواست کردهاید و به آنها اعطا شده است دسترسی داشته باشید.
بازخوانی نشانه ها
در درخواست خود برای دسترسی به API میتوانید درخواست کنید که یک نشانه تازهسازی در طول تبادل code
بازگردانده شود. یک نشانه رفرش دسترسی مداوم برنامه شما به APIهای Google را در حالی که کاربر در برنامه شما حضور ندارد، فراهم می کند. برای درخواست رمز بهروزرسانی، پارامتر access_type
را به offline
در درخواست احراز هویت خود اضافه کنید.
ملاحظات:
- مطمئن شوید که توکن تازهسازی را بهطور ایمن و دائمی ذخیره کنید، زیرا تنها در اولین باری که جریان تبادل کد را انجام میدهید، میتوانید توکن تازهسازی را دریافت کنید.
- محدودیتهایی برای تعداد نشانههای تازهسازی صادر شده وجود دارد: یک محدودیت برای ترکیب مشتری/کاربر، و محدودیت دیگر برای هر کاربر در همه کلاینتها. اگر برنامه شما توکنهای بهروزرسانی بیش از حد درخواست کند، ممکن است با این محدودیتها مواجه شود، در این صورت توکنهای تازهسازی قدیمیتر کار نمیکنند.
برای اطلاعات بیشتر، به بازخوانی نشانه دسترسی (دسترسی آفلاین) مراجعه کنید.
درخواست رضایت مجدد
میتوانید با تنظیم پارامتر prompt
برای consent
در درخواست احراز هویت، از کاربر بخواهید که برنامه شما را مجدداً مجوز دهد. وقتی prompt=consent
گنجانده شده باشد، هر بار که برنامه شما مجوز دامنه دسترسی را درخواست میکند، صفحه رضایت نمایش داده میشود، حتی اگر همه دامنهها قبلاً به پروژه Google APIs شما اعطا شده باشد. به همین دلیل، prompt=consent
فقط در صورت لزوم درج کنید.
برای اطلاعات بیشتر در مورد پارامتر prompt
، prompt
در جدول پارامترهای Authentication URI مراجعه کنید.
پارامترهای URI احراز هویت
جدول زیر توضیحات کامل تری از پارامترهای پذیرفته شده توسط API احراز هویت OAuth 2.0 گوگل ارائه می دهد.
پارامتر | ضروری | شرح |
---|---|---|
client_id | (ضروری) | رشته شناسه مشتری که از API ConsoleCredentials pageبه دست می آورید، همانطور که در دریافت اعتبارنامه OAuth 2.0 توضیح داده شده است. |
nonce | (ضروری) | یک مقدار تصادفی ایجاد شده توسط برنامه شما که محافظت از پخش مجدد را فعال می کند. |
response_type | (ضروری) | اگر مقدار code باشد، یک جریان کد مجوز پایه راهاندازی میکند که برای به دست آوردن نشانهها، به یک POST به نقطه پایانی نشانه نیاز دارد. اگر مقدار token id_token یا id_token token باشد، یک جریان ضمنی راهاندازی میکند که نیاز به استفاده از جاوا اسکریپت در URI تغییر مسیر برای بازیابی نشانهها از شناسه #fragment URI دارد. |
redirect_uri | (ضروری) | محل ارسال پاسخ را مشخص می کند. مقدار این پارامتر باید دقیقاً با یکی از مقادیر تغییر مسیر مجاز که در API ConsoleCredentials page تنظیم کردهاید مطابقت داشته باشد (شامل طرح HTTP یا HTTPS، مورد، و دنباله '/'، در صورت وجود). |
scope | (ضروری) | پارامتر scope باید با مقدار اگر مقدار دامنه اگر مقدار دامنه علاوه بر این محدوده های خاص OpenID، آرگومان scope شما می تواند مقادیر دامنه دیگری را نیز شامل شود. همه مقادیر محدوده باید با فاصله از هم جدا شوند. برای مثال، اگر میخواهید به ازای هر فایل به Google Drive کاربر دسترسی داشته باشد، پارامتر دامنه شما ممکن است برای کسب اطلاعات در مورد دامنه های موجود، به OAuth 2.0 Scopes برای Google API یا اسناد مربوط به Google API که می خواهید استفاده کنید، مراجعه کنید. |
state | (اختیاری، اما به شدت توصیه می شود) | یک رشته مات که در پروتکل رفت و برگشت می شود. یعنی به عنوان پارامتر URI در جریان پایه و در شناسه |
access_type | (اختیاری) | مقادیر مجاز offline و online هستند. این اثر در دسترسی آفلاین مستند شده است. اگر یک نشانه دسترسی درخواست شود، مشتری یک توکن تازهسازی دریافت نمیکند مگر اینکه مقدار offline مشخص شده باشد. |
display | (اختیاری) | یک مقدار رشته ASCII برای تعیین اینکه سرور مجوز چگونه صفحات رابط کاربری تایید و رضایت را نمایش می دهد. مقادیر زیر مشخص شده و توسط سرورهای Google پذیرفته شده است، اما هیچ تاثیری بر رفتار آن ندارند: page ، popup ، touch و wap . |
hd | (اختیاری) | فرآیند ورود به حساب های متعلق به یک سازمان Google Cloud را ساده کنید. با اضافه کردن دامنه سازمانی Google Cloud (به عنوان مثال، mycollege.edu )، میتوانید نشان دهید که رابط کاربری انتخاب حساب باید برای حسابهای موجود در آن دامنه بهینه شود. برای بهینهسازی حسابهای سازمانی Google Cloud بهجای تنها یک دامنه سازمانی Google Cloud، مقدار یک ستاره ( برای کنترل افرادی که میتوانند به برنامه شما دسترسی داشته باشند، به این بهینهسازی UI تکیه نکنید، زیرا درخواستهای سمت کلاینت قابل تغییر هستند. مطمئن شوید که اعتبار شناسه بازگردانده شده دارای یک مقدار ادعای |
include_granted_scopes | (اختیاری) | اگر این پارامتر با مقدار true ارائه شود و درخواست مجوز اعطا شود، مجوز شامل هر مجوز قبلی اعطا شده به این ترکیب کاربر/برنامه برای سایر حوزه ها می شود. مجوز افزایشی را ببینید.توجه داشته باشید که نمی توانید مجوز افزایشی را با جریان برنامه نصب شده انجام دهید. |
login_hint | (اختیاری) | هنگامی که برنامه شما می داند که کدام کاربری را می خواهد احراز هویت کند، می تواند این پارامتر را به عنوان یک اشاره به سرور احراز هویت ارائه دهد. ارسال این راهنمایی، انتخابگر حساب را سرکوب میکند و کادر ایمیل را از قبل در فرم ورود به سیستم پر میکند، یا جلسه مناسب را انتخاب میکند (اگر کاربر از ورود چندگانه استفاده میکند)، که میتواند به شما کمک کند از مشکلاتی که در برنامه شما رخ میدهد جلوگیری کنید. وارد حساب کاربری اشتباه می شود. مقدار می تواند یک آدرس ایمیل یا رشته sub باشد که معادل شناسه گوگل کاربر است. |
prompt | (اختیاری) | فهرستی از مقادیر رشته با فاصله محدود که مشخص می کند آیا سرور مجوز از کاربر برای احراز هویت و رضایت مجدد درخواست می کند یا خیر. مقادیر ممکن عبارتند از:
اگر مقداری مشخص نشده باشد و کاربر قبلاً مجوز دسترسی نداشته باشد، صفحه رضایت به کاربر نشان داده می شود. |
اعتبار سنجی یک رمز شناسه
باید تمام نشانههای شناسه روی سرور خود را تأیید کنید، مگر اینکه بدانید که آنها مستقیماً از Google آمدهاند. به عنوان مثال، سرور شما باید هر کد شناسه ای را که از برنامه های سرویس گیرنده شما دریافت می کند، معتبر بودن تأیید کند.
موارد زیر موارد متداولی هستند که در آن شما ممکن است شناسه های شناسه را به سرور خود ارسال کنید:
- ارسال نشانه های شناسه با درخواست هایی که باید احراز هویت شوند. توکنهای شناسه به کاربر خاصی که درخواست میکند و برای کدام کلاینت آن رمز شناسه داده شده است، میگوید.
توکن های ID حساس هستند و در صورت رهگیری می توان از آنها سوء استفاده کرد. باید اطمینان حاصل کنید که این نشانهها تنها با انتقال آنها از طریق HTTPS و فقط از طریق دادههای POST یا درون هدرهای درخواست، به طور ایمن مدیریت میشوند. اگر توکن های ID را روی سرور خود ذخیره می کنید، باید آنها را نیز به صورت ایمن ذخیره کنید.
یکی از مواردی که توکنهای ID را مفید میکند این است که میتوانید آنها را در قسمتهای مختلف برنامهتان ارسال کنید. این اجزا می توانند از یک نشانه شناسه به عنوان مکانیزم احراز هویت سبک وزن برای احراز هویت برنامه و کاربر استفاده کنند. اما قبل از اینکه بتوانید از اطلاعات موجود در شناسه شناسه استفاده کنید یا به عنوان ادعایی که کاربر احراز هویت کرده است به آن تکیه کنید، باید آن را تأیید کنید.
اعتبارسنجی یک نشانه ID به چندین مرحله نیاز دارد:
- بررسی کنید که کد شناسه به درستی توسط صادرکننده امضا شده باشد. توکنهای صادر شده توسط Google با استفاده از یکی از گواهیهای موجود در URI مشخص شده در مقدار فراداده
jwks_uri
سند Discovery امضا میشوند. - بررسی کنید که ارزش ادعای
iss
در کد شناسه برابر باhttps://accounts.google.com
یاaccounts.google.com
باشد. - بررسی کنید که ارزش ادعای
aud
در کد ID با شناسه مشتری برنامه شما برابر است. - بررسی کنید که زمان انقضا (ادعای
exp
) نشانه شناسه نگذشته باشد. - اگر مقدار پارامتر hd را در درخواست مشخص کردهاید، بررسی کنید که کد ID دارای ادعای
hd
است که با دامنه مورد قبول مرتبط با سازمان Google Cloud مطابقت دارد.
مراحل 2 تا 5 فقط شامل مقایسه رشته و تاریخ است که کاملاً ساده است، بنابراین در اینجا جزئیات آنها را توضیح نمی دهیم.
مرحله اول پیچیده تر است و شامل بررسی امضای رمزنگاری می شود. برای اهداف اشکالزدایی ، میتوانید از نقطه پایانی tokeninfo
Google برای مقایسه با پردازش محلی اجرا شده در سرور یا دستگاه خود استفاده کنید. فرض کنید مقدار کد شناسه شما XYZ123
است. سپس URI https://oauth2.googleapis.com/tokeninfo?id_token= XYZ123
را حذف کنید. اگر امضای رمز معتبر باشد، پاسخ، بار JWT در شکل شی JSON رمزگشایی شده آن خواهد بود.
نقطه پایانی tokeninfo
برای اشکالزدایی مفید است، اما برای اهداف تولید، کلیدهای عمومی Google را از نقطه پایانی کلیدها بازیابی کنید و اعتبارسنجی را به صورت محلی انجام دهید. شما باید URI کلیدها را از سند Discovery با استفاده از مقدار فراداده jwks_uri
بازیابی کنید. درخواستها به نقطه پایانی اشکالزدایی ممکن است نادیده گرفته شوند یا در غیر این صورت دچار خطاهای متناوب شوند.
از آنجایی که Google کلیدهای عمومی خود را به ندرت تغییر می دهد، می توانید آنها را با استفاده از دستورالعمل های حافظه پنهان پاسخ HTTP ذخیره کنید و در اکثر موارد، اعتبار سنجی محلی را بسیار کارآمدتر از استفاده از نقطه پایانی tokeninfo
انجام دهید. این اعتبار به بازیابی و تجزیه گواهی ها و برقراری تماس های رمزنگاری مناسب برای بررسی امضا نیاز دارد. خوشبختانه، کتابخانههای با اشکال زدایی خوبی در زبانهای مختلف برای انجام این کار وجود دارد (به jwt.io مراجعه کنید).
دریافت اطلاعات پروفایل کاربری
برای به دست آوردن اطلاعات نمایه اضافی در مورد کاربر، می توانید از نشانه دسترسی (که برنامه شما در جریان احراز هویت دریافت می کند) و استاندارد OpenID Connect استفاده کنید:
برای سازگاری با OpenID، باید مقادیر محدوده
openid profile
را در درخواست احراز هویت خود وارد کنید.اگر میخواهید آدرس ایمیل کاربر درج شود، میتوانید مقدار دامنه اضافی
email
مشخص کنید. برای تعیینprofile
وemail
، می توانید پارامتر زیر را در URI درخواست احراز هویت خود وارد کنید:scope=openid%20profile%20email
- رمز دسترسی خود را به هدر مجوز اضافه کنید و یک درخواست HTTPS
GET
به نقطه پایانی اطلاعات کاربر ارسال کنید، که باید آن را از سند Discovery با استفاده از مقدار فوق دادهuserinfo_endpoint
بازیابی کنید. پاسخ اطلاعات کاربر شامل اطلاعاتی در مورد کاربر است، همانطور که درOpenID Connect Standard Claims
و مقدار ابردادهclaims_supported
سند Discovery توضیح داده شده است. کاربران یا سازمانهای آنها ممکن است انتخاب کنند که فیلدهای خاصی را عرضه کنند یا از آن خودداری کنند، بنابراین ممکن است اطلاعاتی برای هر زمینه برای محدوده دسترسی مجاز خود دریافت نکنید.
سند کشف
پروتکل OpenID Connect نیاز به استفاده از چندین نقطه پایانی برای احراز هویت کاربران و درخواست منابع از جمله نشانهها، اطلاعات کاربر و کلیدهای عمومی دارد.
برای سادهسازی پیادهسازیها و افزایش انعطافپذیری، OpenID Connect اجازه استفاده از «سند کشف» را میدهد، یک سند JSON که در یک مکان شناختهشده یافت میشود که حاوی جفتهای کلید-مقدار است که جزئیاتی را درباره پیکربندی ارائهدهنده OpenID Connect، از جمله URIهای مجوز ارائه میکند. ، نشانه، ابطال، اطلاعات کاربری و نقاط پایانی کلیدهای عمومی. سند Discovery برای سرویس OpenID Connect Google ممکن است از این موارد بازیابی شود:
https://accounts.google.com/.well-known/openid-configuration
برای استفاده از سرویسهای OpenID Connect Google، باید URI Discovery-document ( https://accounts.google.com/.well-known/openid-configuration
) را در برنامه خود کدگذاری کنید. برنامه شما سند را واکشی می کند، قوانین کش را در پاسخ اعمال می کند، سپس URI های نقطه پایانی را در صورت نیاز از آن بازیابی می کند. برای مثال، برای احراز هویت یک کاربر، کد شما مقدار فراداده authorization_endpoint
( https://accounts.google.com/o/oauth2/v2/auth
در مثال زیر) را به عنوان URI پایه برای درخواستهای احراز هویت که به گوگل.
در اینجا نمونه ای از چنین سندی وجود دارد. نام فیلدها همانهایی هستند که در OpenID Connect Discovery 1.0 مشخص شده اند (برای معانی آنها به آن سند مراجعه کنید). مقادیر صرفاً گویا هستند و ممکن است تغییر کنند، اگرچه از نسخه اخیر سند واقعی Google Discovery کپی شده اند:
{ "issuer": "https://accounts.google.com", "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth", "device_authorization_endpoint": "https://oauth2.googleapis.com/device/code", "token_endpoint": "https://oauth2.googleapis.com/token", "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo", "revocation_endpoint": "https://oauth2.googleapis.com/revoke", "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs", "response_types_supported": [ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "scopes_supported": [ "openid", "email", "profile" ], "token_endpoint_auth_methods_supported": [ "client_secret_post", "client_secret_basic" ], "claims_supported": [ "aud", "email", "email_verified", "exp", "family_name", "given_name", "iat", "iss", "locale", "name", "picture", "sub" ], "code_challenge_methods_supported": [ "plain", "S256" ] }
ممکن است بتوانید با ذخیره مقادیر از سند Discovery از HTTP رفت و برگشت اجتناب کنید. هدرهای ذخیره استاندارد HTTP استفاده می شوند و باید رعایت شوند.
کتابخانه های مشتری
کتابخانه های سرویس گیرنده زیر با ادغام با فریمورک های محبوب، اجرای OAuth 2.0 را ساده تر می کنند:
انطباق با OpenID Connect
سیستم احراز هویت OAuth 2.0 Google از ویژگی های مورد نیاز مشخصات OpenID Connect Core پشتیبانی می کند. هر سرویس گیرنده ای که برای کار با OpenID Connect طراحی شده است، باید با این سرویس همکاری کند (به استثنای OpenID Request Object ).
Google's OAuth 2.0 APIs can be used for both authentication and authorization. This document describes our OAuth 2.0 implementation for authentication, which conforms to the OpenID Connect specification, and is OpenID Certified . The documentation found in Using OAuth 2.0 to Access Google APIs also applies to this service. If you want to explore this protocol interactively, we recommend the Google OAuth 2.0 Playground . To get help on Stack Overflow , tag your questions with 'google-oauth'.
Setting up OAuth 2.0
Before your application can use Google's OAuth 2.0 authentication system for user login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials, set a redirect URI, and (optionally) customize the branding information that your users see on the user-consent screen. You can also use the API Console to create a service account, enable billing, set up filtering, and do other tasks. For more details, see the Google API ConsoleHelp .
Obtain OAuth 2.0 credentials
You need OAuth 2.0 credentials, including a client ID and client secret, to authenticate users and gain access to Google's APIs.
برای مشاهده شناسه مشتری و راز مشتری برای اعتبار OAuth 2.0 داده شده ، روی متن زیر کلیک کنید: اعتبار را انتخاب کنید . در پنجره ای که باز می شود ، پروژه خود و اعتبار مورد نظر خود را انتخاب کرده و سپس بر روی View کلیک کنید.
یا ، شناسه مشتری و راز مشتری خود را از صفحه اعتبارنامه در API Console :
- Go to the Credentials page.
- بر روی نام اعتبار خود یا نماد مداد ( create ) کلیک create . شناسه مشتری و راز شما در بالای صفحه قرار دارند.
Set a redirect URI
The redirect URI that you set in the API Console determines where Google sends responses to your authentication requests .
برای ایجاد ، مشاهده و یا ویرایش URI های تغییر مسیر برای اعتبار OAuth 2.0 داده شده ، موارد زیر را انجام دهید:
- Go to the Credentials page.
- در بخش شناسه های مشتری OAuth 2.0 از صفحه ، روی اعتبار نامه کلیک کنید.
- URI های تغییر مسیر را مشاهده یا ویرایش کنید.
اگر در صفحه شناسنامه ها هیچ بخش شناسه مشتری OAuth 2.0 وجود ندارد ، پروژه شما هیچ اعتبار OAuth ندارد. برای ایجاد یک ، روی ایجاد اعتبارنامه کلیک کنید.
Customize the user consent screen
For your users, the OAuth 2.0 authentication experience includes a consent screen that describes the information that the user is releasing and the terms that apply. For example, when the user logs in, they might be asked to give your app access to their email address and basic account information. You request access to this information using the scope
parameter, which your app includes in its authentication request . You can also use scopes to request access to other Google APIs.
The user consent screen also presents branding information such as your product name, logo, and a homepage URL. You control the branding information in the API Console.
برای فعال کردن صفحه رضایت پروژه خود:
- Consent Screen page در Google API Console .
- If prompted, select a project, or create a new one.
- فرم را پر کنید و روی ذخیره کلیک کنید.
The following consent dialog shows what a user would see when a combination of OAuth 2.0 and Google Drive scopes are present in the request. (This generic dialog was generated using the Google OAuth 2.0 Playground , so it does not include branding information that would be set in the API Console.)

Accessing the service
Google and third parties provide libraries that you can use to take care of many of the implementation details of authenticating users and gaining access to Google APIs. Examples include Google Identity Services and the Google client libraries , which are available for a variety of platforms.
If you choose not to use a library, follow the instructions in the remainder of this document, which describes the HTTP request flows that underly the available libraries.
Authenticating the user
Authenticating the user involves obtaining an ID token and validating it. ID tokens are a standardized feature of OpenID Connect designed for use in sharing identity assertions on the Internet.
The most commonly used approaches for authenticating a user and obtaining an ID token are called the "server" flow and the "implicit" flow. The server flow allows the back-end server of an application to verify the identity of the person using a browser or mobile device. The implicit flow is used when a client-side application (typically a JavaScript app running in the browser) needs to access APIs directly instead of via its back-end server.
This document describes how to perform the server flow for authenticating the user. The implicit flow is significantly more complicated because of security risks in handling and using tokens on the client side. If you need to implement an implicit flow, we highly recommend using Google Identity Services .
Server flow
Make sure you set up your app in the API Console to enable it to use these protocols and authenticate your users. When a user tries to log in with Google, you need to:
- Create an anti-forgery state token
- Send an authentication request to Google
- Confirm the anti-forgery state token
- Exchange
code
for access token and ID token - Obtain user information from the ID token
- Authenticate the user
1. Create an anti-forgery state token
You must protect the security of your users by preventing request forgery attacks. The first step is creating a unique session token that holds state between your app and the user's client. You later match this unique session token with the authentication response returned by the Google OAuth Login service to verify that the user is making the request and not a malicious attacker. These tokens are often referred to as cross-site request forgery ( CSRF ) tokens.
One good choice for a state token is a string of 30 or so characters constructed using a high-quality random-number generator. Another is a hash generated by signing some of your session state variables with a key that is kept secret on your back-end.
The following code demonstrates generating unique session tokens.
PHP
You must download the Google APIs client library for PHP to use this sample.
// Create a state token to prevent request forgery. // Store it in the session for later validation. $state = bin2hex(random_bytes(128/8)); $app['session']->set('state', $state); // Set the client ID, token state, and application name in the HTML while // serving it. return $app['twig']->render('index.html', array( 'CLIENT_ID' => CLIENT_ID, 'STATE' => $state, 'APPLICATION_NAME' => APPLICATION_NAME ));
جاوا
You must download the Google APIs client library for Java to use this sample.
// Create a state token to prevent request forgery. // Store it in the session for later validation. String state = new BigInteger(130, new SecureRandom()).toString(32); request.session().attribute("state", state); // Read index.html into memory, and set the client ID, // token state, and application name in the HTML before serving it. return new Scanner(new File("index.html"), "UTF-8") .useDelimiter("\\A").next() .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID) .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state) .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME);
پایتون
You must download the Google APIs client library for Python to use this sample.
# Create a state token to prevent request forgery. # Store it in the session for later validation. state = hashlib.sha256(os.urandom(1024)).hexdigest() session['state'] = state # Set the client ID, token state, and application name in the HTML while # serving it. response = make_response( render_template('index.html', CLIENT_ID=CLIENT_ID, STATE=state, APPLICATION_NAME=APPLICATION_NAME))
2. Send an authentication request to Google
The next step is forming an HTTPS GET
request with the appropriate URI parameters. Note the use of HTTPS rather than HTTP in all the steps of this process; HTTP connections are refused. You should retrieve the base URI from the Discovery document using the authorization_endpoint
metadata value. The following discussion assumes the base URI is https://accounts.google.com/o/oauth2/v2/auth
.
For a basic request, specify the following parameters:
-
client_id
, which you obtain from the API ConsoleCredentials page. -
response_type
, which in a basic authorization code flow request should becode
. (Read more atresponse_type
.) -
scope
, which in a basic request should beopenid email
. (Read more atscope
.) -
redirect_uri
should be the HTTP endpoint on your server that will receive the response from Google. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in the API ConsoleCredentials page. If this value doesn't match an authorized URI, the request will fail with aredirect_uri_mismatch
error. -
state
should include the value of the anti-forgery unique session token, as well as any other information needed to recover the context when the user returns to your application, eg, the starting URL. (Read more atstate
.) -
nonce
is a random value generated by your app that enables replay protection when present. -
login_hint
can be the user's email address or thesub
string, which is equivalent to the user's Google ID. If you do not provide alogin_hint
and the user is currently logged in, the consent screen includes a request for approval to release the user's email address to your app. (Read more atlogin_hint
.) - Use the
hd
parameter to optimize the OpenID Connect flow for users of a particular domain associated with a Google Cloud organization. (Read more athd
.)
Here is an example of a complete OpenID Connect authentication URI, with line breaks and spaces for readability:
https://accounts.google.com/o/oauth2/v2/auth? response_type=code& client_id=424911365001.apps.googleusercontent.com& scope=openid%20email& redirect_uri=https%3A//oauth2.example.com/code& state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2-login-demo.example.com%2FmyHome& login_hint=jsmith@example.com& nonce=0394852-3190485-2490358& hd=example.com
Users are required to give consent if your app requests any new information about them, or if your app requests account access that they have not previously approved.
3. Confirm anti-forgery state token
The response is sent to the redirect_uri
that you specified in the request . All responses are returned in the query string, as shown below:
https://oauth2.example.com/code?state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foa2cb.example.com%2FmyHome&code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&scope=openid%20email%20https://www.googleapis.com/auth/userinfo.email
On the server, you must confirm that the state
received from Google matches the session token you created in Step 1 . This round-trip verification helps to ensure that the user, not a malicious script, is making the request.
The following code demonstrates confirming the session tokens that you created in Step 1:
PHP
You must download the Google APIs client library for PHP to use this sample.
// Ensure that there is no request forgery going on, and that the user // sending us this connect request is the user that was supposed to. if ($request->get('state') != ($app['session']->get('state'))) { return new Response('Invalid state parameter', 401); }
جاوا
You must download the Google APIs client library for Java to use this sample.
// Ensure that there is no request forgery going on, and that the user // sending us this connect request is the user that was supposed to. if (!request.queryParams("state").equals( request.session().attribute("state"))) { response.status(401); return GSON.toJson("Invalid state parameter."); }
پایتون
You must download the Google APIs client library for Python to use this sample.
# Ensure that the request is not a forgery and that the user sending # this connect request is the expected user. if request.args.get('state', '') != session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response
4. Exchange code
for access token and ID token
The response includes a code
parameter, a one-time authorization code that your server can exchange for an access token and ID token. Your server makes this exchange by sending an HTTPS POST
request. The POST
request is sent to the token endpoint, which you should retrieve from the Discovery document using the token_endpoint
metadata value. The following discussion assumes the endpoint is https://oauth2.googleapis.com/token
. The request must include the following parameters in the POST
body:
زمینه های | |
---|---|
code | The authorization code that is returned from the initial request . |
client_id | The client ID that you obtain from the API ConsoleCredentials page, as described in Obtain OAuth 2.0 credentials . |
client_secret | The client secret that you obtain from the API ConsoleCredentials page, as described in Obtain OAuth 2.0 credentials . |
redirect_uri | An authorized redirect URI for the given client_id specified in the API ConsoleCredentials page, as described in Set a redirect URI . |
grant_type | This field must contain a value of authorization_code , as defined in the OAuth 2.0 specification . |
The actual request might look like the following example:
POST /token HTTP/1.1 Host: oauth2.googleapis.com Content-Type: application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=your-client-id& client_secret=your-client-secret& redirect_uri=https%3A//oauth2.example.com/code& grant_type=authorization_code
A successful response to this request contains the following fields in a JSON array:
زمینه های | |
---|---|
access_token | A token that can be sent to a Google API. |
expires_in | The remaining lifetime of the access token in seconds. |
id_token | A JWT that contains identity information about the user that is digitally signed by Google. |
scope | The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. |
token_type | Identifies the type of token returned. At this time, this field always has the value Bearer . |
refresh_token | (optional) This field is only present if the |
5. Obtain user information from the ID token
An ID Token is a JWT (JSON Web Token), that is, a cryptographically signed Base64-encoded JSON object. Normally, it is critical that you validate an ID token before you use it, but since you are communicating directly with Google over an intermediary-free HTTPS channel and using your client secret to authenticate yourself to Google, you can be confident that the token you receive really comes from Google and is valid. If your server passes the ID token to other components of your app, it is extremely important that the other components validate the token before using it.
Since most API libraries combine the validation with the work of decoding the base64url-encoded values and parsing the JSON within, you will probably end up validating the token anyway as you access the claims in the ID token.
An ID token's payload
An ID token is a JSON object containing a set of name/value pairs. Here's an example, formatted for readability:
{ "iss": "https://accounts.google.com", "azp": "1234987819200.apps.googleusercontent.com", "aud": "1234987819200.apps.googleusercontent.com", "sub": "10769150350006150715113082367", "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q", "hd": "example.com", "email": "jsmith@example.com", "email_verified": "true", "iat": 1353601026, "exp": 1353604926, "nonce": "0394852-3190485-2490358" }
Google ID Tokens may contain the following fields (known as claims ):
Claim | Provided | شرح |
---|---|---|
aud | always | The audience that this ID token is intended for. It must be one of the OAuth 2.0 client IDs of your application. |
exp | always | Expiration time on or after which the ID token must not be accepted. Represented in Unix time (integer seconds). |
iat | always | The time the ID token was issued. Represented in Unix time (integer seconds). |
iss | always | The Issuer Identifier for the Issuer of the response. Always https://accounts.google.com or accounts.google.com for Google ID tokens. |
sub | always | An identifier for the user, unique among all Google accounts and never reused. A Google account can have multiple email addresses at different points in time, but the sub value is never changed. Use sub within your application as the unique-identifier key for the user. Maximum length of 255 case-sensitive ASCII characters. |
at_hash | Access token hash. Provides validation that the access token is tied to the identity token. If the ID token is issued with an access_token value in the server flow, this claim is always included. This claim can be used as an alternate mechanism to protect against cross-site request forgery attacks, but if you follow Step 1 and Step 3 it is not necessary to verify the access token. | |
azp | The client_id of the authorized presenter. This claim is only needed when the party requesting the ID token is not the same as the audience of the ID token. This may be the case at Google for hybrid apps where a web application and Android app have a different OAuth 2.0 client_id but share the same Google APIs project. | |
email | The user's email address. This value may not be unique to this user and is not suitable for use as a primary key. Provided only if your scope included the email scope value. | |
email_verified | True if the user's e-mail address has been verified; otherwise false. | |
family_name | The user's surname(s) or last name(s). Might be provided when a name claim is present. | |
given_name | The user's given name(s) or first name(s). Might be provided when a name claim is present. | |
hd | The domain associated with the Google Cloud organization of the user. Provided only if the user belongs to a Google Cloud organization. | |
locale | The user's locale, represented by a BCP 47 language tag. Might be provided when a name claim is present. | |
name | The user's full name, in a displayable form. Might be provided when:
When | |
nonce | The value of the nonce supplied by your app in the authentication request. You should enforce protection against replay attacks by ensuring it is presented only once. | |
picture | The URL of the user's profile picture. Might be provided when:
When | |
profile | The URL of the user's profile page. Might be provided when:
When |
6. Authenticate the user
After obtaining user information from the ID token, you should query your app's user database. If the user already exists in your database, you should start an application session for that user if all login requirements are met by the Google API response.
If the user does not exist in your user database, you should redirect the user to your new-user sign-up flow. You may be able to auto-register the user based on the information you receive from Google, or at the very least you may be able to pre-populate many of the fields that you require on your registration form. In addition to the information in the ID token, you can get additional user profile information at our user profile endpoints.
Advanced topics
The following sections describe the Google OAuth 2.0 API in greater detail. This information is intended for developers with advanced requirements around authentication and authorization.
Access to other Google APIs
One of the advantages of using OAuth 2.0 for authentication is that your application can get permission to use other Google APIs on behalf of the user (such as YouTube, Google Drive, Calendar, or Contacts) at the same time as you authenticate the user. To do this, include the other scopes that you need in the authentication request that you send to Google. For example, to add user's age group to your authentication request, pass a scope parameter of openid email https://www.googleapis.com/auth/profile.agerange.read
. The user is prompted appropriately on the consent screen . The access token that you receive back from Google allows you to access all the APIs related to the scopes of access you requested and were granted.
Refresh tokens
In your request for API access you can request a refresh token to be returned during the code
exchange . A refresh token provides your app continuous access to Google APIs while the user is not present in your application. To request a refresh token, add set the access_type
parameter to offline
in your authentication request .
Considerations:
- Be sure to store the refresh token safely and permanently, because you can only obtain a refresh token the first time that you perform the code exchange flow.
- There are limits on the number of refresh tokens that are issued: one limit per client/user combination, and another per user across all clients. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens stop working.
For more information, see Refreshing an access token (offline access) .
Prompting re-consent
You can prompt the user to re-authorize your app by setting the prompt
parameter to consent
in your authentication request . When prompt=consent
is included, the consent screen is displayed every time your app requests authorization of scopes of access, even if all scopes were previously granted to your Google APIs project. For this reason, include prompt=consent
only when necessary.
For more about the prompt
parameter, see prompt
in the Authentication URI parameters table.
Authentication URI parameters
The following table gives more complete descriptions of the parameters accepted by Google's OAuth 2.0 authentication API.
پارامتر | ضروری | شرح |
---|---|---|
client_id | (Required) | The client ID string that you obtain from the API ConsoleCredentials page, as described in Obtain OAuth 2.0 credentials . |
nonce | (Required) | A random value generated by your app that enables replay protection. |
response_type | (Required) | If the value is code , launches a Basic authorization code flow , requiring a POST to the token endpoint to obtain the tokens. If the value is token id_token or id_token token , launches an Implicit flow , requiring the use of JavaScript at the redirect URI to retrieve tokens from the URI #fragment identifier . |
redirect_uri | (Required) | Determines where the response is sent. The value of this parameter must exactly match one of the authorized redirect values that you set in the API ConsoleCredentials page (including the HTTP or HTTPS scheme, case, and trailing '/', if any). |
scope | (Required) | The scope parameter must begin with the If the If the In addition to these OpenID-specific scopes, your scope argument can also include other scope values. All scope values must be space-separated. For example, if you wanted per-file access to a user's Google Drive, your scope parameter might be For information about available scopes, see OAuth 2.0 Scopes for Google APIs or the documentation for the Google API you would like to use. |
state | (Optional, but strongly recommended) | An opaque string that is round-tripped in the protocol; that is to say, it is returned as a URI parameter in the Basic flow, and in the URI The |
access_type | (Optional) | The allowed values are offline and online . The effect is documented in Offline Access ; if an access token is being requested, the client does not receive a refresh token unless a value of offline is specified. |
display | (Optional) | An ASCII string value for specifying how the authorization server displays the authentication and consent user interface pages. The following values are specified, and accepted by the Google servers, but do not have any effect on its behavior: page , popup , touch , and wap . |
hd | (Optional) | Streamline the login process for accounts owned by a Google Cloud organization. By including the Google Cloud organization domain (for example, mycollege.edu ), you can indicate that the account selection UI should be optimized for accounts at that domain. To optimize for Google Cloud organization accounts generally instead of just one Google Cloud organization domain, set a value of an asterisk ( Don't rely on this UI optimization to control who can access your app, as client-side requests can be modified. Be sure to validate that the returned ID token has an |
include_granted_scopes | (Optional) | If this parameter is provided with the value true , and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes; see Incremental authorization .Note that you cannot do incremental authorization with the Installed App flow. |
login_hint | (Optional) | When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fills the email box on the sign-in form, or selects the proper session (if the user is using multiple sign-in ), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string, which is equivalent to the user's Google ID. |
prompt | (Optional) | A space-delimited list of string values that specifies whether the authorization server prompts the user for reauthentication and consent. The possible values are:
If no value is specified and the user has not previously authorized access, then the user is shown a consent screen. |
Validating an ID token
You need to validate all ID tokens on your server unless you know that they came directly from Google. For example, your server must verify as authentic any ID tokens it receives from your client apps.
The following are common situations where you might send ID tokens to your server:
- Sending ID tokens with requests that need to be authenticated. The ID tokens tell you the particular user making the request and for which client that ID token was granted.
ID tokens are sensitive and can be misused if intercepted. You must ensure that these tokens are handled securely by transmitting them only over HTTPS and only via POST data or within request headers. If you store ID tokens on your server, you must also store them securely.
One thing that makes ID tokens useful is that fact that you can pass them around different components of your app. These components can use an ID token as a lightweight authentication mechanism authenticating the app and the user. But before you can use the information in the ID token or rely on it as an assertion that the user has authenticated, you must validate it.
Validation of an ID token requires several steps:
- Verify that the ID token is properly signed by the issuer. Google-issued tokens are signed using one of the certificates found at the URI specified in the
jwks_uri
metadata value of the Discovery document . - Verify that the value of the
iss
claim in the ID token is equal tohttps://accounts.google.com
oraccounts.google.com
. - Verify that the value of the
aud
claim in the ID token is equal to your app's client ID. - Verify that the expiry time (
exp
claim) of the ID token has not passed. - If you specified a hd parameter value in the request, verify that the ID token has a
hd
claim that matches an accepted domain associated with a Google Cloud organization.
Steps 2 to 5 involve only string and date comparisons which are quite straightforward, so we won't detail them here.
The first step is more complex, and involves cryptographic signature checking. For debugging purposes, you can use Google's tokeninfo
endpoint to compare against local processing implemented on your server or device. Suppose your ID token's value is XYZ123
. Then you would dereference the URI https://oauth2.googleapis.com/tokeninfo?id_token= XYZ123
. If the token signature is valid, the response would be the JWT payload in its decoded JSON object form.
The tokeninfo
endpoint is useful for debugging but for production purposes, retrieve Google's public keys from the keys endpoint and perform the validation locally. You should retrieve the keys URI from the Discovery document using the jwks_uri
metadata value. Requests to the debugging endpoint may be throttled or otherwise subject to intermittent errors.
Since Google changes its public keys only infrequently, you can cache them using the cache directives of the HTTP response and, in the vast majority of cases, perform local validation much more efficiently than by using the tokeninfo
endpoint. This validation requires retrieving and parsing certificates, and making the appropriate cryptographic calls to check the signature. Fortunately, there are well-debugged libraries available in a wide variety of languages to accomplish this (see jwt.io ).
Obtaining user profile information
To obtain additional profile information about the user, you can use the access token (which your application receives during the authentication flow ) and the OpenID Connect standard:
To be OpenID-compliant, you must include the
openid profile
scope values in your authentication request .If you want the user's email address to be included, you can specify an additional scope value of
email
. To specify bothprofile
andemail
, you can include the following parameter in your authentication request URI:scope=openid%20profile%20email
- Add your access token to the authorization header and make an HTTPS
GET
request to the userinfo endpoint, which you should retrieve from the Discovery document using theuserinfo_endpoint
metadata value. The userinfo response includes information about the user, as described inOpenID Connect Standard Claims
and theclaims_supported
metadata value of the Discovery document. Users or their organizations may choose to supply or withhold certain fields, so you might not get information for every field for your authorized scopes of access.
The Discovery document
The OpenID Connect protocol requires the use of multiple endpoints for authenticating users, and for requesting resources including tokens, user information, and public keys.
To simplify implementations and increase flexibility, OpenID Connect allows the use of a "Discovery document," a JSON document found at a well-known location containing key-value pairs which provide details about the OpenID Connect provider's configuration, including the URIs of the authorization, token, revocation, userinfo, and public-keys endpoints. The Discovery document for Google's OpenID Connect service may be retrieved from:
https://accounts.google.com/.well-known/openid-configuration
To use Google's OpenID Connect services, you should hard-code the Discovery-document URI ( https://accounts.google.com/.well-known/openid-configuration
) into your application. Your application fetches the document, applies caching rules in the response, then retrieves endpoint URIs from it as needed. For example, to authenticate a user, your code would retrieve the authorization_endpoint
metadata value ( https://accounts.google.com/o/oauth2/v2/auth
in the example below) as the base URI for authentication requests that are sent to Google.
Here is an example of such a document; the field names are those specified in OpenID Connect Discovery 1.0 (refer to that document for their meanings). The values are purely illustrative and might change, although they are copied from a recent version of the actual Google Discovery document:
{ "issuer": "https://accounts.google.com", "authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth", "device_authorization_endpoint": "https://oauth2.googleapis.com/device/code", "token_endpoint": "https://oauth2.googleapis.com/token", "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo", "revocation_endpoint": "https://oauth2.googleapis.com/revoke", "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs", "response_types_supported": [ "code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "scopes_supported": [ "openid", "email", "profile" ], "token_endpoint_auth_methods_supported": [ "client_secret_post", "client_secret_basic" ], "claims_supported": [ "aud", "email", "email_verified", "exp", "family_name", "given_name", "iat", "iss", "locale", "name", "picture", "sub" ], "code_challenge_methods_supported": [ "plain", "S256" ] }
You may be able to avoid an HTTP round-trip by caching the values from the Discovery document. Standard HTTP caching headers are used and should be respected.
Client libraries
The following client libraries make implementing OAuth 2.0 simpler by integrating with popular frameworks:
OpenID Connect compliance
Google's OAuth 2.0 authentication system supports the required features of the OpenID Connect Core specification. Any client which is designed to work with OpenID Connect should interoperate with this service (with the exception of the OpenID Request Object ).