ওয়েব সার্ভার অ্যাপ্লিকেশনের জন্য OAuth 2.0 ব্যবহার করা

এই দস্তাবেজটি ব্যাখ্যা করে যে কীভাবে ওয়েব সার্ভার অ্যাপ্লিকেশনগুলি Google API ক্লায়েন্ট লাইব্রেরি বা Google OAuth 2.0 এন্ডপয়েন্ট ব্যবহার করে Google API অ্যাক্সেস করার জন্য OAuth 2.0 অনুমোদন কার্যকর করতে।

OAuth 2.0 ব্যবহারকারীদের তাদের ব্যবহারকারীর নাম, পাসওয়ার্ড এবং অন্যান্য তথ্য গোপন রেখে একটি অ্যাপ্লিকেশনের সাথে নির্দিষ্ট ডেটা ভাগ করার অনুমতি দেয়৷ উদাহরণস্বরূপ, একটি অ্যাপ্লিকেশন OAuth 2.0 ব্যবহার করে ব্যবহারকারীদের কাছ থেকে তাদের Google ড্রাইভে ফাইল সংরক্ষণের অনুমতি পেতে পারে।

এই OAuth 2.0 ফ্লো বিশেষভাবে ব্যবহারকারীর অনুমোদনের জন্য। এটি এমন অ্যাপ্লিকেশনের জন্য ডিজাইন করা হয়েছে যা গোপন তথ্য সঞ্চয় করতে পারে এবং অবস্থা বজায় রাখতে পারে। একটি সঠিকভাবে অনুমোদিত ওয়েব সার্ভার অ্যাপ্লিকেশন একটি API অ্যাক্সেস করতে পারে যখন ব্যবহারকারী অ্যাপ্লিকেশনটির সাথে ইন্টারঅ্যাক্ট করে বা ব্যবহারকারী অ্যাপ্লিকেশনটি ছেড়ে যাওয়ার পরে।

ওয়েব সার্ভার অ্যাপ্লিকেশনগুলি প্রায়শই API অনুরোধগুলি অনুমোদন করার জন্য পরিষেবা অ্যাকাউন্টগুলি ব্যবহার করে, বিশেষত যখন ব্যবহারকারী-নির্দিষ্ট ডেটার পরিবর্তে প্রকল্প-ভিত্তিক ডেটা অ্যাক্সেস করতে ক্লাউড এপিআইগুলিকে কল করে। ওয়েব সার্ভার অ্যাপ্লিকেশন ব্যবহারকারীর অনুমোদনের সাথে একত্রে পরিষেবা অ্যাকাউন্ট ব্যবহার করতে পারে।

ক্লায়েন্ট লাইব্রেরি

এই পৃষ্ঠার ভাষা-নির্দিষ্ট উদাহরণগুলি OAuth 2.0 অনুমোদন কার্যকর করতে Google API ক্লায়েন্ট লাইব্রেরি ব্যবহার করে। কোড নমুনা চালানোর জন্য, আপনাকে প্রথমে আপনার ভাষার জন্য ক্লায়েন্ট লাইব্রেরি ইনস্টল করতে হবে।

যখন আপনি আপনার অ্যাপ্লিকেশনের OAuth 2.0 ফ্লো পরিচালনা করার জন্য একটি Google API ক্লায়েন্ট লাইব্রেরি ব্যবহার করেন, তখন ক্লায়েন্ট লাইব্রেরি এমন অনেকগুলি কাজ করে যা অ্যাপ্লিকেশনটিকে অন্যথায় নিজে থেকে পরিচালনা করতে হবে৷ উদাহরণস্বরূপ, এটি নির্ধারণ করে যে কখন অ্যাপ্লিকেশনটি সঞ্চিত অ্যাক্সেস টোকেনগুলি ব্যবহার বা রিফ্রেশ করতে পারে সেইসাথে কখন অ্যাপ্লিকেশনটিকে পুনরায় সম্মতি নিতে হবে। ক্লায়েন্ট লাইব্রেরি সঠিক রিডাইরেক্ট ইউআরএল তৈরি করে এবং রিডাইরেক্ট হ্যান্ডলার প্রয়োগ করতে সাহায্য করে যা অ্যাক্সেস টোকেনের জন্য অনুমোদন কোড বিনিময় করে।

সার্ভার-সাইড অ্যাপ্লিকেশনগুলির জন্য Google API ক্লায়েন্ট লাইব্রেরিগুলি নিম্নলিখিত ভাষার জন্য উপলব্ধ:

পূর্বশর্ত

আপনার প্রকল্পের জন্য API সক্ষম করুন

Google API-কে কল করে এমন যেকোনো অ্যাপ্লিকেশনকে API Consoleএ সেই APIগুলি সক্ষম করতে হবে।

আপনার প্রকল্পের জন্য একটি API সক্ষম করতে:

  1. Open the API Library এ Google API Console।
  2. If prompted, select a project, or create a new one.
  3. API Library পণ্য পরিবার এবং জনপ্রিয়তা দ্বারা গোষ্ঠীবদ্ধ সমস্ত উপলব্ধ API তালিকাভুক্ত করে। আপনি যে APIটি সক্ষম করতে চান তা তালিকায় দৃশ্যমান না হলে, এটি খুঁজতে অনুসন্ধান ব্যবহার করুন, অথবা এটি যে পণ্যের পরিবারে রয়েছে তার সমস্ত দেখুন ক্লিক করুন৷
  4. আপনি যে APIটি সক্ষম করতে চান তা নির্বাচন করুন, তারপর সক্ষম বোতামটি ক্লিক করুন।
  5. If prompted, enable billing.
  6. If prompted, read and accept the API's Terms of Service.

অনুমোদনের শংসাপত্র তৈরি করুন

Google APIগুলি অ্যাক্সেস করতে OAuth 2.0 ব্যবহার করে এমন যেকোনো অ্যাপ্লিকেশনের অনুমোদনের শংসাপত্র থাকতে হবে যা Google-এর OAuth 2.0 সার্ভারে অ্যাপ্লিকেশনটিকে সনাক্ত করে৷ নিম্নলিখিত ধাপগুলি ব্যাখ্যা করে কিভাবে আপনার প্রকল্পের জন্য শংসাপত্র তৈরি করতে হয়। আপনার অ্যাপ্লিকেশনগুলি তারপরে সেই প্রকল্পের জন্য সক্ষম করা APIগুলি অ্যাক্সেস করতে শংসাপত্রগুলি ব্যবহার করতে পারে৷

  1. Go to the Credentials page.
  2. ক্রেডেনশিয়াল তৈরি করুন > OAuth ক্লায়েন্ট আইডি ক্লিক করুন।
  3. ওয়েব অ্যাপ্লিকেশন অ্যাপ্লিকেশন প্রকার নির্বাচন করুন.
  4. ফর্মটি পূরণ করুন এবং তৈরি করুন ক্লিক করুন। PHP, Java, Python, Ruby, এবং .NET এর মত ভাষা এবং ফ্রেমওয়ার্ক ব্যবহার করে এমন অ্যাপ্লিকেশনগুলিকে অবশ্যই অনুমোদিত রিডাইরেক্ট URI উল্লেখ করতে হবে। রিডাইরেক্ট ইউআরআই হল শেষ পয়েন্ট যেখানে OAuth 2.0 সার্ভার প্রতিক্রিয়া পাঠাতে পারে। এই শেষ পয়েন্টগুলি অবশ্যই Google-এর বৈধতা নিয়ম মেনে চলতে হবে৷

    পরীক্ষার জন্য, আপনি URI উল্লেখ করতে পারেন যা স্থানীয় মেশিনে উল্লেখ করে, যেমন http://localhost:8080 । এটি মনে রেখে, অনুগ্রহ করে মনে রাখবেন যে এই নথির সমস্ত উদাহরণ http://localhost:8080 পুনঃনির্দেশ URI হিসাবে ব্যবহার করে।

    আমরা সুপারিশ করি যে আপনি আপনার অ্যাপের প্রমাণীকরণের শেষ পয়েন্টগুলি ডিজাইন করুন যাতে আপনার অ্যাপ্লিকেশনটি পৃষ্ঠার অন্যান্য সংস্থানগুলিতে অনুমোদনের কোডগুলি প্রকাশ না করে৷

আপনার শংসাপত্র তৈরি করার পরে, API Consoleথেকে client_secret.json ফাইলটি ডাউনলোড করুন। ফাইলটিকে নিরাপদে এমন একটি স্থানে সংরক্ষণ করুন যেখানে শুধুমাত্র আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে।

অ্যাক্সেস স্কোপ সনাক্ত করুন

স্কোপগুলি আপনার অ্যাপ্লিকেশনটিকে শুধুমাত্র প্রয়োজনীয় সংস্থানগুলিতে অ্যাক্সেসের অনুরোধ করতে সক্ষম করে এবং ব্যবহারকারীদের তারা আপনার অ্যাপ্লিকেশনটিতে যে পরিমাণ অ্যাক্সেস দেয় তা নিয়ন্ত্রণ করতে সক্ষম করে। সুতরাং, অনুরোধ করা স্কোপের সংখ্যা এবং ব্যবহারকারীর সম্মতি পাওয়ার সম্ভাবনার মধ্যে একটি বিপরীত সম্পর্ক থাকতে পারে।

আপনি OAuth 2.0 অনুমোদন কার্যকর করা শুরু করার আগে, আমরা সুপারিশ করি যে আপনি সেই সুযোগগুলি সনাক্ত করুন যেগুলি অ্যাক্সেস করার জন্য আপনার অ্যাপের অনুমতির প্রয়োজন হবে৷

আমরা এটিও সুপারিশ করি যে আপনার অ্যাপ্লিকেশন একটি ক্রমবর্ধমান অনুমোদন প্রক্রিয়ার মাধ্যমে অনুমোদনের সুযোগে অ্যাক্সেসের অনুরোধ করুন, যেখানে আপনার অ্যাপ্লিকেশন প্রসঙ্গে ব্যবহারকারীর ডেটা অ্যাক্সেসের অনুরোধ করে। এই সর্বোত্তম অনুশীলন ব্যবহারকারীদের আরও সহজে বুঝতে সাহায্য করে যে কেন আপনার অ্যাপ্লিকেশানটি অনুরোধ করছে তার অ্যাক্সেসের প্রয়োজন৷

OAuth 2.0 API স্কোপ নথিতে স্কোপের একটি সম্পূর্ণ তালিকা রয়েছে যা আপনি Google API অ্যাক্সেস করতে ব্যবহার করতে পারেন।

ভাষা-নির্দিষ্ট প্রয়োজনীয়তা

এই নথিতে কোডের যেকোন নমুনা চালানোর জন্য, আপনার একটি Google অ্যাকাউন্ট, ইন্টারনেট অ্যাক্সেস এবং একটি ওয়েব ব্রাউজার প্রয়োজন। আপনি যদি API ক্লায়েন্ট লাইব্রেরিগুলির একটি ব্যবহার করেন তবে নীচের ভাষা-নির্দিষ্ট প্রয়োজনীয়তাগুলিও দেখুন৷

পিএইচপি

এই নথিতে পিএইচপি কোড নমুনা চালানোর জন্য, আপনার প্রয়োজন হবে:

  • কমান্ড-লাইন ইন্টারফেস (CLI) এবং JSON এক্সটেনশন ইনস্টল সহ PHP 5.6 বা তার বেশি।
  • কম্পোজার নির্ভরতা ব্যবস্থাপনা টুল।
  • PHP-এর জন্য Google APIs ক্লায়েন্ট লাইব্রেরি:

    composer require google/apiclient:^2.10

পাইথন

এই নথিতে পাইথন কোড নমুনা চালানোর জন্য, আপনার প্রয়োজন হবে:

  • পাইথন 2.6 বা তার বেশি
  • পাইপ প্যাকেজ ম্যানেজমেন্ট টুল।
  • পাইথনের জন্য Google APIs ক্লায়েন্ট লাইব্রেরি:
    pip install --upgrade google-api-python-client
  • ব্যবহারকারীর অনুমোদনের জন্য google-auth , google-auth-oauthlib এবং google-auth-httplib2
    pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
  • ফ্লাস্ক পাইথন ওয়েব অ্যাপ্লিকেশন ফ্রেমওয়ার্ক।
    pip install --upgrade flask
  • requests HTTP লাইব্রেরি.
    pip install --upgrade requests

রুবি

এই নথিতে রুবি কোড নমুনা চালানোর জন্য, আপনার প্রয়োজন হবে:

  • রুবি 2.2.2 বা তার বেশি
  • রুবির জন্য Google APIs ক্লায়েন্ট লাইব্রেরি:

    gem install google-api-client
  • সিনাট্রা রুবি ওয়েব অ্যাপ্লিকেশন ফ্রেমওয়ার্ক।

    gem install sinatra

Node.js

এই নথিতে Node.js কোড নমুনা চালানোর জন্য, আপনার প্রয়োজন হবে:

  • রক্ষণাবেক্ষণ এলটিএস, সক্রিয় এলটিএস, বা Node.js-এর বর্তমান প্রকাশ।
  • Google APIs Node.js ক্লায়েন্ট:

    npm install googleapis

HTTP/REST

OAuth 2.0 এন্ডপয়েন্টে সরাসরি কল করতে আপনাকে কোনো লাইব্রেরি ইনস্টল করার দরকার নেই।

OAuth 2.0 অ্যাক্সেস টোকেন প্রাপ্ত করা

নিম্নলিখিত পদক্ষেপগুলি দেখায় যে কীভাবে আপনার অ্যাপ্লিকেশনটি Google-এর OAuth 2.0 সার্ভারের সাথে ইন্টারঅ্যাক্ট করে ব্যবহারকারীর পক্ষে একটি API অনুরোধ সম্পাদন করার জন্য ব্যবহারকারীর সম্মতি পেতে৷ ব্যবহারকারীর অনুমোদনের প্রয়োজন এমন একটি Google API অনুরোধ কার্যকর করার আগে আপনার আবেদনের সেই সম্মতি থাকতে হবে।

নীচের তালিকাটি দ্রুত এই পদক্ষেপগুলিকে সংক্ষিপ্ত করে:

  1. আপনার অ্যাপ্লিকেশনটি প্রয়োজনীয় অনুমতিগুলি সনাক্ত করে৷
  2. আপনার অ্যাপ্লিকেশন ব্যবহারকারীকে অনুরোধ করা অনুমতিগুলির তালিকা সহ Google-এ পুনঃনির্দেশ করে৷
  3. ব্যবহারকারী আপনার আবেদনের অনুমতি প্রদান করবেন কিনা তা সিদ্ধান্ত নেয়।
  4. আপনার অ্যাপ্লিকেশন ব্যবহারকারী কি সিদ্ধান্ত নিয়েছে খুঁজে বের করে.
  5. ব্যবহারকারী অনুরোধকৃত অনুমতি প্রদান করলে, আপনার অ্যাপ্লিকেশন ব্যবহারকারীর পক্ষ থেকে API অনুরোধ করার জন্য প্রয়োজনীয় টোকেন পুনরুদ্ধার করে।

ধাপ 1: অনুমোদনের পরামিতি সেট করুন

আপনার প্রথম ধাপ হল অনুমোদনের অনুরোধ তৈরি করা। এই অনুরোধটি এমন প্যারামিটার সেট করে যা আপনার অ্যাপ্লিকেশনকে শনাক্ত করে এবং ব্যবহারকারীকে আপনার আবেদনে মঞ্জুর করতে বলা হবে এমন অনুমতিগুলিকে সংজ্ঞায়িত করে৷

  • আপনি যদি OAuth 2.0 প্রমাণীকরণ এবং অনুমোদনের জন্য একটি Google ক্লায়েন্ট লাইব্রেরি ব্যবহার করেন, আপনি একটি বস্তু তৈরি এবং কনফিগার করেন যা এই পরামিতিগুলিকে সংজ্ঞায়িত করে৷
  • আপনি যদি সরাসরি Google OAuth 2.0 এন্ডপয়েন্টে কল করেন, তাহলে আপনি একটি URL তৈরি করবেন এবং সেই URL-এ প্যারামিটার সেট করবেন।

নীচের ট্যাবগুলি ওয়েব সার্ভার অ্যাপ্লিকেশনগুলির জন্য সমর্থিত অনুমোদনের পরামিতিগুলিকে সংজ্ঞায়িত করে৷ ভাষা-নির্দিষ্ট উদাহরণগুলিও দেখায় যে কীভাবে একটি ক্লায়েন্ট লাইব্রেরি বা অনুমোদন লাইব্রেরি ব্যবহার করতে হয় এমন একটি বস্তু কনফিগার করতে যা সেই প্যারামিটারগুলি সেট করে।

পিএইচপি

নীচের কোড স্নিপেটটি একটি Google\Client() অবজেক্ট তৈরি করে, যা অনুমোদনের অনুরোধে পরামিতিগুলিকে সংজ্ঞায়িত করে।

সেই বস্তুটি আপনার অ্যাপ্লিকেশন সনাক্ত করতে আপনার client_secret.json ফাইল থেকে তথ্য ব্যবহার করে। (সেই ফাইলটি সম্পর্কে আরও তথ্যের জন্য অনুমোদনের শংসাপত্র তৈরি করা দেখুন।) বস্তুটি সেই সুযোগগুলিকেও চিহ্নিত করে যা আপনার অ্যাপ্লিকেশন অ্যাক্সেসের অনুমতির জন্য অনুরোধ করছে এবং আপনার অ্যাপ্লিকেশনের প্রমাণীকরণের শেষ পয়েন্টের URL, যা Google এর OAuth 2.0 সার্ভার থেকে প্রতিক্রিয়া পরিচালনা করবে। অবশেষে, কোড ঐচ্ছিক access_type এবং include_granted_scopes প্যারামিটার সেট করে।

উদাহরণস্বরূপ, এই কোডটি একজন ব্যবহারকারীর Google ড্রাইভে শুধুমাত্র-পঠন, অফলাইন অ্যাক্সেসের অনুরোধ করে:

$client = new Google\Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt('consent');
$client->setIncludeGrantedScopes(true);   // incremental auth

অনুরোধ নিম্নলিখিত তথ্য নির্দিষ্ট করে:

পরামিতি
client_id প্রয়োজন

আপনার আবেদনের জন্য ক্লায়েন্ট আইডি। আপনি API ConsoleCredentials pageএ এই মানটি খুঁজে পেতে পারেন।

PHP-এ, একটি client_secret.json ফাইল থেকে অনুমোদনের শংসাপত্র লোড করতে setAuthConfig ফাংশনকে কল করুন।

$client = new Google\Client();
$client->setAuthConfig('client_secret.json');
redirect_uri প্রয়োজন

ব্যবহারকারী অনুমোদন প্রবাহ সম্পূর্ণ করার পরে API সার্ভার ব্যবহারকারীকে কোথায় রিডাইরেক্ট করে তা নির্ধারণ করে। মানটি অবশ্যই OAuth 2.0 ক্লায়েন্টের জন্য অনুমোদিত রিডাইরেক্ট ইউআরআইগুলির একটির সাথে মেলে, যা আপনি আপনার ক্লায়েন্টের API ConsoleCredentials pageএ কনফিগার করেছেন। যদি এই মানটি প্রদত্ত client_id জন্য একটি অনুমোদিত পুনঃনির্দেশ URI-এর সাথে মেলে না তাহলে আপনি একটি redirect_uri_mismatch ত্রুটি পাবেন।

মনে রাখবেন যে http বা https স্কিম, কেস এবং ট্রেইলিং স্ল্যাশ (' / ') অবশ্যই মিলবে।

PHP-তে এই মান সেট করতে, setRedirectUri ফাংশনটি কল করুন। মনে রাখবেন যে আপনাকে অবশ্যই প্রদত্ত client_id এর জন্য একটি বৈধ পুনঃনির্দেশ URI উল্লেখ করতে হবে।

$client->setRedirectUri('https://oauth2.example.com/code');
scope প্রয়োজন

স্কোপের একটি স্থান-সীমাবদ্ধ তালিকা যা ব্যবহারকারীর পক্ষ থেকে আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে এমন সংস্থানগুলি সনাক্ত করে৷ এই মানগুলি সম্মতি স্ক্রীনকে জানায় যা Google ব্যবহারকারীকে প্রদর্শন করে।

স্কোপগুলি আপনার অ্যাপ্লিকেশনটিকে শুধুমাত্র প্রয়োজনীয় সংস্থানগুলিতে অ্যাক্সেসের অনুরোধ করতে সক্ষম করে এবং ব্যবহারকারীদের তারা আপনার অ্যাপ্লিকেশনটিতে যে পরিমাণ অ্যাক্সেস দেয় তা নিয়ন্ত্রণ করতে সক্ষম করে। সুতরাং, অনুরোধ করা স্কোপের সংখ্যা এবং ব্যবহারকারীর সম্মতি পাওয়ার সম্ভাবনার মধ্যে একটি বিপরীত সম্পর্ক রয়েছে।

PHP-তে এই মান সেট করতে, addScope ফাংশনটি কল করুন:

$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

আমরা সুপারিশ করি যে যখনই সম্ভব প্রেক্ষাপটে অনুমোদনের সুযোগে অ্যাক্সেসের জন্য আপনার আবেদন অনুরোধ। প্রেক্ষাপটে ব্যবহারকারীর ডেটাতে অ্যাক্সেসের অনুরোধ করে, ক্রমবর্ধমান অনুমোদনের মাধ্যমে, আপনি ব্যবহারকারীদের আরও সহজে বুঝতে সাহায্য করেন যে কেন আপনার অ্যাপ্লিকেশানটি অনুরোধ করছে সেই অ্যাক্সেসের প্রয়োজন৷

access_type প্রস্তাবিত

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশন অ্যাক্সেস টোকেন রিফ্রেশ করতে পারে কিনা তা নির্দেশ করে৷ বৈধ প্যারামিটার মানগুলি online , যা ডিফল্ট মান এবং offline

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশনটির অ্যাক্সেস টোকেন রিফ্রেশ করার প্রয়োজন হলে offline মান সেট করুন। এই নথিতে পরে বর্ণিত অ্যাক্সেস টোকেন রিফ্রেশ করার পদ্ধতি। এই মানটি Google অনুমোদন সার্ভারকে একটি রিফ্রেশ টোকেন এবং একটি অ্যাক্সেস টোকেন ফেরত দেওয়ার নির্দেশ দেয় যখন আপনার অ্যাপ্লিকেশন টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করে।

PHP-তে এই মান সেট করতে, setAccessType ফাংশনটি কল করুন:

$client->setAccessType('offline');
state প্রস্তাবিত

আপনার অনুমোদনের অনুরোধ এবং অনুমোদন সার্ভারের প্রতিক্রিয়ার মধ্যে অবস্থা বজায় রাখতে আপনার অ্যাপ্লিকেশন ব্যবহার করে এমন কোনো স্ট্রিং মান নির্দিষ্ট করে। ব্যবহারকারী আপনার আবেদনের অ্যাক্সেস অনুরোধে সম্মতি বা অস্বীকার করার পরে সার্ভারটি সঠিক মানটি ফেরত দেয় যা আপনি একটি name=value pair হিসেবে পাঠান redirect_uri এর URL ক্যোয়ারী উপাদান ( ? )।

আপনি এই প্যারামিটারটি বিভিন্ন উদ্দেশ্যে ব্যবহার করতে পারেন, যেমন ব্যবহারকারীকে আপনার অ্যাপ্লিকেশনের সঠিক সংস্থানে নির্দেশ দেওয়া, ননসেস পাঠানো এবং ক্রস-সাইট অনুরোধ জালিয়াতি প্রশমিত করা। যেহেতু আপনার redirect_uri অনুমান করা যেতে পারে, একটি state মান ব্যবহার করে আপনার নিশ্চয়তা বৃদ্ধি করতে পারে যে একটি ইনকামিং সংযোগ একটি প্রমাণীকরণ অনুরোধের ফলাফল। আপনি যদি একটি এলোমেলো স্ট্রিং তৈরি করেন বা একটি কুকির হ্যাশ বা ক্লায়েন্টের অবস্থা ক্যাপচার করে এমন অন্য মান এনকোড করেন, তাহলে ক্রস-সাইটের মতো আক্রমণের বিরুদ্ধে সুরক্ষা প্রদান করে অনুরোধ এবং প্রতিক্রিয়া একই ব্রাউজারে উদ্ভূত হয়েছে তা নিশ্চিত করতে আপনি প্রতিক্রিয়া যাচাই করতে পারেন জালিয়াতি অনুরোধ কিভাবে একটি state টোকেন তৈরি এবং নিশ্চিত করতে হয় তার উদাহরণের জন্য OpenID Connect ডকুমেন্টেশন দেখুন।

পিএইচপি-তে এই মান সেট করতে, setState ফাংশনটি কল করুন:

$client->setState($sample_passthrough_value);
include_granted_scopes ঐচ্ছিক

প্রেক্ষাপটে অতিরিক্ত সুযোগে অ্যাক্সেসের অনুরোধ করতে ক্রমবর্ধমান অনুমোদন ব্যবহার করতে অ্যাপ্লিকেশনগুলিকে সক্ষম করে৷ আপনি যদি এই প্যারামিটারের মানটিকে true হিসাবে সেট করেন এবং অনুমোদনের অনুরোধটি মঞ্জুর করা হয়, তাহলে নতুন অ্যাক্সেস টোকেনটি এমন কোনো স্কোপকেও কভার করবে যেখানে ব্যবহারকারী পূর্বে অ্যাপ্লিকেশন অ্যাক্সেস মঞ্জুর করেছেন। উদাহরণের জন্য ক্রমবর্ধমান অনুমোদন বিভাগ দেখুন।

PHP-তে এই মান সেট করতে, setIncludeGrantedScopes ফাংশনটি কল করুন:

$client->setIncludeGrantedScopes(true);
login_hint ঐচ্ছিক

আপনার অ্যাপ্লিকেশন যদি জানে কোন ব্যবহারকারী প্রমাণীকরণের চেষ্টা করছে, তাহলে এটি এই প্যারামিটারটি ব্যবহার করে Google প্রমাণীকরণ সার্ভারে একটি ইঙ্গিত দিতে পারে। সার্ভার সাইন-ইন ফর্মে ইমেল ক্ষেত্রটি প্রিফিলিং করে বা উপযুক্ত মাল্টি-লগইন সেশন নির্বাচন করে লগইন প্রবাহকে সহজ করার জন্য ইঙ্গিতটি ব্যবহার করে।

প্যারামিটার মানটিকে একটি ইমেল ঠিকানা বা sub শনাক্তকারীতে সেট করুন, যা ব্যবহারকারীর Google আইডির সমতুল্য।

PHP-তে এই মান সেট করতে, setLoginHint ফাংশনটি কল করুন:

$client->setLoginHint('None');
prompt ঐচ্ছিক

ব্যবহারকারীকে উপস্থাপন করার জন্য প্রম্পটের একটি স্থান-বিভাজিত, কেস-সংবেদনশীল তালিকা। আপনি যদি এই প্যারামিটারটি নির্দিষ্ট না করেন, তাহলে ব্যবহারকারীকে শুধুমাত্র প্রথমবার আপনার প্রকল্প অ্যাক্সেসের অনুরোধ জানানো হবে। আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

PHP-তে এই মান সেট করতে, setApprovalPrompt ফাংশনটি কল করুন:

$client->setApprovalPrompt('consent');

সম্ভাব্য মান হল:

none কোনো প্রমাণীকরণ বা সম্মতি স্ক্রীন প্রদর্শন করবেন না। অন্যান্য মানের সাথে নির্দিষ্ট করা উচিত নয়।
consent ব্যবহারকারীকে সম্মতির জন্য অনুরোধ করুন।
select_account ব্যবহারকারীকে একটি অ্যাকাউন্ট নির্বাচন করতে অনুরোধ করুন।

পাইথন

নিম্নলিখিত কোড স্নিপেট অনুমোদনের অনুরোধ তৈরি করতে google-auth-oauthlib.flow মডিউল ব্যবহার করে।

কোডটি একটি Flow অবজেক্ট তৈরি করে, যা আপনার অনুমোদনের শংসাপত্র তৈরি করার পরে ডাউনলোড করা client_secret.json ফাইল থেকে তথ্য ব্যবহার করে আপনার অ্যাপ্লিকেশনটিকে সনাক্ত করে। সেই অবজেক্টটি সেই স্কোপগুলিকেও শনাক্ত করে যা আপনার অ্যাপ্লিকেশন অ্যাক্সেসের অনুমতির জন্য অনুরোধ করছে এবং আপনার অ্যাপ্লিকেশনের প্রমাণীকরণের শেষ পয়েন্টের URL, যা Google এর OAuth 2.0 সার্ভার থেকে প্রতিক্রিয়া পরিচালনা করবে। অবশেষে, কোড ঐচ্ছিক access_type এবং include_granted_scopes প্যারামিটার সেট করে।

উদাহরণস্বরূপ, এই কোডটি একজন ব্যবহারকারীর Google ড্রাইভে শুধুমাত্র-পঠন, অফলাইন অ্যাক্সেসের অনুরোধ করে:

import google.oauth2.credentials
import google_auth_oauthlib.flow

# Use the client_secret.json file to identify the application requesting
# authorization. The client ID (from that file) and access scopes are required.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])

# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value must exactly
# match one of the authorized redirect URIs for the OAuth 2.0 client, which you
# configured in the API Console. If this value doesn't match an authorized URI,
# you will get a 'redirect_uri_mismatch' error.
flow.redirect_uri = 'https://www.example.com/oauth2callback'

# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
    # Enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type='offline',
    # Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes='true')

অনুরোধ নিম্নলিখিত তথ্য নির্দিষ্ট করে:

পরামিতি
client_id প্রয়োজন

আপনার আবেদনের জন্য ক্লায়েন্ট আইডি। আপনি এই মানটি API ConsoleCredentials pageএ খুঁজে পেতে পারেন।

পাইথনে, একটি client_secret.json ফাইল থেকে ক্লায়েন্ট আইডি পুনরুদ্ধার করতে from_client_secrets_file পদ্ধতিতে কল করুন। (আপনি from_client_config পদ্ধতিটিও ব্যবহার করতে পারেন, যা ক্লায়েন্ট কনফিগারেশনটি পাস করে কারণ এটি মূলত একটি ক্লায়েন্ট সিক্রেট ফাইলে উপস্থিত হয়েছিল কিন্তু ফাইলটি নিজেই অ্যাক্সেস করে না।)

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])
redirect_uri প্রয়োজন

ব্যবহারকারী অনুমোদন প্রবাহ সম্পূর্ণ করার পরে API সার্ভার ব্যবহারকারীকে কোথায় রিডাইরেক্ট করে তা নির্ধারণ করে। মানটি অবশ্যই OAuth 2.0 ক্লায়েন্টের জন্য অনুমোদিত রিডাইরেক্ট ইউআরআইগুলির একটির সাথে মেলে, যা আপনি আপনার ক্লায়েন্টের API ConsoleCredentials pageএ কনফিগার করেছেন। যদি এই মানটি প্রদত্ত client_id জন্য একটি অনুমোদিত পুনঃনির্দেশ URI-এর সাথে মেলে না তাহলে আপনি একটি redirect_uri_mismatch ত্রুটি পাবেন।

মনে রাখবেন যে http বা https স্কিম, কেস এবং ট্রেইলিং স্ল্যাশ (' / ') অবশ্যই মিলবে।

পাইথনে এই মান সেট করতে, flow অবজেক্টের redirect_uri বৈশিষ্ট্য সেট করুন:

flow.redirect_uri = 'https://oauth2.example.com/code'
scope প্রয়োজন

স্কোপের একটি তালিকা যা ব্যবহারকারীর পক্ষে আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে এমন সংস্থানগুলি সনাক্ত করে৷ এই মানগুলি সম্মতি স্ক্রীনকে জানায় যা Google ব্যবহারকারীকে প্রদর্শন করে।

স্কোপগুলি আপনার অ্যাপ্লিকেশনটিকে শুধুমাত্র প্রয়োজনীয় সংস্থানগুলিতে অ্যাক্সেসের অনুরোধ করতে সক্ষম করে এবং ব্যবহারকারীদের তারা আপনার অ্যাপ্লিকেশনটিতে যে পরিমাণ অ্যাক্সেস দেয় তা নিয়ন্ত্রণ করতে সক্ষম করে। সুতরাং, অনুরোধ করা স্কোপের সংখ্যা এবং ব্যবহারকারীর সম্মতি পাওয়ার সম্ভাবনার মধ্যে একটি বিপরীত সম্পর্ক রয়েছে।

পাইথনে, স্কোপের তালিকা নির্দিষ্ট করতে client_id সেট করতে আপনি যে পদ্ধতি ব্যবহার করেন তা ব্যবহার করুন।

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])

আমরা সুপারিশ করি যে যখনই সম্ভব প্রেক্ষাপটে অনুমোদনের সুযোগে অ্যাক্সেসের জন্য আপনার আবেদন অনুরোধ। প্রেক্ষাপটে ব্যবহারকারীর ডেটাতে অ্যাক্সেসের অনুরোধ করে, ক্রমবর্ধমান অনুমোদনের মাধ্যমে, আপনি ব্যবহারকারীদের আরও সহজে বুঝতে সাহায্য করেন যে কেন আপনার অ্যাপ্লিকেশানটি অনুরোধ করছে সেই অ্যাক্সেসের প্রয়োজন৷

access_type প্রস্তাবিত

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশন অ্যাক্সেস টোকেন রিফ্রেশ করতে পারে কিনা তা নির্দেশ করে৷ বৈধ প্যারামিটার মানগুলি online , যা ডিফল্ট মান এবং offline

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশনটির অ্যাক্সেস টোকেন রিফ্রেশ করার প্রয়োজন হলে offline মান সেট করুন। এই নথিতে পরে বর্ণিত অ্যাক্সেস টোকেন রিফ্রেশ করার পদ্ধতি। এই মানটি Google অনুমোদন সার্ভারকে একটি রিফ্রেশ টোকেন এবং একটি অ্যাক্সেস টোকেন ফেরত দেওয়ার নির্দেশ দেয় যখন আপনার অ্যাপ্লিকেশন টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করে।

পাইথনে, flow.authorization_url পদ্ধতিতে কল করার সময় একটি কীওয়ার্ড আর্গুমেন্ট হিসাবে access_type নির্দিষ্ট করে access_type প্যারামিটার সেট করুন:

authorization_url, state = flow.authorization_url(
    access_type='offline',
    include_granted_scopes='true')
state প্রস্তাবিত

আপনার অনুমোদনের অনুরোধ এবং অনুমোদন সার্ভারের প্রতিক্রিয়ার মধ্যে অবস্থা বজায় রাখতে আপনার অ্যাপ্লিকেশন ব্যবহার করে এমন কোনো স্ট্রিং মান নির্দিষ্ট করে। ব্যবহারকারী আপনার আবেদনের অ্যাক্সেস অনুরোধে সম্মতি বা অস্বীকার করার পরে সার্ভারটি সঠিক মানটি ফেরত দেয় যা আপনি একটি name=value pair হিসেবে পাঠান redirect_uri এর URL ক্যোয়ারী উপাদান ( ? )।

আপনি এই প্যারামিটারটি বিভিন্ন উদ্দেশ্যে ব্যবহার করতে পারেন, যেমন ব্যবহারকারীকে আপনার অ্যাপ্লিকেশনের সঠিক সংস্থানে নির্দেশ দেওয়া, ননসেস পাঠানো এবং ক্রস-সাইট অনুরোধ জালিয়াতি প্রশমিত করা। যেহেতু আপনার redirect_uri অনুমান করা যেতে পারে, একটি state মান ব্যবহার করে আপনার নিশ্চয়তা বৃদ্ধি করতে পারে যে একটি ইনকামিং সংযোগ একটি প্রমাণীকরণ অনুরোধের ফলাফল। আপনি যদি একটি এলোমেলো স্ট্রিং তৈরি করেন বা একটি কুকির হ্যাশ বা ক্লায়েন্টের অবস্থা ক্যাপচার করে এমন অন্য মান এনকোড করেন, তাহলে ক্রস-সাইটের মতো আক্রমণের বিরুদ্ধে সুরক্ষা প্রদান করে অনুরোধ এবং প্রতিক্রিয়া একই ব্রাউজারে উদ্ভূত হয়েছে তা নিশ্চিত করতে আপনি প্রতিক্রিয়া যাচাই করতে পারেন জালিয়াতি অনুরোধ কিভাবে একটি state টোকেন তৈরি এবং নিশ্চিত করতে হয় তার উদাহরণের জন্য OpenID Connect ডকুমেন্টেশন দেখুন।

Python-এ, flow.authorization_url পদ্ধতিতে কল করার সময় একটি কীওয়ার্ড আর্গুমেন্ট হিসাবে state নির্দিষ্ট করে state প্যারামিটার সেট করুন:

authorization_url, state = flow.authorization_url(
    access_type='offline',
    state=sample_passthrough_value,
    include_granted_scopes='true')
include_granted_scopes ঐচ্ছিক

প্রেক্ষাপটে অতিরিক্ত সুযোগে অ্যাক্সেসের অনুরোধ করতে ক্রমবর্ধমান অনুমোদন ব্যবহার করতে অ্যাপ্লিকেশনগুলিকে সক্ষম করে৷ আপনি যদি এই প্যারামিটারের মানটিকে true হিসাবে সেট করেন এবং অনুমোদনের অনুরোধটি মঞ্জুর করা হয়, তাহলে নতুন অ্যাক্সেস টোকেনটি এমন কোনো স্কোপকেও কভার করবে যেখানে ব্যবহারকারী পূর্বে অ্যাপ্লিকেশন অ্যাক্সেস মঞ্জুর করেছেন। উদাহরণের জন্য ক্রমবর্ধমান অনুমোদন বিভাগ দেখুন।

পাইথনে, flow.authorization_url পদ্ধতিতে কল করার সময় include_granted_scopes কীওয়ার্ড আর্গুমেন্ট হিসেবে উল্লেখ করে include_granted_scopes প্যারামিটার সেট করুন:

authorization_url, state = flow.authorization_url(
    access_type='offline',
    include_granted_scopes='true')
login_hint ঐচ্ছিক

আপনার অ্যাপ্লিকেশন যদি জানে কোন ব্যবহারকারী প্রমাণীকরণের চেষ্টা করছে, তাহলে এটি এই প্যারামিটারটি ব্যবহার করে Google প্রমাণীকরণ সার্ভারে একটি ইঙ্গিত দিতে পারে। সার্ভার সাইন-ইন ফর্মে ইমেল ক্ষেত্রটি প্রিফিলিং করে বা উপযুক্ত মাল্টি-লগইন সেশন নির্বাচন করে লগইন প্রবাহকে সহজ করার জন্য ইঙ্গিতটি ব্যবহার করে।

প্যারামিটার মানটিকে একটি ইমেল ঠিকানা বা sub শনাক্তকারীতে সেট করুন, যা ব্যবহারকারীর Google আইডির সমতুল্য।

পাইথনে, flow.authorization_url পদ্ধতিতে কল করার সময় login_hint একটি কীওয়ার্ড আর্গুমেন্ট হিসাবে নির্দিষ্ট করে login_hint প্যারামিটার সেট করুন:

authorization_url, state = flow.authorization_url(
    access_type='offline',
    login_hint='None',
    include_granted_scopes='true')
prompt ঐচ্ছিক

ব্যবহারকারীকে উপস্থাপন করার জন্য প্রম্পটের একটি স্থান-বিভাজিত, কেস-সংবেদনশীল তালিকা। আপনি যদি এই প্যারামিটারটি নির্দিষ্ট না করেন, তাহলে ব্যবহারকারীকে শুধুমাত্র প্রথমবার আপনার প্রকল্প অ্যাক্সেসের অনুরোধ জানানো হবে। আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

পাইথনে, flow.authorization_url পদ্ধতিতে কল করার সময় একটি কীওয়ার্ড আর্গুমেন্ট হিসাবে prompt নির্দিষ্ট করে prompt প্যারামিটার সেট করুন:

authorization_url, state = flow.authorization_url(
      access_type='offline',
      prompt='consent',
      include_granted_scopes='true')

সম্ভাব্য মান হল:

none কোনো প্রমাণীকরণ বা সম্মতি স্ক্রীন প্রদর্শন করবেন না। অন্যান্য মানের সাথে নির্দিষ্ট করা উচিত নয়।
consent ব্যবহারকারীকে সম্মতির জন্য অনুরোধ করুন।
select_account ব্যবহারকারীকে একটি অ্যাকাউন্ট নির্বাচন করতে অনুরোধ করুন।

রুবি

আপনার অ্যাপ্লিকেশনে একটি ক্লায়েন্ট অবজেক্ট কনফিগার করতে আপনার তৈরি করা client_secrets.json ফাইলটি ব্যবহার করুন। আপনি যখন একটি ক্লায়েন্ট অবজেক্ট কনফিগার করেন, তখন আপনি আপনার অ্যাপ্লিকেশনের প্রমাণীকরণ এন্ডপয়েন্টের URL সহ আপনার অ্যাপ্লিকেশনের অ্যাক্সেস করার জন্য প্রয়োজনীয় সুযোগগুলি নির্দিষ্ট করেন, যা OAuth 2.0 সার্ভার থেকে প্রতিক্রিয়া পরিচালনা করবে।

উদাহরণস্বরূপ, এই কোডটি একজন ব্যবহারকারীর Google ড্রাইভে শুধুমাত্র-পঠন, অফলাইন অ্যাক্সেসের অনুরোধ করে:

require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'

client_secrets = Google::APIClient::ClientSecrets.load
auth_client = client_secrets.to_authorization
auth_client.update!(
  :scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
  :redirect_uri => 'http://www.example.com/oauth2callback',
  :additional_parameters => {
    "access_type" => "offline",         # offline access
    "include_granted_scopes" => "true"  # incremental auth
  }
)

আপনার অ্যাপ্লিকেশনটি OAuth 2.0 ক্রিয়াকলাপ সম্পাদন করতে ক্লায়েন্ট অবজেক্ট ব্যবহার করে, যেমন অনুমোদনের অনুরোধ URL তৈরি করা এবং HTTP অনুরোধগুলিতে অ্যাক্সেস টোকেন প্রয়োগ করা।

Node.js

নীচের কোড স্নিপেট একটি google.auth.OAuth2 অবজেক্ট তৈরি করে, যা অনুমোদনের অনুরোধে পরামিতিগুলিকে সংজ্ঞায়িত করে৷

সেই বস্তুটি আপনার অ্যাপ্লিকেশন সনাক্ত করতে আপনার client_secret.json ফাইল থেকে তথ্য ব্যবহার করে। একটি অ্যাক্সেস টোকেন পুনরুদ্ধার করার জন্য একটি ব্যবহারকারীর কাছ থেকে অনুমতি চাইতে, আপনি তাদের একটি সম্মতি পৃষ্ঠায় পুনঃনির্দেশিত করুন। একটি সম্মতি পৃষ্ঠার URL তৈরি করতে:

const {google} = require('googleapis');

/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
 * from the client_secret.json file. To get these credentials for your application, visit
 * https://console.cloud.google.com/apis/credentials.
 */
const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// Access scopes for read-only Drive activity.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly'
];

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',
  /** Pass in the scopes array defined above.
    * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
  scope: scopes,
  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true
});

গুরুত্বপূর্ণ দ্রষ্টব্য - refresh_token শুধুমাত্র প্রথম অনুমোদনে ফেরত দেওয়া হয়। এখানে আরো বিস্তারিত.

HTTP/REST

Google-এর OAuth 2.0 এন্ডপয়েন্ট https://accounts.google.com/o/oauth2/v2/auth এ রয়েছে। এই এন্ডপয়েন্ট শুধুমাত্র HTTPS এর মাধ্যমে অ্যাক্সেসযোগ্য। সরল HTTP সংযোগ প্রত্যাখ্যান করা হয়.

Google অনুমোদন সার্ভার ওয়েব সার্ভার অ্যাপ্লিকেশনের জন্য নিম্নলিখিত ক্যোয়ারী স্ট্রিং পরামিতি সমর্থন করে:

পরামিতি
client_id প্রয়োজন

আপনার আবেদনের জন্য ক্লায়েন্ট আইডি। আপনি API ConsoleCredentials pageএ এই মানটি খুঁজে পেতে পারেন।

redirect_uri প্রয়োজন

ব্যবহারকারী অনুমোদন প্রবাহ সম্পূর্ণ করার পরে API সার্ভার ব্যবহারকারীকে কোথায় রিডাইরেক্ট করে তা নির্ধারণ করে। মানটি অবশ্যই OAuth 2.0 ক্লায়েন্টের জন্য অনুমোদিত রিডাইরেক্ট ইউআরআইগুলির একটির সাথে মেলে, যা আপনি আপনার ক্লায়েন্টের API ConsoleCredentials pageএ কনফিগার করেছেন। যদি এই মানটি প্রদত্ত client_id জন্য একটি অনুমোদিত পুনঃনির্দেশ URI-এর সাথে মেলে না তাহলে আপনি একটি redirect_uri_mismatch ত্রুটি পাবেন।

মনে রাখবেন যে http বা https স্কিম, কেস এবং ট্রেইলিং স্ল্যাশ (' / ') অবশ্যই মিলবে।

response_type প্রয়োজন

Google OAuth 2.0 এন্ডপয়েন্ট একটি অনুমোদন কোড প্রদান করে কিনা তা নির্ধারণ করে।

ওয়েব সার্ভার অ্যাপ্লিকেশনের জন্য code প্যারামিটার মান সেট করুন।

scope প্রয়োজন

স্কোপের একটি স্থান-সীমাবদ্ধ তালিকা যা ব্যবহারকারীর পক্ষ থেকে আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে এমন সংস্থানগুলি সনাক্ত করে৷ এই মানগুলি সম্মতি স্ক্রীনকে জানায় যা Google ব্যবহারকারীকে প্রদর্শন করে।

স্কোপগুলি আপনার অ্যাপ্লিকেশনটিকে শুধুমাত্র প্রয়োজনীয় সংস্থানগুলিতে অ্যাক্সেসের অনুরোধ করতে সক্ষম করে এবং ব্যবহারকারীদের তারা আপনার অ্যাপ্লিকেশনটিতে যে পরিমাণ অ্যাক্সেস দেয় তা নিয়ন্ত্রণ করতে সক্ষম করে। সুতরাং, অনুরোধ করা স্কোপের সংখ্যা এবং ব্যবহারকারীর সম্মতি পাওয়ার সম্ভাবনার মধ্যে একটি বিপরীত সম্পর্ক রয়েছে।

আমরা সুপারিশ করি যে যখনই সম্ভব প্রেক্ষাপটে অনুমোদনের সুযোগে অ্যাক্সেসের জন্য আপনার আবেদন অনুরোধ। প্রেক্ষাপটে ব্যবহারকারীর ডেটাতে অ্যাক্সেসের অনুরোধ করে, ক্রমবর্ধমান অনুমোদনের মাধ্যমে, আপনি ব্যবহারকারীদের আরও সহজে বুঝতে সাহায্য করেন যে কেন আপনার অ্যাপ্লিকেশানটি অনুরোধ করছে সেই অ্যাক্সেসের প্রয়োজন৷

access_type প্রস্তাবিত

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশন অ্যাক্সেস টোকেন রিফ্রেশ করতে পারে কিনা তা নির্দেশ করে৷ বৈধ প্যারামিটার মানগুলি online , যা ডিফল্ট মান এবং offline

ব্যবহারকারী ব্রাউজারে উপস্থিত না থাকলে আপনার অ্যাপ্লিকেশনটির অ্যাক্সেস টোকেন রিফ্রেশ করার প্রয়োজন হলে offline মান সেট করুন। এই নথিতে পরে বর্ণিত অ্যাক্সেস টোকেন রিফ্রেশ করার পদ্ধতি। এই মানটি Google অনুমোদন সার্ভারকে একটি রিফ্রেশ টোকেন এবং একটি অ্যাক্সেস টোকেন ফেরত দেওয়ার নির্দেশ দেয় যখন আপনার অ্যাপ্লিকেশন টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করে।

state প্রস্তাবিত

আপনার অনুমোদনের অনুরোধ এবং অনুমোদন সার্ভারের প্রতিক্রিয়ার মধ্যে অবস্থা বজায় রাখতে আপনার অ্যাপ্লিকেশন ব্যবহার করে এমন কোনো স্ট্রিং মান নির্দিষ্ট করে। ব্যবহারকারী আপনার আবেদনের অ্যাক্সেস অনুরোধে সম্মতি বা অস্বীকার করার পরে সার্ভারটি সঠিক মানটি ফেরত দেয় যা আপনি একটি name=value pair হিসেবে পাঠান redirect_uri এর URL ক্যোয়ারী উপাদান ( ? )।

আপনি এই প্যারামিটারটি বিভিন্ন উদ্দেশ্যে ব্যবহার করতে পারেন, যেমন ব্যবহারকারীকে আপনার অ্যাপ্লিকেশনের সঠিক সংস্থানে নির্দেশ দেওয়া, ননসেস পাঠানো এবং ক্রস-সাইট অনুরোধ জালিয়াতি প্রশমিত করা। যেহেতু আপনার redirect_uri অনুমান করা যেতে পারে, একটি state মান ব্যবহার করে আপনার নিশ্চয়তা বৃদ্ধি করতে পারে যে একটি ইনকামিং সংযোগ একটি প্রমাণীকরণ অনুরোধের ফলাফল। আপনি যদি একটি এলোমেলো স্ট্রিং তৈরি করেন বা একটি কুকির হ্যাশ বা ক্লায়েন্টের অবস্থা ক্যাপচার করে এমন অন্য মান এনকোড করেন, তাহলে ক্রস-সাইটের মতো আক্রমণের বিরুদ্ধে সুরক্ষা প্রদান করে অনুরোধ এবং প্রতিক্রিয়া একই ব্রাউজারে উদ্ভূত হয়েছে তা নিশ্চিত করতে আপনি প্রতিক্রিয়া যাচাই করতে পারেন জালিয়াতি অনুরোধ কিভাবে একটি state টোকেন তৈরি এবং নিশ্চিত করতে হয় তার উদাহরণের জন্য OpenID Connect ডকুমেন্টেশন দেখুন।

include_granted_scopes ঐচ্ছিক

প্রেক্ষাপটে অতিরিক্ত সুযোগে অ্যাক্সেসের অনুরোধ করতে ক্রমবর্ধমান অনুমোদন ব্যবহার করতে অ্যাপ্লিকেশনগুলিকে সক্ষম করে৷ আপনি যদি এই প্যারামিটারের মানটিকে true হিসাবে সেট করেন এবং অনুমোদনের অনুরোধটি মঞ্জুর করা হয়, তাহলে নতুন অ্যাক্সেস টোকেনটি এমন কোনো স্কোপকেও কভার করবে যেখানে ব্যবহারকারী পূর্বে অ্যাপ্লিকেশন অ্যাক্সেস মঞ্জুর করেছেন। উদাহরণের জন্য ক্রমবর্ধমান অনুমোদন বিভাগ দেখুন।

login_hint ঐচ্ছিক

আপনার অ্যাপ্লিকেশন যদি জানে কোন ব্যবহারকারী প্রমাণীকরণের চেষ্টা করছে, তাহলে এটি এই প্যারামিটারটি ব্যবহার করে Google প্রমাণীকরণ সার্ভারে একটি ইঙ্গিত দিতে পারে। সার্ভার সাইন-ইন ফর্মে ইমেল ক্ষেত্রটি প্রিফিলিং করে বা উপযুক্ত মাল্টি-লগইন সেশন নির্বাচন করে লগইন প্রবাহকে সহজ করার জন্য ইঙ্গিতটি ব্যবহার করে।

প্যারামিটার মানটিকে একটি ইমেল ঠিকানা বা sub শনাক্তকারীতে সেট করুন, যা ব্যবহারকারীর Google আইডির সমতুল্য।

prompt ঐচ্ছিক

ব্যবহারকারীকে উপস্থাপন করার জন্য প্রম্পটের একটি স্থান-বিভাজিত, কেস-সংবেদনশীল তালিকা। আপনি যদি এই প্যারামিটারটি নির্দিষ্ট না করেন, তাহলে ব্যবহারকারীকে শুধুমাত্র প্রথমবার আপনার প্রকল্প অ্যাক্সেসের অনুরোধ জানানো হবে। আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

সম্ভাব্য মান হল:

none কোনো প্রমাণীকরণ বা সম্মতি স্ক্রীন প্রদর্শন করবেন না। অন্যান্য মানের সাথে নির্দিষ্ট করা উচিত নয়।
consent ব্যবহারকারীকে সম্মতির জন্য অনুরোধ করুন।
select_account ব্যবহারকারীকে একটি অ্যাকাউন্ট নির্বাচন করতে অনুরোধ করুন।

ধাপ 2: Google এর OAuth 2.0 সার্ভারে পুনঃনির্দেশ করুন

প্রমাণীকরণ এবং অনুমোদন প্রক্রিয়া শুরু করতে ব্যবহারকারীকে Google এর OAuth 2.0 সার্ভারে পুনঃনির্দেশ করুন৷ সাধারণত, এটি ঘটে যখন আপনার অ্যাপ্লিকেশনটিকে প্রথমে ব্যবহারকারীর ডেটা অ্যাক্সেস করতে হবে৷ ক্রমবর্ধমান অনুমোদনের ক্ষেত্রে, এই পদক্ষেপটি তখনও ঘটে যখন আপনার অ্যাপ্লিকেশনটিকে প্রথমে অতিরিক্ত সংস্থানগুলি অ্যাক্সেস করতে হবে যেগুলি অ্যাক্সেস করার অনুমতি এখনও নেই৷

পিএইচপি

  1. Google এর OAuth 2.0 সার্ভার থেকে অ্যাক্সেসের অনুরোধ করার জন্য একটি URL তৈরি করুন:
    $auth_url = $client->createAuthUrl();
  2. ব্যবহারকারীকে $auth_url এ রিডাইরেক্ট করুন :
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

পাইথন

এই উদাহরণটি দেখায় কিভাবে ব্যবহারকারীকে ফ্লাস্ক ওয়েব অ্যাপ্লিকেশন ফ্রেমওয়ার্ক ব্যবহার করে অনুমোদনের URL-এ পুনঃনির্দেশ করা যায়:

return flask.redirect(authorization_url)

রুবি

  1. Google এর OAuth 2.0 সার্ভার থেকে অ্যাক্সেসের অনুরোধ করার জন্য একটি URL তৈরি করুন:
    auth_uri = auth_client.authorization_uri.to_s
  2. ব্যবহারকারীকে auth_uri এ পুনঃনির্দেশ করুন।

Node.js

  1. Google-এর OAuth 2.0 সার্ভার থেকে অ্যাক্সেসের অনুরোধ করতে ধাপ 1 generateAuthUrl পদ্ধতি থেকে জেনারেট করা URL authorizationUrl ব্যবহার করুন।
  2. ব্যবহারকারীকে authorizationUrl এ পুনঃনির্দেশ করুন।
    res.writeHead(301, { "Location": authorizationUrl });

HTTP/REST

Sample redirect to Google's authorization server

An example URL is shown below, with line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

আপনি অনুরোধ URL তৈরি করার পরে, ব্যবহারকারীকে এটিতে পুনঃনির্দেশ করুন।

Google-এর OAuth 2.0 সার্ভার ব্যবহারকারীকে প্রমাণীকরণ করে এবং অনুরোধ করা স্কোপগুলি অ্যাক্সেস করার জন্য আপনার আবেদনের জন্য ব্যবহারকারীর কাছ থেকে সম্মতি নেয়। আপনার নির্দিষ্ট করা পুনঃনির্দেশ URL ব্যবহার করে প্রতিক্রিয়াটি আপনার অ্যাপ্লিকেশনে ফেরত পাঠানো হয়।

ধাপ 3: Google ব্যবহারকারীকে সম্মতির জন্য অনুরোধ করে

এই ধাপে, ব্যবহারকারী আপনার অ্যাপ্লিকেশনটিকে অনুরোধ করা অ্যাক্সেস মঞ্জুর করবেন কিনা তা সিদ্ধান্ত নেয়। এই পর্যায়ে, Google একটি সম্মতি উইন্ডো প্রদর্শন করে যা আপনার অ্যাপ্লিকেশনের নাম এবং Google API পরিষেবাগুলিকে দেখায় যা ব্যবহারকারীর অনুমোদনের শংসাপত্রের সাথে অ্যাক্সেসের অনুমতির অনুরোধ করছে এবং অ্যাক্সেসের সুযোগের সারসংক্ষেপ। ব্যবহারকারী তারপর আপনার আবেদন দ্বারা অনুরোধ করা এক বা একাধিক স্কোপের অ্যাক্সেস মঞ্জুর করতে বা অনুরোধ প্রত্যাখ্যান করতে সম্মতি দিতে পারেন।

আপনার অ্যাপ্লিকেশনটির এই পর্যায়ে কিছু করার দরকার নেই কারণ এটি Google-এর OAuth 2.0 সার্ভারের প্রতিক্রিয়ার জন্য অপেক্ষা করে যা নির্দেশ করে যে কোনও অ্যাক্সেস দেওয়া হয়েছে কিনা। যে প্রতিক্রিয়া নিম্নলিখিত ধাপে ব্যাখ্যা করা হয়েছে.

ত্রুটি

Google-এর OAuth 2.0 অনুমোদনের এন্ডপয়েন্টের অনুরোধগুলি প্রত্যাশিত প্রমাণীকরণ এবং অনুমোদনের প্রবাহের পরিবর্তে ব্যবহারকারী-মুখী ত্রুটি বার্তাগুলি প্রদর্শন করতে পারে৷ সাধারণ ত্রুটি কোড এবং প্রস্তাবিত রেজোলিউশন নীচে তালিকাভুক্ত করা হয়.

admin_policy_enforced

Google অ্যাকাউন্ট তাদের Google Workspace অ্যাডমিনিস্ট্রেটরের নীতির কারণে অনুরোধ করা এক বা একাধিক স্কোপের অনুমোদন দিতে পারে না। আপনার OAuth ক্লায়েন্ট আইডি-তে স্পষ্টভাবে অ্যাক্সেস না দেওয়া পর্যন্ত অ্যাডমিনিস্ট্রেটর কীভাবে সমস্ত স্কোপ বা সংবেদনশীল এবং সীমাবদ্ধ স্কোপের অ্যাক্সেস সীমাবদ্ধ করতে পারে সে সম্পর্কে আরও তথ্যের জন্য কোন থার্ড-পার্টি এবং অভ্যন্তরীণ অ্যাপগুলি Google Workspace ডেটা অ্যাক্সেস করতে পারে তা নিয়ন্ত্রণ করুন Google Workspace অ্যাডমিন সহায়তা নিবন্ধটি দেখুন।

disallowed_useragent

অনুমোদনের এন্ডপয়েন্টটি Google-এর OAuth 2.0 নীতি দ্বারা অনুমোদিত একটি এমবেডেড ব্যবহারকারী-এজেন্টের ভিতরে প্রদর্শিত হয়৷

অ্যান্ড্রয়েড

android.webkit.WebView এ অনুমোদনের অনুরোধগুলি খোলার সময় Android বিকাশকারীরা এই ত্রুটির বার্তাটির সম্মুখীন হতে পারে৷ বিকাশকারীদের পরিবর্তে Android লাইব্রেরিগুলি ব্যবহার করা উচিত যেমন Android এর জন্য Google সাইন-ইন বা Android এর জন্য OpenID ফাউন্ডেশনের AppAuth

ওয়েব ডেভেলপাররা এই ত্রুটির সম্মুখীন হতে পারে যখন একটি Android অ্যাপ একটি এমবেডেড ইউজার-এজেন্টে একটি সাধারণ ওয়েব লিঙ্ক খোলে এবং একজন ব্যবহারকারী আপনার সাইট থেকে Google-এর OAuth 2.0 অনুমোদনের শেষ পয়েন্টে নেভিগেট করে। বিকাশকারীদের অপারেটিং সিস্টেমের ডিফল্ট লিঙ্ক হ্যান্ডলারে সাধারণ লিঙ্কগুলি খোলার অনুমতি দেওয়া উচিত, যাতে Android অ্যাপ লিঙ্ক হ্যান্ডলার বা ডিফল্ট ব্রাউজার অ্যাপ উভয়ই অন্তর্ভুক্ত থাকে। অ্যান্ড্রয়েড কাস্টম ট্যাব লাইব্রেরিও একটি সমর্থিত বিকল্প।

iOS

WKWebView এ অনুমোদনের অনুরোধ খোলার সময় iOS এবং macOS ডেভেলপাররা এই ত্রুটির সম্মুখীন হতে পারে। বিকাশকারীদের পরিবর্তে iOS লাইব্রেরিগুলি ব্যবহার করা উচিত যেমন iOS এর জন্য Google সাইন-ইন বা iOS এর জন্য OpenID ফাউন্ডেশনের AppAuth

যখন কোনো iOS বা macOS অ্যাপ এমবেডেড ইউজার-এজেন্টে একটি সাধারণ ওয়েব লিঙ্ক খোলে এবং কোনো ব্যবহারকারী আপনার সাইট থেকে Google-এর OAuth 2.0 অনুমোদনের শেষ পয়েন্টে নেভিগেট করে তখন ওয়েব ডেভেলপাররা এই ত্রুটির সম্মুখীন হতে পারেন। বিকাশকারীদের অপারেটিং সিস্টেমের ডিফল্ট লিঙ্ক হ্যান্ডলারে সাধারণ লিঙ্কগুলি খোলার অনুমতি দেওয়া উচিত, যাতে ইউনিভার্সাল লিঙ্ক হ্যান্ডলার বা ডিফল্ট ব্রাউজার অ্যাপ উভয়ই অন্তর্ভুক্ত থাকে। SFSafariViewController লাইব্রেরিও একটি সমর্থিত বিকল্প।

org_internal

অনুরোধে OAuth ক্লায়েন্ট আইডি একটি নির্দিষ্ট Google ক্লাউড সংস্থার Google অ্যাকাউন্টগুলিতে অ্যাক্সেস সীমিত করে এমন একটি প্রকল্পের অংশ৷ এই কনফিগারেশন বিকল্প সম্পর্কে আরও তথ্যের জন্য আপনার OAuth সম্মতি স্ক্রীন সহায়তা নিবন্ধ সেট আপ করার ব্যবহারকারীর প্রকার বিভাগটি দেখুন।

invalid_client

OAuth ক্লায়েন্ট সিক্রেটটি ভুল। এই অনুরোধের জন্য ব্যবহৃত ক্লায়েন্ট আইডি এবং গোপনীয়তা সহ OAuth ক্লায়েন্ট কনফিগারেশন পর্যালোচনা করুন।

invalid_grant

একটি অ্যাক্সেস টোকেন রিফ্রেশ করার সময় বা বর্ধিত অনুমোদন ব্যবহার করার সময়, টোকেনের মেয়াদ শেষ হয়ে যেতে পারে বা অবৈধ হয়ে গেছে। ব্যবহারকারীকে আবার প্রমাণীকরণ করুন এবং নতুন টোকেন পাওয়ার জন্য ব্যবহারকারীর সম্মতি চান। আপনি যদি ক্রমাগত এই ত্রুটিটি দেখতে থাকেন তবে নিশ্চিত করুন যে আপনার অ্যাপ্লিকেশনটি সঠিকভাবে কনফিগার করা হয়েছে এবং আপনি আপনার অনুরোধে সঠিক টোকেন এবং প্যারামিটার ব্যবহার করছেন। অন্যথায়, ব্যবহারকারীর অ্যাকাউন্ট মুছে ফেলা বা নিষ্ক্রিয় করা হতে পারে।

redirect_uri_mismatch

অনুমোদনের অনুরোধে পাস করা redirect_uri OAuth ক্লায়েন্ট আইডির জন্য অনুমোদিত রিডাইরেক্ট URI-এর সাথে মেলে না। Review authorized redirect URIs in the Google API Console Credentials page.

The redirect_uri parameter may refer to the OAuth out-of-band (OOB) flow that has been deprecated and is no longer supported. Refer to the migration guide to update your integration.

Step 4: Handle the OAuth 2.0 server response

The OAuth 2.0 server responds to your application's access request by using the URL specified in the request.

If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message. The authorization code or error message that is returned to the web server appears on the query string, as shown below:

An error response:

https://oauth2.example.com/auth?error=access_denied

An authorization code response:

https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

Sample OAuth 2.0 server response

You can test this flow by clicking on the following sample URL, which requests read-only access to view metadata for files in your Google Drive:

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

After completing the OAuth 2.0 flow, you should be redirected to http://localhost/oauth2callback , which will likely yield a 404 NOT FOUND error unless your local machine serves a file at that address. The next step provides more detail about the information returned in the URI when the user is redirected back to your application.

Step 5: Exchange authorization code for refresh and access tokens

After the web server receives the authorization code, it can exchange the authorization code for an access token.

পিএইচপি

To exchange an authorization code for an access token, use the authenticate method:

$client->authenticate($_GET['code']);

You can retrieve the access token with the getAccessToken method:

$access_token = $client->getAccessToken();

পাইথন

On your callback page, use the google-auth library to verify the authorization server response. Then, use the flow.fetch_token method to exchange the authorization code in that response for an access token:

state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'],
    state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)

# Store the credentials in the session.
# ACTION ITEM for developers:
#     Store user's access and refresh tokens in your data store if
#     incorporating this code into your real app.
credentials = flow.credentials
flask.session['credentials'] = {
    'token': credentials.token,
    'refresh_token': credentials.refresh_token,
    'token_uri': credentials.token_uri,
    'client_id': credentials.client_id,
    'client_secret': credentials.client_secret,
    'scopes': credentials.scopes}

রুবি

To exchange an authorization code for an access token, use the fetch_access_token! method:

auth_client.code = auth_code
auth_client.fetch_access_token!

Node.js

To exchange an authorization code for an access token, use the getToken method:

const url = require('url');

// Receive the callback from Google's OAuth 2.0 server.
if (req.url.startsWith('/oauth2callback')) {
  // Handle the OAuth 2.0 server response
  let q = url.parse(req.url, true).query;

  // Get access and refresh tokens (if access_type is offline)
  let { tokens } = await oauth2Client.getToken(q.code);
  oauth2Client.setCredentials(tokens);
}

HTTP/REST

To exchange an authorization code for an access token, call the https://oauth2.googleapis.com/token endpoint and set the following parameters:

Fields
client_id The client ID obtained from the API ConsoleCredentials page.
client_secret The client secret obtained from the API ConsoleCredentials page.
code The authorization code returned from the initial request.
grant_type As defined in the OAuth 2.0 specification , this field's value must be set to authorization_code .
redirect_uri One of the redirect URIs listed for your project in the API ConsoleCredentials page for the given client_id .

The following snippet shows a sample request:

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

Google responds to this request by returning a JSON object that contains a short-lived access token and a refresh token. Note that the refresh token is only returned if your application set the access_type parameter to offline in the initial request to Google's authorization server .

The response contains the following fields:

Fields
access_token The token that your application sends to authorize a Google API request.
expires_in The remaining lifetime of the access token in seconds.
refresh_token A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Again, this field is only present in this response if you set the access_type parameter to offline in the initial request to Google's authorization server.
scope The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
token_type The type of token returned. At this time, this field's value is always set to Bearer .

The following snippet shows a sample response:

{
  "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in": 3920,
  "token_type": "Bearer",
  "scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
  "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Errors

When exchanging the authorization code for an access token you may encounter the following error instead of the expected response. Common error codes and suggested resolutions are listed below.

invalid_grant

The supplied authorization code is invalid or in the wrong format. Request a new code by restarting the OAuth process to prompt the user for consent again.

Calling Google APIs

পিএইচপি

Use the access token to call Google APIs by completing the following steps:

  1. If you need to apply an access token to a new Google\Client object — for example, if you stored the access token in a user session — use the setAccessToken method:
    $client->setAccessToken($access_token);
  2. Build a service object for the API that you want to call. You build a service object by providing an authorized Google\Client object to the constructor for the API you want to call. For example, to call the Drive API:
    $drive = new Google\Service\Drive($client);
  3. Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
    $files = $drive->files->listFiles(array())->getItems();

পাইথন

After obtaining an access token, your application can use that token to authorize API requests on behalf of a given user account or service account. Use the user-specific authorization credentials to build a service object for the API that you want to call, and then use that object to make authorized API requests.

  1. Build a service object for the API that you want to call. You build a service object by calling the googleapiclient.discovery library's build method with the name and version of the API and the user credentials: For example, to call version 2 of the Drive API:
    from googleapiclient.discovery import build
    
    drive = build('drive', 'v2', credentials=credentials)
  2. Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
    files = drive.files().list().execute()

রুবি

Use the auth_client object to call Google APIs by completing the following steps:

  1. Build a service object for the API that you want to call. For example, to call version 2 of the Drive API:
    drive = Google::Apis::DriveV2::DriveService.new
  2. Set the credentials on the service:
    drive.authorization = auth_client
  3. Make requests to the API service using the interface provided by the service object . For example, to list the files in the authenticated user's Google Drive:
    files = drive.list_files

Alternately, authorization can be provided on a per-method basis by supplying the options parameter to a method:

files = drive.list_files(options: { authorization: auth_client })

Node.js

After obtaining an access token and setting it to the OAuth2 object, use the object to call Google APIs. Your application can use that token to authorize API requests on behalf of a given user account or service account. Build a service object for the API that you want to call.

const { google } = require('googleapis');

// Example of using Google Drive API to list filenames in user's Drive.
const drive = google.drive('v3');
drive.files.list({
  auth: oauth2Client,
  pageSize: 10,
  fields: 'nextPageToken, files(id, name)',
}, (err1, res1) => {
  if (err1) return console.log('The API returned an error: ' + err1);
  const files = res1.data.files;
  if (files.length) {
    console.log('Files:');
    files.map((file) => {
      console.log(`${file.name} (${file.id})`);
    });
  } else {
    console.log('No files found.');
  }
});

HTTP/REST

After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account if the scope(s) of access required by the API have been granted. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization HTTP header Bearer value. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive Files API ).

You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground .

HTTP GET examples

A call to the drive.files endpoint (the Drive Files API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

GET /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token

Here is a call to the same API for the authenticated user using the access_token query string parameter:

GET https://www.googleapis.com/drive/v2/files?access_token=access_token

curl examples

You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):

curl -H "Authorization: Bearer access_token" https://www.googleapis.com/drive/v2/files

Or, alternatively, the query string parameter option:

curl https://www.googleapis.com/drive/v2/files?access_token=access_token

Complete example

The following example prints a JSON-formatted list of files in a user's Google Drive after the user authenticates and gives consent for the application to access the user's Drive metadata.

পিএইচপি

To run this example:

  1. In the API Console, add the URL of the local machine to the list of redirect URLs. For example, add http://localhost:8080 .
  2. Create a new directory and change to it. For example:
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Install the Google API Client Library for PHP using Composer :
    composer require google/apiclient:^2.10
  4. Create the files index.php and oauth2callback.php with the content below.
  5. Run the example with a web server configured to serve PHP. If you use PHP 5.6 or newer, you can use PHP's built-in test web server:
    php -S localhost:8080 ~/php-oauth2-example

index.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $drive = new Google\Service\Drive($client);
  $files = $drive->files->listFiles(array())->getItems();
  echo json_encode($files);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

পাইথন

This example uses the Flask framework. It runs a web application at http://localhost:8080 that lets you test the OAuth 2.0 flow. If you go to that URL, you should see four links:

  • Test an API request: This link points to a page that tries to execute a sample API request. If necessary, it starts the authorization flow. If successful, the page displays the API response.
  • Test the auth flow directly: This link points to a page that tries to send the user through the authorization flow . The app requests permission to submit authorized API requests on the user's behalf.
  • Revoke current credentials: This link points to a page that revokes permissions that the user has already granted to the application.
  • Clear Flask session credentials: This link clears authorization credentials that are stored in the Flask session. This lets you see what would happen if a user who had already granted permission to your app tried to execute an API request in a new session. It also lets you see the API response your app would get if a user had revoked permissions granted to your app, and your app still tried to authorize a request with a revoked access token.
# -*- coding: utf-8 -*-

import os
import flask
import requests

import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery

# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
API_SERVICE_NAME = 'drive'
API_VERSION = 'v2'

app = flask.Flask(__name__)
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See https://flask.palletsprojects.com/quickstart/#sessions.
app.secret_key = 'REPLACE ME - this value is here as a placeholder.'


@app.route('/')
def index():
  return print_index_table()


@app.route('/test')
def test_api_request():
  if 'credentials' not in flask.session:
    return flask.redirect('authorize')

  # Load credentials from the session.
  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  drive = googleapiclient.discovery.build(
      API_SERVICE_NAME, API_VERSION, credentials=credentials)

  files = drive.files().list().execute()

  # Save credentials back to session in case access token was refreshed.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.jsonify(**files)


@app.route('/authorize')
def authorize():
  # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)

  # The URI created here must exactly match one of the authorized redirect URIs
  # for the OAuth 2.0 client, which you configured in the API Console. If this
  # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
  # error.
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  authorization_url, state = flow.authorization_url(
      # Enable offline access so that you can refresh an access token without
      # re-prompting the user for permission. Recommended for web server apps.
      access_type='offline',
      # Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes='true')

  # Store the state so the callback can verify the auth server response.
  flask.session['state'] = state

  return flask.redirect(authorization_url)


@app.route('/oauth2callback')
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.
  state = flask.session['state']

  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = flask.request.url
  flow.fetch_token(authorization_response=authorization_response)

  # Store credentials in the session.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  credentials = flow.credentials
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.redirect(flask.url_for('test_api_request'))


@app.route('/revoke')
def revoke():
  if 'credentials' not in flask.session:
    return ('You need to <a href="/authorize">authorize</a> before ' +
            'testing the code to revoke credentials.')

  credentials = google.oauth2.credentials.Credentials(
    **flask.session['credentials'])

  revoke = requests.post('https://oauth2.googleapis.com/revoke',
      params={'token': credentials.token},
      headers = {'content-type': 'application/x-www-form-urlencoded'})

  status_code = getattr(revoke, 'status_code')
  if status_code == 200:
    return('Credentials successfully revoked.' + print_index_table())
  else:
    return('An error occurred.' + print_index_table())


@app.route('/clear')
def clear_credentials():
  if 'credentials' in flask.session:
    del flask.session['credentials']
  return ('Credentials have been cleared.<br><br>' +
          print_index_table())


def credentials_to_dict(credentials):
  return {'token': credentials.token,
          'refresh_token': credentials.refresh_token,
          'token_uri': credentials.token_uri,
          'client_id': credentials.client_id,
          'client_secret': credentials.client_secret,
          'scopes': credentials.scopes}

def print_index_table():
  return ('<table>' +
          '<tr><td><a href="/test">Test an API request</a></td>' +
          '<td>Submit an API request and see a formatted JSON response. ' +
          '    Go through the authorization flow if there are no stored ' +
          '    credentials for the user.</td></tr>' +
          '<tr><td><a href="/authorize">Test the auth flow directly</a></td>' +
          '<td>Go directly to the authorization flow. If there are stored ' +
          '    credentials, you still might not be prompted to reauthorize ' +
          '    the application.</td></tr>' +
          '<tr><td><a href="/revoke">Revoke current credentials</a></td>' +
          '<td>Revoke the access token associated with the current user ' +
          '    session. After revoking credentials, if you go to the test ' +
          '    page, you should see an <code>invalid_grant</code> error.' +
          '</td></tr>' +
          '<tr><td><a href="/clear">Clear Flask session credentials</a></td>' +
          '<td>Clear the access token currently stored in the user session. ' +
          '    After clearing the token, if you <a href="/test">test the ' +
          '    API request</a> again, you should go back to the auth flow.' +
          '</td></tr></table>')


if __name__ == '__main__':
  # When running locally, disable OAuthlib's HTTPs verification.
  # ACTION ITEM for developers:
  #     When running in production *do not* leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  # Specify a hostname and port that are set as a valid redirect URI
  # for your API project in the Google API Console.
  app.run('localhost', 8080, debug=True)

রুবি

This example uses the Sinatra framework.

require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'
require 'json'
require 'sinatra'

enable :sessions
set :session_secret, 'setme'

get '/' do
  unless session.has_key?(:credentials)
    redirect to('/oauth2callback')
  end
  client_opts = JSON.parse(session[:credentials])
  auth_client = Signet::OAuth2::Client.new(client_opts)
  drive = Google::Apis::DriveV2::DriveService.new
  files = drive.list_files(options: { authorization: auth_client })
  "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
end

get '/oauth2callback' do
  client_secrets = Google::APIClient::ClientSecrets.load
  auth_client = client_secrets.to_authorization
  auth_client.update!(
    :scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
    :redirect_uri => url('/oauth2callback'))
  if request['code'] == nil
    auth_uri = auth_client.authorization_uri.to_s
    redirect to(auth_uri)
  else
    auth_client.code = request['code']
    auth_client.fetch_access_token!
    auth_client.client_secret = nil
    session[:credentials] = auth_client.to_json
    redirect to('/')
  end
end

Node.js

To run this example:

  1. In the API Console, add the URL of the local machine to the list of redirect URLs. For example, add http://localhost .
  2. Make sure you have maintenance LTS, active LTS, or current release of Node.js installed.
  3. Create a new directory and change to it. For example:
    mkdir ~/nodejs-oauth2-example
    cd ~/nodejs-oauth2-example
  4. Install the Google API Client Library for Node.js using npm:
    npm install googleapis
  5. Create the files main.js with the content below.
  6. Run the example:
    node .\main.js

main.js

const http = require('http');
const https = require('https');
const url = require('url');
const { google } = require('googleapis');

/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI.
 * To get these credentials for your application, visit
 * https://console.cloud.google.com/apis/credentials.
 */
const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// Access scopes for read-only Drive activity.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly'
];

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',
  /** Pass in the scopes array defined above.
    * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
  scope: scopes,
  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true
});

/* Global variable that stores user credential in this code example.
 * ACTION ITEM for developers:
 *   Store user's refresh token in your data store if
 *   incorporating this code into your real app.
 *   For more information on handling refresh tokens,
 *   see https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens
 */
let userCredential = null;

async function main() {
  const server = http.createServer(async function (req, res) {
    // Example on redirecting user to Google's OAuth 2.0 server.
    if (req.url == '/') {
      res.writeHead(301, { "Location": authorizationUrl });
    }

    // Receive the callback from Google's OAuth 2.0 server.
    if (req.url.startsWith('/oauth2callback')) {
      // Handle the OAuth 2.0 server response
      let q = url.parse(req.url, true).query;

      if (q.error) { // An error response e.g. error=access_denied
        console.log('Error:' + q.error);
      } else { // Get access and refresh tokens (if access_type is offline)
        let { tokens } = await oauth2Client.getToken(q.code);
        oauth2Client.setCredentials(tokens);

        /** Save credential to the global variable in case access token was refreshed.
          * ACTION ITEM: In a production app, you likely want to save the refresh token
          *              in a secure persistent database instead. */
        userCredential = tokens;

        // Example of using Google Drive API to list filenames in user's Drive.
        const drive = google.drive('v3');
        drive.files.list({
          auth: oauth2Client,
          pageSize: 10,
          fields: 'nextPageToken, files(id, name)',
        }, (err1, res1) => {
          if (err1) return console.log('The API returned an error: ' + err1);
          const files = res1.data.files;
          if (files.length) {
            console.log('Files:');
            files.map((file) => {
              console.log(`${file.name} (${file.id})`);
            });
          } else {
            console.log('No files found.');
          }
        });
      }
    }

    // Example on revoking a token
    if (req.url == '/revoke') {
      // Build the string for the POST request
      let postData = "token=" + userCredential.access_token;

      // Options for POST request to Google's OAuth 2.0 server to revoke a token
      let postOptions = {
        host: 'oauth2.googleapis.com',
        port: '443',
        path: '/revoke',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(postData)
        }
      };

      // Set up the request
      const postReq = https.request(postOptions, function (res) {
        res.setEncoding('utf8');
        res.on('data', d => {
          console.log('Response: ' + d);
        });
      });

      postReq.on('error', error => {
        console.log(error)
      });

      // Post the request with data
      postReq.write(postData);
      postReq.end();
    }
    res.end();
  }).listen(80);
}
main().catch(console.error);

HTTP/REST

This Python example uses the Flask framework and the Requests library to demonstrate the OAuth 2.0 web flow. We recommend using the Google API Client Library for Python for this flow. (The example in the Python tab does use the client library.)

import json

import flask
import requests


app = flask.Flask(__name__)

CLIENT_ID = '123456789.apps.googleusercontent.com'
CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly'
REDIRECT_URI = 'http://example.com/oauth2callback'


@app.route('/')
def index():
  if 'credentials' not in flask.session:
    return flask.redirect(flask.url_for('oauth2callback'))
  credentials = json.loads(flask.session['credentials'])
  if credentials['expires_in'] <= 0:
    return flask.redirect(flask.url_for('oauth2callback'))
  else:
    headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
    req_uri = 'https://www.googleapis.com/drive/v2/files'
    r = requests.get(req_uri, headers=headers)
    return r.text


@app.route('/oauth2callback')
def oauth2callback():
  if 'code' not in flask.request.args:
    auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                '&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    data = {'code': auth_code,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'authorization_code'}
    r = requests.post('https://oauth2.googleapis.com/token', data=data)
    flask.session['credentials'] = r.text
    return flask.redirect(flask.url_for('index'))


if __name__ == '__main__':
  import uuid
  app.secret_key = str(uuid.uuid4())
  app.debug = False
  app.run()

Redirect URI validation rules

Google applies the following validation rules to redirect URIs in order to help developers keep their applications secure. Your redirect URIs must adhere to these rules. See RFC 3986 section 3 for the definition of domain, host, path, query, scheme and userinfo, mentioned below.

Validation rules
Scheme

Redirect URIs must use the HTTPS scheme, not plain HTTP. Localhost URIs (including localhost IP address URIs) are exempt from this rule.

Host

Hosts cannot be raw IP addresses. Localhost IP addresses are exempted from this rule.

Domain
  • Host TLDs ( Top Level Domains ) must belong to the public suffix list .
  • Host domains cannot be “googleusercontent.com” .
  • Redirect URIs cannot contain URL shortener domains (eg goo.gl ) unless the app owns the domain. Furthermore, if an app that owns a shortener domain chooses to redirect to that domain, that redirect URI must either contain “/google-callback/” in its path or end with “/google-callback” .
  • Userinfo

    Redirect URIs cannot contain the userinfo subcomponent.

    Path

    Redirect URIs cannot contain a path traversal (also called directory backtracking), which is represented by an “/..” or “\..” or their URL encoding.

    Query

    Redirect URIs cannot contain open redirects .

    Fragment

    Redirect URIs cannot contain the fragment component.

    Characters Redirect URIs cannot contain certain characters including:
    • Wildcard characters ( '*' )
    • Non-printable ASCII characters
    • Invalid percent encodings (any percent encoding that does not follow URL-encoding form of a percent sign followed by two hexadecimal digits)
    • Null characters (an encoded NULL character, eg, %00 , %C0%80 )

    Incremental authorization

    In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google's authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission for the new scope, returns an authorization code that may be exchanged for a token containing all scopes the user has granted the project.

    For example, an app that lets people sample music tracks and create mixes might need very few resources at sign-in time, perhaps nothing more than the name of the person signing in. However, saving a completed mix would require access to their Google Drive. Most people would find it natural if they only were asked for access to their Google Drive at the time the app actually needed it.

    In this case, at sign-in time the app might request the openid and profile scopes to perform basic sign-in, and then later request the https://www.googleapis.com/auth/drive.file scope at the time of the first request to save a mix.

    To implement incremental authorization, you complete the normal flow for requesting an access token but make sure that the authorization request includes previously granted scopes. This approach allows your app to avoid having to manage multiple access tokens.

    The following rules apply to an access token obtained from an incremental authorization:

    • The token can be used to access resources corresponding to any of the scopes rolled into the new, combined authorization.
    • When you use the refresh token for the combined authorization to obtain an access token, the access token represents the combined authorization and can be used for any of the scope values included in the response.
    • The combined authorization includes all scopes that the user granted to the API project even if the grants were requested from different clients. For example, if a user granted access to one scope using an application's desktop client and then granted another scope to the same application via a mobile client, the combined authorization would include both scopes.
    • If you revoke a token that represents a combined authorization, access to all of that authorization's scopes on behalf of the associated user are revoked simultaneously.

    The language-specific code samples in Step 1: Set authorization parameters and the sample HTTP/REST redirect URL in Step 2: Redirect to Google's OAuth 2.0 server all use incremental authorization. The code samples below also show the code that you need to add to use incremental authorization.

    পিএইচপি

    $client->setIncludeGrantedScopes(true);

    পাইথন

    In Python, set the include_granted_scopes keyword argument to true to ensure that an authorization request includes previously granted scopes. It is very possible that include_granted_scopes will not be the only keyword argument that you set, as shown in the example below.

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    রুবি

    auth_client.update!(
      :additional_parameters => {"include_granted_scopes" => "true"}
    )

    Node.js

    const authorizationUrl = oauth2Client.generateAuthUrl({
      // 'online' (default) or 'offline' (gets refresh_token)
      access_type: 'offline',
      /** Pass in the scopes array defined above.
        * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
      scope: scopes,
      // Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes: true
    });
    

    HTTP/REST

    GET https://accounts.google.com/o/oauth2/v2/auth?
      client_id=your_client_id&
      response_type=code&
      state=state_parameter_passthrough_value&
      scope=https%3A//www.googleapis.com/auth/drive.file&
      redirect_uri=https%3A//oauth2.example.com/code&
      prompt=consent&
      include_granted_scopes=true

    Refreshing an access token (offline access)

    Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

    • If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
    • If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server . In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.

    Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online .

    Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

    পিএইচপি

    If your application needs offline access to a Google API, set the API client's access type to offline :

    $client->setAccessType("offline");

    After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

    পাইথন

    In Python, set the access_type keyword argument to offline to ensure that you will be able to refresh the access token without having to re-prompt the user for permission. It is very possible that access_type will not be the only keyword argument that you set, as shown in the example below.

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

    রুবি

    If your application needs offline access to a Google API, set the API client's access type to offline :

    auth_client.update!(
      :additional_parameters => {"access_type" => "offline"}
    )

    After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

    Node.js

    If your application needs offline access to a Google API, set the API client's access type to offline :

    const authorizationUrl = oauth2Client.generateAuthUrl({
      // 'online' (default) or 'offline' (gets refresh_token)
      access_type: 'offline',
      /** Pass in the scopes array defined above.
        * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
      scope: scopes,
      // Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes: true
    });
    

    After a user grants offline access to the requested scopes, you can continue to use the API client to access Google APIs on the user's behalf when the user is offline. The client object will refresh the access token as needed.

    Access tokens expire. This library will automatically use a refresh token to obtain a new access token if it is about to expire. An easy way to make sure you always store the most recent tokens is to use the tokens event:

    oauth2Client.on('tokens', (tokens) => {
      if (tokens.refresh_token) {
        // store the refresh_token in your secure persistent database
        console.log(tokens.refresh_token);
      }
      console.log(tokens.access_token);
    });

    This tokens event only occurs in the first authorization, and you need to have set your access_type to offline when calling the generateAuthUrl method to receive the refresh token. If you have already given your app the requisiste permissions without setting the appropriate constraints for receiving a refresh token, you will need to re-authorize the application to receive a fresh refresh token.

    To set the refresh_token at a later time, you can use the setCredentials method:

    oauth2Client.setCredentials({
      refresh_token: `STORED_REFRESH_TOKEN`
    });
    

    Once the client has a refresh token, access tokens will be acquired and refreshed automatically in the next call to the API.

    HTTP/REST

    To refresh an access token, your application sends an HTTPS POST request to Google's authorization server ( https://oauth2.googleapis.com/token ) that includes the following parameters:

    Fields
    client_id The client ID obtained from the API Console.
    client_secret The client secret obtained from the API Console.
    grant_type As defined in the OAuth 2.0 specification , this field's value must be set to refresh_token .
    refresh_token The refresh token returned from the authorization code exchange.

    The following snippet shows a sample request:

    POST /token HTTP/1.1
    Host: oauth2.googleapis.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=your_client_id&
    client_secret=your_client_secret&
    refresh_token=refresh_token&
    grant_type=refresh_token

    As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

    {
      "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
      "expires_in": 3920,
      "scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
      "token_type": "Bearer"
    }

    Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.

    Revoking a token

    In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings . See the Remove site or app access section of the Third-party sites & apps with access to your account support document for more information.

    It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes, removes an application, or the API resources required by an app have significantly changed. In other words, part of the removal process can include an API request to ensure the permissions previously granted to the application are removed.

    পিএইচপি

    To programmatically revoke a token, call revokeToken() :

    $client->revokeToken();

    পাইথন

    To programmatically revoke a token, make a request to https://oauth2.googleapis.com/revoke that includes the token as a parameter and sets the Content-Type header:

    requests.post('https://oauth2.googleapis.com/revoke',
        params={'token': credentials.token},
        headers = {'content-type': 'application/x-www-form-urlencoded'})

    রুবি

    To programmatically revoke a token, make an HTTP request to the oauth2.revoke endpoint:

    uri = URI('https://oauth2.googleapis.com/revoke')
    response = Net::HTTP.post_form(uri, 'token' => auth_client.access_token)
    

    The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

    If the revocation is successfully processed, then the status code of the response is 200 . For error conditions, a status code 400 is returned along with an error code.

    Node.js

    To programmatically revoke a token, make an HTTPS POST request to /revoke endpoint:

    const https = require('https');
    
    // Build the string for the POST request
    let postData = "token=" + userCredential.access_token;
    
    // Options for POST request to Google's OAuth 2.0 server to revoke a token
    let postOptions = {
      host: 'oauth2.googleapis.com',
      port: '443',
      path: '/revoke',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };
    
    // Set up the request
    const postReq = https.request(postOptions, function (res) {
      res.setEncoding('utf8');
      res.on('data', d => {
        console.log('Response: ' + d);
      });
    });
    
    postReq.on('error', error => {
      console.log(error)
    });
    
    // Post the request with data
    postReq.write(postData);
    postReq.end();
    

    The token parameter can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

    If the revocation is successfully processed, then the status code of the response is 200 . For error conditions, a status code 400 is returned along with an error code.

    HTTP/REST

    To programmatically revoke a token, your application makes a request to https://oauth2.googleapis.com/revoke and includes the token as a parameter:

    curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded" \
            https://oauth2.googleapis.com/revoke?token={token}

    The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

    If the revocation is successfully processed, then the HTTP status code of the response is 200 . For error conditions, an HTTP status code 400 is returned along with an error code.