ওয়েব সার্ভার অ্যাপ্লিকেশনের জন্য 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গুলিকে সক্ষম করতে হবে৷ API Console.

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

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

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

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

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

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

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

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

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

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

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

পিএইচপি

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

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

    composer require google/apiclient:^2.15.0

আরও তথ্যের জন্য PHP-এর জন্য Google APIs ক্লায়েন্ট লাইব্রেরি দেখুন।

পাইথন

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

  • Python 3.7 বা তার বেশি
  • পাইপ প্যাকেজ ম্যানেজমেন্ট টুল।
  • Python 2.0 প্রকাশের জন্য 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

আপনি যদি পাইথন এবং সংশ্লিষ্ট মাইগ্রেশন গাইড আপগ্রেড করতে না পারেন তবে Google API Python ক্লায়েন্ট লাইব্রেরি রিলিজ নোটটি পর্যালোচনা করুন।

রুবি

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

  • রুবি 2.6 বা তার বেশি
  • রুবির জন্য Google Auth লাইব্রেরি:

    gem install googleauth
  • ড্রাইভ এবং ক্যালেন্ডার Google API-এর জন্য ক্লায়েন্ট লাইব্রেরি:

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

    gem install sinatra

Node.js

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

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

    npm install googleapis crypto express express-session

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 ড্রাইভ মেটাডেটা এবং ক্যালেন্ডার ইভেন্টগুলিতে শুধুমাত্র-পঠন, অফলাইন অ্যাক্সেসের অনুরোধ করে:

use Google\Client;

$client = new Client();

// Required, call the setAuthConfig function to load authorization credentials from
// client_secret.json file.
$client->setAuthConfig('client_secret.json');

// Required, to set the scope value, call the addScope function
$client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);

// Required, call the setRedirectUri function to specify a valid redirect URI for the
// provided client_id
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

// Recommended, 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');

// Recommended, call the setState function. Using a state value can increase your assurance that
// an incoming connection is the result of an authentication request.
$client->setState($sample_passthrough_value);

// Optional, if your application knows which user is trying to authenticate, it can use this
// parameter to provide a hint to the Google Authentication Server.
$client->setLoginHint('hint@example.com');

// Optional, call the setPrompt function to set "consent" will prompt the user for consent
$client->setPrompt('consent');

// Optional, call the setIncludeGrantedScopes function with true to enable incremental
// authorization
$client->setIncludeGrantedScopes(true);

পাইথন

নিম্নলিখিত কোড স্নিপেট অনুমোদনের অনুরোধ তৈরি করতে 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

# Required, call the from_client_secrets_file method to retrieve the client ID from a
# client_secret.json file. The client ID (from that file) and access scopes are required. (You can
# also use the from_client_config method, which passes the client configuration as it originally
# appeared in a client secrets file but doesn't access the file itself.)
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly',
            'https://www.googleapis.com/auth/calendar.readonly'])

# Required, 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(
    # Recommended, 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',
    # Optional, enable incremental authorization. Recommended as a best practice.
    include_granted_scopes='true',
    # Optional, if your application knows which user is trying to authenticate, it can use this
    # parameter to provide a hint to the Google Authentication Server.
    login_hint='hint@example.com',
    # Optional, set prompt to 'consent' will prompt the user for consent
    prompt='consent')

রুবি

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

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

require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'

require 'google/apis/drive_v3'
require 'google/apis/calendar_v3'

# Required, call the from_file method to retrieve the client ID from a
# client_secret.json file.
client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')

# Required, scope value 
# Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
         'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']

# Required, Authorizers require a storage instance to manage long term persistence of
# access and refresh tokens.
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)

# Required, 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.
callback_uri = '/oauth2callback'

# 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.
authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope,
                                                token_store, callback_uri)

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

Node.js

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

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

const {google} = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');

/**
 * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly',
  'https://www.googleapis.com/auth/calendar.readonly'
];

// Generate a secure random state value.
const state = crypto.randomBytes(32).toString('hex');

// Store state in the session
req.session.state = state;

// Generate a url that asks permissions for the Drive activity and Google Calendar 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,
  // Include the state parameter to reduce the risk of CSRF attacks.
  state: state
});

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

HTTP/REST

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

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

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

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

redirect_uri প্রয়োজন

ব্যবহারকারী অনুমোদন প্রবাহ সম্পূর্ণ করার পরে API সার্ভার ব্যবহারকারীকে কোথায় রিডাইরেক্ট করে তা নির্ধারণ করে। মানটি অবশ্যই OAuth 2.0 ক্লায়েন্টের জন্য অনুমোদিত রিডাইরেক্ট ইউআরআইগুলির একটির সাথে মিলতে হবে, যা আপনি আপনার ক্লায়েন্টের কনফিগার করেছেন . যদি এই মানটি প্রদত্ত 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 = authorizer.get_authorization_url(request: request)
  2. ব্যবহারকারীকে auth_uri এ পুনঃনির্দেশ করুন।

Node.js

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

HTTP/REST

Google এর অনুমোদন সার্ভারে নমুনা পুনঃনির্দেশ

পঠনযোগ্যতার জন্য লাইন বিরতি এবং স্পেস সহ একটি উদাহরণ URL নীচে দেখানো হয়েছে।

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.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-এর সাথে মেলে না। তে অনুমোদিত পুনঃনির্দেশ ইউআরআই পর্যালোচনা করুন৷ .

redirect_uri প্যারামিটার OAuth আউট-অফ-ব্যান্ড (OOB) প্রবাহকে নির্দেশ করতে পারে যা অবমূল্যায়িত হয়েছে এবং আর সমর্থিত নয়। আপনার ইন্টিগ্রেশন আপডেট করতে মাইগ্রেশন গাইড পড়ুন।

invalid_request

আপনার অনুরোধে কিছু ভুল ছিল। এটি বেশ কয়েকটি কারণে হতে পারে:

  • অনুরোধটি সঠিকভাবে ফরম্যাট করা হয়নি
  • অনুরোধে প্রয়োজনীয় পরামিতি অনুপস্থিত ছিল
  • অনুরোধটি একটি অনুমোদন পদ্ধতি ব্যবহার করে যা Google সমর্থন করে না। আপনার OAuth ইন্টিগ্রেশন একটি প্রস্তাবিত ইন্টিগ্রেশন পদ্ধতি ব্যবহার করে যাচাই করুন

ধাপ 4: OAuth 2.0 সার্ভার প্রতিক্রিয়া পরিচালনা করুন

OAuth 2.0 সার্ভার অনুরোধে উল্লেখিত URL ব্যবহার করে আপনার অ্যাপ্লিকেশনের অ্যাক্সেসের অনুরোধে সাড়া দেয়।

ব্যবহারকারী যদি অ্যাক্সেস অনুরোধ অনুমোদন করে, তাহলে প্রতিক্রিয়াটিতে একটি অনুমোদন কোড থাকে। ব্যবহারকারী অনুরোধটি অনুমোদন না করলে, প্রতিক্রিয়াটিতে একটি ত্রুটি বার্তা রয়েছে। ওয়েব সার্ভারে প্রত্যাবর্তিত অনুমোদন কোড বা ত্রুটি বার্তাটি ক্যোয়ারী স্ট্রিং-এ প্রদর্শিত হবে, যেমনটি নীচে দেখানো হয়েছে:

একটি ত্রুটি প্রতিক্রিয়া:

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

একটি অনুমোদন কোড প্রতিক্রিয়া:

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

নমুনা OAuth 2.0 সার্ভার প্রতিক্রিয়া

আপনি নিম্নলিখিত নমুনা URL-এ ক্লিক করে এই প্রবাহটি পরীক্ষা করতে পারেন, যা আপনার Google ড্রাইভে ফাইলগুলির জন্য মেটাডেটা দেখার জন্য শুধুমাত্র-পঠন অ্যাক্সেসের অনুরোধ করে এবং আপনার Google ক্যালেন্ডার ইভেন্টগুলি দেখার জন্য শুধুমাত্র-পঠন অ্যাক্সেসের অনুরোধ করে:

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.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

OAuth 2.0 ফ্লো সম্পূর্ণ করার পরে, আপনাকে http://localhost/oauth2callback এ পুনঃনির্দেশিত করা উচিত, যা সম্ভবত একটি 404 NOT FOUND ত্রুটি প্রদান করবে যদি না আপনার স্থানীয় মেশিন সেই ঠিকানায় একটি ফাইল পরিবেশন করে। পরবর্তী ধাপে ইউআরআই-এ ফেরত দেওয়া তথ্য সম্পর্কে আরও বিশদ প্রদান করা হয় যখন ব্যবহারকারীকে আপনার অ্যাপ্লিকেশনে ফেরত পাঠানো হয়।

ধাপ 5: রিফ্রেশ এবং অ্যাক্সেস টোকেনগুলির জন্য এক্সচেঞ্জ অনুমোদন কোড

ওয়েব সার্ভার অনুমোদন কোড পাওয়ার পরে, এটি একটি অ্যাক্সেস টোকেনের জন্য অনুমোদন কোড বিনিময় করতে পারে।

পিএইচপি

একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করতে, fetchAccessTokenWithAuthCode পদ্ধতি ব্যবহার করুন:

$access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

পাইথন

আপনার কলব্যাক পৃষ্ঠায়, অনুমোদন সার্ভার প্রতিক্রিয়া যাচাই করতে google-auth লাইব্রেরি ব্যবহার করুন৷ তারপর, একটি অ্যাক্সেস টোকেনের জন্য সেই প্রতিক্রিয়াতে অনুমোদন কোড বিনিময় করতে flow.fetch_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,
    'granted_scopes': credentials.granted_scopes}

রুবি

আপনার কলব্যাক পৃষ্ঠায়, অনুমোদন সার্ভার প্রতিক্রিয়া যাচাই করতে googleauth লাইব্রেরি ব্যবহার করুন৷ অনুমোদন কোড সংরক্ষণ করতে authorizer.handle_auth_callback_deferred পদ্ধতি ব্যবহার করুন এবং মূল অনুমোদনের অনুরোধ করা URL-এ পুনরায় নির্দেশ করুন৷ এটি ব্যবহারকারীর সেশনে ফলাফলগুলিকে সাময়িকভাবে লুকিয়ে রেখে কোডের বিনিময় স্থগিত করে৷

  target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
  redirect target_url

Node.js

একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করতে, getToken পদ্ধতি ব্যবহার করুন:

const url = require('url');

// Receive the callback from Google's OAuth 2.0 server.
app.get('/oauth2callback', async (req, res) => {
  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 if (q.state !== req.session.state) { //check state value
    console.log('State mismatch. Possible CSRF attack');
    res.end('State mismatch. Possible CSRF attack');
  } else { // Get access and refresh tokens (if access_type is offline)

    let { tokens } = await oauth2Client.getToken(q.code);
    oauth2Client.setCredentials(tokens);
});

HTTP/REST

একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করতে, https://oauth2.googleapis.com/token এন্ডপয়েন্টে কল করুন এবং নিম্নলিখিত প্যারামিটারগুলি সেট করুন:

ক্ষেত্র
client_id ক্লায়েন্ট আইডি থেকে প্রাপ্ত .
client_secret ক্লায়েন্ট সিক্রেট থেকে প্রাপ্ত .
code অনুমোদন কোড প্রাথমিক অনুরোধ থেকে ফিরে.
grant_type OAuth 2.0 স্পেসিফিকেশনে যেমন সংজ্ঞায়িত করা হয়েছে , এই ক্ষেত্রের মান অবশ্যই authorization_code এ সেট করতে হবে।
redirect_uri আপনার প্রোজেক্টের জন্য তালিকাভুক্ত রিডাইরেক্ট ইউআরআইগুলির মধ্যে একটি প্রদত্ত client_id জন্য।

নিম্নলিখিত স্নিপেট একটি নমুনা অনুরোধ দেখায়:

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 একটি JSON অবজেক্ট ফেরত দিয়ে এই অনুরোধে সাড়া দেয় যাতে একটি স্বল্পকালীন অ্যাক্সেস টোকেন এবং একটি রিফ্রেশ টোকেন রয়েছে। মনে রাখবেন যে রিফ্রেশ টোকেনটি শুধুমাত্র তখনই ফেরত দেওয়া হয় যখন আপনার অ্যাপ্লিকেশন Google-এর অনুমোদন সার্ভারে প্রাথমিক অনুরোধে access_type প্যারামিটারটিকে offline সেট করে।

প্রতিক্রিয়াতে নিম্নলিখিত ক্ষেত্রগুলি রয়েছে:

ক্ষেত্র
access_token একটি Google API অনুরোধ অনুমোদন করার জন্য আপনার অ্যাপ্লিকেশন যে টোকেন পাঠায়।
expires_in সেকেন্ডে অ্যাক্সেস টোকেনের অবশিষ্ট জীবনকাল।
refresh_token একটি টোকেন যা আপনি একটি নতুন অ্যাক্সেস টোকেন পেতে ব্যবহার করতে পারেন। রিফ্রেশ টোকেন বৈধ থাকে যতক্ষণ না ব্যবহারকারী অ্যাক্সেস প্রত্যাহার করে বা রিফ্রেশ টোকেনের মেয়াদ শেষ না হয়। আবার, এই ক্ষেত্রটি শুধুমাত্র এই প্রতিক্রিয়াতে উপস্থিত থাকে যদি আপনি Google-এর অনুমোদন সার্ভারে প্রাথমিক অনুরোধে access_type প্যারামিটার offline সেট করেন।
refresh_token_expires_in সেকেন্ডে রিফ্রেশ টোকেনের অবশিষ্ট জীবনকাল। এই মানটি তখনই সেট করা হয় যখন ব্যবহারকারী সময়-ভিত্তিক অ্যাক্সেস মঞ্জুর করে৷
scope access_token দ্বারা প্রদত্ত অ্যাক্সেসের সুযোগগুলি স্থান-সীমাবদ্ধ, কেস-সংবেদনশীল স্ট্রিংগুলির একটি তালিকা হিসাবে প্রকাশ করা হয়েছে।
token_type টোকেনের ধরন ফিরে এসেছে। এই সময়ে, এই ক্ষেত্রের মান সর্বদা Bearer এ সেট করা থাকে।

নিম্নলিখিত স্নিপেট একটি নমুনা প্রতিক্রিয়া দেখায়:

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

ত্রুটি

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

invalid_grant

সরবরাহকৃত অনুমোদন কোডটি অবৈধ বা ভুল বিন্যাসে। ব্যবহারকারীকে আবার সম্মতির জন্য অনুরোধ করার জন্য OAuth প্রক্রিয়া পুনরায় চালু করে একটি নতুন কোডের অনুরোধ করুন।

ধাপ 6: ব্যবহারকারীদের মঞ্জুর করা সুযোগগুলি পরীক্ষা করুন৷

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

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

আরও বিশদ তথ্যের জন্য, দানাদার অনুমতিগুলি কীভাবে পরিচালনা করবেন তা দেখুন।

পিএইচপি

ব্যবহারকারী কোন স্কোপ মঞ্জুর করেছেন তা পরীক্ষা করতে, getGrantedScope() পদ্ধতি ব্যবহার করুন:

// Space-separated string of granted scopes if it exists, otherwise null.
$granted_scopes = $client->getOAuth2Service()->getGrantedScope();

// Determine which scopes user granted and build a dictionary
$granted_scopes_dict = [
  'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
  'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
];

পাইথন

প্রত্যাবর্তিত credentials বস্তুর একটি granted_scopes প্রপার্টি রয়েছে, যা ব্যবহারকারী আপনার অ্যাপে দেওয়া সুযোগগুলির একটি তালিকা।

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,
    'granted_scopes': credentials.granted_scopes}

নিম্নলিখিত ফাংশন ব্যবহারকারী আপনার অ্যাপে কোন স্কোপ মঞ্জুর করেছে তা পরীক্ষা করে।

def check_granted_scopes(credentials):
  features = {}
  if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
    features['drive'] = True
  else:
    features['drive'] = False

  if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
    features['calendar'] = True
  else:
    features['calendar'] = False

  return features

রুবি

একবারে একাধিক স্কোপের অনুরোধ করার সময়, credentials বস্তুর scope বৈশিষ্ট্যের মাধ্যমে কোন স্কোপগুলি মঞ্জুর করা হয়েছে তা পরীক্ষা করুন।

# User authorized the request. Now, check which scopes were granted.
if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
  # User authorized read-only Drive activity permission.
  # Calling the APIs, etc
else
  # User didn't authorize read-only Drive activity permission.
  # Update UX and application accordingly
end

# Check if user authorized Calendar read permission.
if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
  # User authorized Calendar read permission.
  # Calling the APIs, etc.
else
  # User didn't authorize Calendar read permission.
  # Update UX and application accordingly
end

Node.js

একবারে একাধিক স্কোপের অনুরোধ করার সময়, tokens অবজেক্টের scope প্রপার্টির মাধ্যমে কোন স্কোপ মঞ্জুর করা হয়েছে তা পরীক্ষা করে দেখুন।

// User authorized the request. Now, check which scopes were granted.
if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
{
  // User authorized read-only Drive activity permission.
  // Calling the APIs, etc.
}
else
{
  // User didn't authorize read-only Drive activity permission.
  // Update UX and application accordingly
}

// Check if user authorized Calendar read permission.
if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
{
  // User authorized Calendar read permission.
  // Calling the APIs, etc.
}
else
{
  // User didn't authorize Calendar read permission.
  // Update UX and application accordingly
}

HTTP/REST

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

উদাহরণস্বরূপ, নিম্নলিখিত নমুনা অ্যাক্সেস টোকেন প্রতিক্রিয়া ইঙ্গিত করে যে ব্যবহারকারী আপনার অ্যাপ্লিকেশনটিকে শুধুমাত্র-পঠনযোগ্য ড্রাইভ কার্যকলাপ এবং ক্যালেন্ডার ইভেন্ট অনুমতিগুলিতে অ্যাক্সেস দিয়েছেন:

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

Google API কল করুন

পিএইচপি

নিম্নলিখিত ধাপগুলি সম্পূর্ণ করে Google API কল করতে অ্যাক্সেস টোকেন ব্যবহার করুন:

  1. আপনি যদি একটি নতুন Google\Client অবজেক্টে একটি অ্যাক্সেস টোকেন প্রয়োগ করতে চান - উদাহরণস্বরূপ, যদি আপনি একটি ব্যবহারকারীর সেশনে অ্যাক্সেস টোকেন সংরক্ষণ করেন - setAccessToken পদ্ধতি ব্যবহার করুন:
    $client->setAccessToken($access_token);
  2. আপনি যে APIটি কল করতে চান তার জন্য একটি পরিষেবা বস্তু তৈরি করুন। আপনি যে API কল করতে চান তার জন্য কনস্ট্রাক্টরকে একটি অনুমোদিত Google\Client অবজেক্ট প্রদান করে আপনি একটি পরিষেবা বস্তু তৈরি করেন। উদাহরণস্বরূপ, ড্রাইভ API কল করতে:
    $drive = new Google\Service\Drive($client);
  3. সার্ভিস অবজেক্ট দ্বারা প্রদত্ত ইন্টারফেস ব্যবহার করে API পরিষেবাতে অনুরোধ করুন। উদাহরণস্বরূপ, প্রমাণীকৃত ব্যবহারকারীর Google ড্রাইভে ফাইলগুলি তালিকাভুক্ত করতে:
    $files = $drive->files->listFiles(array());

পাইথন

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

  1. আপনি যে APIটি কল করতে চান তার জন্য একটি পরিষেবা বস্তু তৈরি করুন। আপনি API এর নাম এবং সংস্করণ এবং ব্যবহারকারীর শংসাপত্র সহ googleapiclient.discovery লাইব্রেরির build পদ্ধতিতে কল করে একটি পরিষেবা অবজেক্ট তৈরি করেন: উদাহরণস্বরূপ, ড্রাইভ API-এর সংস্করণ 3 কল করতে:
    from googleapiclient.discovery import build
    
    drive = build('drive', 'v2', credentials=credentials)
  2. সার্ভিস অবজেক্ট দ্বারা প্রদত্ত ইন্টারফেস ব্যবহার করে API পরিষেবাতে অনুরোধ করুন। উদাহরণস্বরূপ, প্রমাণীকৃত ব্যবহারকারীর Google ড্রাইভে ফাইলগুলি তালিকাভুক্ত করতে:
    files = drive.files().list().execute()

রুবি

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

  1. আপনি যে APIটি কল করতে চান তার জন্য একটি পরিষেবা বস্তু তৈরি করুন। উদাহরণস্বরূপ, ড্রাইভ API-এর সংস্করণ 3 কল করতে:
    drive = Google::Apis::DriveV3::DriveService.new
  2. পরিষেবাটিতে শংসাপত্রগুলি সেট করুন:
    drive.authorization = credentials
  3. সার্ভিস অবজেক্ট দ্বারা প্রদত্ত ইন্টারফেস ব্যবহার করে API পরিষেবাতে অনুরোধ করুন। উদাহরণস্বরূপ, প্রমাণীকৃত ব্যবহারকারীর Google ড্রাইভে ফাইলগুলি তালিকাভুক্ত করতে:
    files = drive.list_files

বিকল্পভাবে, একটি পদ্ধতিতে options পরামিতি সরবরাহ করে প্রতি-পদ্ধতির ভিত্তিতে অনুমোদন প্রদান করা যেতে পারে:

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

Node.js

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

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

আপনার অ্যাপ্লিকেশন একটি অ্যাক্সেস টোকেন প্রাপ্ত করার পরে, যদি API দ্বারা প্রয়োজনীয় অ্যাক্সেসের সুযোগ মঞ্জুর করা হয় তবে আপনি একটি প্রদত্ত ব্যবহারকারী অ্যাকাউন্টের হয়ে একটি Google API এ কল করতে টোকেনটি ব্যবহার করতে পারেন। এটি করার জন্য, একটি access_token ক্যোয়ারী প্যারামিটার বা একটি Authorization HTTP শিরোনাম Bearer মান অন্তর্ভুক্ত করে API-এর একটি অনুরোধে অ্যাক্সেস টোকেন অন্তর্ভুক্ত করুন। যখন সম্ভব, HTTP শিরোনামটি পছন্দনীয়, কারণ সার্ভার লগগুলিতে কোয়েরি স্ট্রিংগুলি দৃশ্যমান হয়। বেশিরভাগ ক্ষেত্রে আপনি Google API-এ আপনার কলগুলি সেট আপ করতে একটি ক্লায়েন্ট লাইব্রেরি ব্যবহার করতে পারেন (উদাহরণস্বরূপ, ড্রাইভ ফাইল API কল করার সময়)।

আপনি সমস্ত Google API ব্যবহার করে দেখতে পারেন এবং OAuth 2.0 খেলার মাঠে তাদের স্কোপ দেখতে পারেন।

HTTP GET উদাহরণ

অনুমোদনের ব্যবহার করে drive.files এন্ডপয়েন্ট (ড্রাইভ ফাইলগুলি এপিআই) এ একটি কল Authorization: Bearer এইচটিটিপি শিরোনামটি নিম্নলিখিতগুলির মতো দেখতে পারে। নোট করুন যে আপনার নিজের অ্যাক্সেস টোকেন নির্দিষ্ট করতে হবে:

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

access_token ক্যোয়ারী স্ট্রিং প্যারামিটারটি ব্যবহার করে প্রমাণীকরণ করা ব্যবহারকারীর জন্য একই এপিআইয়ের কাছে এখানে একটি কল রয়েছে:

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

curl উদাহরণ

আপনি এই কমান্ডগুলি curl কমান্ড-লাইন অ্যাপ্লিকেশন দিয়ে পরীক্ষা করতে পারেন। এখানে একটি উদাহরণ যা এইচটিটিপি শিরোনাম বিকল্পটি ব্যবহার করে (পছন্দসই):

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

বা, বিকল্পভাবে, ক্যোয়ারী স্ট্রিং প্যারামিটার বিকল্প:

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

সম্পূর্ণ উদাহরণ

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

পিএইচপি

এই উদাহরণ চালানোর জন্য:

  1. মধ্যে API Console, স্থানীয় মেশিনের URL টি পুনর্নির্দেশের ইউআরএলগুলির তালিকায় যুক্ত করুন। উদাহরণস্বরূপ, http://localhost:8080 যুক্ত করুন।
  2. একটি নতুন ডিরেক্টরি তৈরি করুন এবং এটিতে পরিবর্তন করুন। যেমন:
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. সুরকার ব্যবহার করে পিএইচপি -র জন্য গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ইনস্টল করুন:
    composer require google/apiclient:^2.15.0
  4. নিম্নলিখিত সামগ্রী সহ ফাইলগুলি index.php এবং oauth2callback.php তৈরি করুন।
  5. পিএইচপি-র অন্তর্নির্মিত টেস্ট ওয়েব সার্ভারের সাথে উদাহরণটি চালান:
    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_secret.json');

// User granted permission as an access token is in the session.
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
  $client->setAccessToken($_SESSION['access_token']);
  
  // Check if user granted Drive permission
  if ($_SESSION['granted_scopes_dict']['Drive']) {
    echo "Drive feature is enabled.";
    echo "</br>";
    $drive = new Drive($client);
    $files = array();
    $response = $drive->files->listFiles(array());
    foreach ($response->files as $file) {
        echo "File: " . $file->name . " (" . $file->id . ")";
        echo "</br>";
    }
  } else {
    echo "Drive feature is NOT enabled.";
    echo "</br>";
  }

   // Check if user granted Calendar permission
  if ($_SESSION['granted_scopes_dict']['Calendar']) {
    echo "Calendar feature is enabled.";
    echo "</br>";
  } else {
    echo "Calendar feature is NOT enabled.";
    echo "</br>";
  }
}
else
{
  // Redirect users to outh2call.php which redirects users to Google OAuth 2.0
  $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();

// Required, call the setAuthConfig function to load authorization credentials from
// client_secret.json file.
$client->setAuthConfigFile('client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);

// Required, to set the scope value, call the addScope function.
$client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);

// Enable incremental authorization. Recommended as a best practice.
$client->setIncludeGrantedScopes(true);

// Recommended, 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");

// Generate a URL for authorization as it doesn't contain code and error
if (!isset($_GET['code']) && !isset($_GET['error']))
{
  // Generate and set state value
  $state = bin2hex(random_bytes(16));
  $client->setState($state);
  $_SESSION['state'] = $state;

  // Generate a url that asks permissions.
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}

// User authorized the request and authorization code is returned to exchange access and
// refresh tokens.
if (isset($_GET['code']))
{
  // Check the state value
  if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
    die('State mismatch. Possible CSRF attack.');
  }

  // Get access and refresh tokens (if access_type is offline)
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

  /** Save access and refresh token to the session variables.
    * ACTION ITEM: In a production app, you likely want to save the
    *              refresh token in a secure persistent storage instead. */
  $_SESSION['access_token'] = $token;
  $_SESSION['refresh_token'] = $client->getRefreshToken();
  
  // Space-separated string of granted scopes if it exists, otherwise null.
  $granted_scopes = $client->getOAuth2Service()->getGrantedScope();

  // Determine which scopes user granted and build a dictionary
  $granted_scopes_dict = [
    'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
    'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
  ];
  $_SESSION['granted_scopes_dict'] = $granted_scopes_dict;
  
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

// An error response e.g. error=access_denied
if (isset($_GET['error']))
{
  echo "Error: ". $_GET['error'];
}
?>

পাইথন

এই উদাহরণটি ফ্লাস্ক ফ্রেমওয়ার্ক ব্যবহার করে। এটি http://localhost:8080 এ একটি ওয়েব অ্যাপ্লিকেশন চালায় যা আপনাকে OAuth 2.0 প্রবাহ পরীক্ষা করতে দেয়। আপনি যদি সেই ইউআরএলে যান তবে আপনার পাঁচটি লিঙ্ক দেখা উচিত:

  • কল ড্রাইভ এপিআই: এই লিঙ্কটি এমন একটি পৃষ্ঠায় নির্দেশ করে যা ব্যবহারকারীরা অনুমতি প্রদান করে তবে একটি নমুনা এপিআই অনুরোধ কার্যকর করার চেষ্টা করে। যদি প্রয়োজন হয় তবে এটি অনুমোদনের প্রবাহ শুরু করে। সফল হলে, পৃষ্ঠাটি এপিআই প্রতিক্রিয়া প্রদর্শন করে।
  • ক্যালেন্ডার এপিআই কল করার জন্য মক পৃষ্ঠা: এই লিঙ্কটি এমন একটি মওকপেজের দিকে নির্দেশ করে যা ব্যবহারকারীরা অনুমতি প্রদান করে তবে একটি নমুনা ক্যালেন্ডার এপিআই অনুরোধ কার্যকর করার চেষ্টা করে। যদি প্রয়োজন হয় তবে এটি অনুমোদনের প্রবাহ শুরু করে। সফল হলে, পৃষ্ঠাটি এপিআই প্রতিক্রিয়া প্রদর্শন করে।
  • লেখক প্রবাহকে সরাসরি পরীক্ষা করুন: এই লিঙ্কটি এমন একটি পৃষ্ঠায় নির্দেশ করে যা অনুমোদনের প্রবাহের মাধ্যমে ব্যবহারকারীকে প্রেরণের চেষ্টা করে। অ্যাপ্লিকেশনটি ব্যবহারকারীর পক্ষে অনুমোদিত এপিআই অনুরোধ জমা দেওয়ার অনুমতি অনুরোধ করে।
  • বর্তমান শংসাপত্রগুলি প্রত্যাহার করুন: এই লিঙ্কটি এমন একটি পৃষ্ঠায় নির্দেশ করে যা ব্যবহারকারী ইতিমধ্যে অ্যাপ্লিকেশনটিতে মঞ্জুর করেছে এমন অনুমতিগুলি প্রত্যাহার করে
  • ফ্লাস্ক সেশন শংসাপত্রগুলি সাফ করুন: এই লিঙ্কটি ফ্লাস্ক সেশনে সঞ্চিত অনুমোদনের শংসাপত্রগুলি সাফ করে। এটি আপনাকে দেখতে দেয় যে যদি কোনও ব্যবহারকারী ইতিমধ্যে আপনার অ্যাপকে অনুমতি দেয় এমন কোনও ব্যবহারকারী যদি নতুন সেশনে একটি API অনুরোধ কার্যকর করার চেষ্টা করে তবে কী হবে। এটি আপনাকে আপনার অ্যাপ্লিকেশনটিকে যদি কোনও ব্যবহারকারী আপনার অ্যাপকে মঞ্জুরিপ্রাপ্ত অনুমতি প্রত্যাহার করে নেয় এবং আপনার অ্যাপ্লিকেশনটি এখনও বাতিল হওয়া অ্যাক্সেস টোকেন সহ একটি অনুরোধ অনুমোদনের চেষ্টা করার চেষ্টা করে তবে এটি আপনাকে এপিআই প্রতিক্রিয়াটি দেখতে দেয়।
# -*- 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"

# The OAuth 2.0 access scope allows for access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
          'https://www.googleapis.com/auth/calendar.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('/drive')
def drive_api_request():
  if 'credentials' not in flask.session:
    return flask.redirect('authorize')

  features = flask.session['features']

  if features['drive']:
    # 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)
  else:
    # User didn't authorize read-only Drive activity permission.
    # Update UX and application accordingly
    return '<p>Drive feature is not enabled.</p>'

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

      features = flask.session['features']

      if features['calendar']:
        # User authorized Calendar read permission.
        # Calling the APIs, etc.
        return ('<p>User granted the Google Calendar read permission. '+
                'This sample code does not include code to call Calendar</p>')
      else:
        # User didn't authorize Calendar read permission.
        # Update UX and application accordingly
        return '<p>Calendar feature is not enabled.</p>'

@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
  
  credentials = credentials_to_dict(credentials)
  flask.session['credentials'] = credentials

  # Check which scopes user granted
  features = check_granted_scopes(credentials)
  flask.session['features'] = features
  return flask.redirect('/')
  

@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,
          'granted_scopes': credentials.granted_scopes}

def check_granted_scopes(credentials):
  features = {}
  if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
    features['drive'] = True
  else:
    features['drive'] = False

  if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
    features['calendar'] = True
  else:
    features['calendar'] = False

  return features

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'

  # This disables the requested scopes and granted scopes check.
  # If users only grant partial request, the warning would not be thrown.
  os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '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)

রুবি

এই উদাহরণটি সিনেট্রা ফ্রেমওয়ার্ক ব্যবহার করে।

require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'

require 'google/apis/drive_v3'
require 'google/apis/calendar_v3'

require 'sinatra'

configure do
  enable :sessions

  # Required, call the from_file method to retrieve the client ID from a
  # client_secret.json file.
  set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json')

  # Required, scope value
  # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
  scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
           'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']

  # Required, Authorizers require a storage instance to manage long term persistence of
  # access and refresh tokens.
  set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)

  # Required, 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.
  set :callback_uri, '/oauth2callback'

  # 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.
  set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope,
                          settings.token_store, callback_uri: settings.callback_uri)
end

get '/' do
  # NOTE: Assumes the user is already authenticated to the app
  user_id = request.session['user_id']

  # Fetch stored credentials for the user from the given request session.
  # nil if none present
  credentials = settings.authorizer.get_credentials(user_id, request)

  if credentials.nil?
    # Generate a url that asks the user to authorize requested scope(s).
    # Then, redirect user to the url.
    redirect settings.authorizer.get_authorization_url(request: request)
  end
  
  # User authorized the request. Now, check which scopes were granted.
  if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
    # User authorized read-only Drive activity permission.
    # Example of using Google Drive API to list filenames in user's Drive.
    drive = Google::Apis::DriveV3::DriveService.new
    files = drive.list_files(options: { authorization: credentials })
    "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
  else
    # User didn't authorize read-only Drive activity permission.
    # Update UX and application accordingly
  end

  # Check if user authorized Calendar read permission.
  if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
    # User authorized Calendar read permission.
    # Calling the APIs, etc.
  else
    # User didn't authorize Calendar read permission.
    # Update UX and application accordingly
  end
end

# Receive the callback from Google's OAuth 2.0 server.
get '/oauth2callback' do
  # Handle the result of the oauth callback. Defers the exchange of the code by
  # temporarily stashing the results in the user's session.
  target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
  redirect target_url
end

Node.js

এই উদাহরণ চালানোর জন্য:

  1. মধ্যে API Console, স্থানীয় মেশিনের URL টি পুনর্নির্দেশের ইউআরএলগুলির তালিকায় যুক্ত করুন। উদাহরণস্বরূপ, http://localhost যুক্ত করুন।
  2. আপনার রক্ষণাবেক্ষণ এলটিএস, সক্রিয় এলটিএস, বা নোড.জেএস ইনস্টল করা বর্তমান রিলিজ রয়েছে তা নিশ্চিত করুন।
  3. একটি নতুন ডিরেক্টরি তৈরি করুন এবং এটিতে পরিবর্তন করুন। যেমন:
    mkdir ~/nodejs-oauth2-example
    cd ~/nodejs-oauth2-example
  4. এনপিএম ব্যবহার করে নোড.জেএসের জন্য গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ইনস্টল করুন:
    npm install googleapis
  5. নিম্নলিখিত সামগ্রী সহ ফাইলগুলি main.js তৈরি করুন।
  6. উদাহরণ চালান:
    node .\main.js

main.js

const http = require('http');
const https = require('https');
const url = require('url');
const { google } = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');

/**
 * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly',
  'https://www.googleapis.com/auth/calendar.readonly'
];

/* 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 app = express();

  app.use(session({
    secret: 'your_secure_secret_key', // Replace with a strong secret
    resave: false,
    saveUninitialized: false,
  }));

  // Example on redirecting user to Google's OAuth 2.0 server.
  app.get('/', async (req, res) => {
    // Generate a secure random state value.
    const state = crypto.randomBytes(32).toString('hex');
    // Store state in the session
    req.session.state = state;

    // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
      // Include the state parameter to reduce the risk of CSRF attacks.
      state: state
    });

    res.redirect(authorizationUrl);
  });

  // Receive the callback from Google's OAuth 2.0 server.
  app.get('/oauth2callback', async (req, res) => {
    // 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 if (q.state !== req.session.state) { //check state value
      console.log('State mismatch. Possible CSRF attack');
      res.end('State mismatch. Possible CSRF attack');
    } 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;
      
      // User authorized the request. Now, check which scopes were granted.
      if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
      {
        // User authorized read-only Drive activity permission.
        // 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.');
          }
        });
      }
      else
      {
        // User didn't authorize read-only Drive activity permission.
        // Update UX and application accordingly
      }

      // Check if user authorized Calendar read permission.
      if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
      {
        // User authorized Calendar read permission.
        // Calling the APIs, etc.
      }
      else
      {
        // User didn't authorize Calendar read permission.
        // Update UX and application accordingly
      }
    }
  });

  // Example on revoking a token
  app.get('/revoke', async (req, res) => {
    // 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();
  });


  const server = http.createServer(app);
  server.listen(8080);
}
main().catch(console.error);

HTTP/REST

এই পাইথন উদাহরণটি OAuth 2.0 ওয়েব প্রবাহ প্রদর্শনের জন্য ফ্লাস্ক ফ্রেমওয়ার্ক এবং অনুরোধ লাইব্রেরি ব্যবহার করে। আমরা এই প্রবাহের জন্য পাইথনের জন্য গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ব্যবহার করার পরামর্শ দিই। (পাইথন ট্যাবে উদাহরণটি ক্লায়েন্ট লাইব্রেরি ব্যবহার করে))

import json
import flask
import requests

app = flask.Flask(__name__)

# To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit
# https://console.cloud.google.com/apis/credentials.
CLIENT_ID = '123456789.apps.googleusercontent.com'
CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app

# Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.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.
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: 
    # User authorized the request. Now, check which scopes were granted.
    if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']:
      # User authorized read-only Drive activity permission.
      # Example of using Google Drive API to list filenames in user's Drive.
      headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
      req_uri = 'https://www.googleapis.com/drive/v2/files'
      r = requests.get(req_uri, headers=headers).text
    else:
      # User didn't authorize read-only Drive activity permission.
      # Update UX and application accordingly
      r = 'User did not authorize Drive permission.'

    # Check if user authorized Calendar read permission.
    if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']:
      # User authorized Calendar read permission.
      # Calling the APIs, etc.
      r += 'User authorized Calendar permission.'
    else:
      # User didn't authorize Calendar read permission.
      # Update UX and application accordingly
      r += 'User did not authorize Calendar permission.'

  return r

@app.route('/oauth2callback')
def oauth2callback():
  if 'code' not in flask.request.args:
    state = str(uuid.uuid4())
    flask.session['state'] = state
    # Generate a url that asks permissions for the Drive activity
    # and Google Calendar scope. Then, redirect user to the url.
    auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
                                                                          SCOPE, state)
    return flask.redirect(auth_uri)
  else:
    if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
      return 'State mismatch. Possible CSRF attack.', 400

    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'}

    # Exchange authorization code for access and refresh tokens (if access_type is offline)
    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()

ইউআরআই বৈধতা বিধি পুনর্নির্দেশ

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

বৈধতা নিয়ম
স্কিম

পুনর্নির্দেশের ইউআরআইএস অবশ্যই এইচটিটিপিএস স্কিমটি ব্যবহার করতে হবে, সাধারণ এইচটিটিপি নয়। লোকালহোস্ট ইউআরআই (লোকালহোস্ট আইপি ঠিকানা ইউআরআই সহ) এই বিধি থেকে অব্যাহতিপ্রাপ্ত।

হোস্ট

হোস্টগুলি কাঁচা আইপি ঠিকানা হতে পারে না। লোকালহোস্ট আইপি ঠিকানাগুলি এই নিয়ম থেকে অব্যাহতিপ্রাপ্ত।

ডোমেইন
  • হোস্ট টিএলডিএস ( শীর্ষ স্তরের ডোমেন ) অবশ্যই পাবলিক প্রত্যয় তালিকার অন্তর্ভুক্ত।
  • হোস্ট ডোমেনগুলি “googleusercontent.com” হতে পারে না।
  • পুনর্নির্দেশের ইউআরআইএসে ইউআরএল শর্টনার ডোমেনগুলি (যেমন goo.gl ) থাকতে পারে না যদি না অ্যাপ্লিকেশনটি ডোমেনের মালিক না হয়। তদ্ব্যতীত, যদি কোনও শর্টেনার ডোমেনের মালিকানাধীন কোনও অ্যাপ্লিকেশন সেই ডোমেনে পুনর্নির্দেশ করতে পছন্দ করে, তবে পুনর্নির্দেশের ইউআরআইকে অবশ্যই তার পথে “/google-callback/” থাকতে হবে বা “/google-callback” দিয়ে শেষ করতে হবে।
  • ব্যবহারকারীর তথ্য

    পুনর্নির্দেশের ইউআরআইএস ব্যবহারকারী আইএনএফও সাবকম্পোনেন্ট থাকতে পারে না।

    পথ

    পুনর্নির্দেশ ইউআরআইএসে কোনও পাথ ট্র্যাভারসাল থাকতে পারে না (ডিরেক্টরি ব্যাকট্র্যাকিংও বলা হয়), যা একটি “/..” বা “\..” বা তাদের ইউআরএল এনকোডিং দ্বারা প্রতিনিধিত্ব করা হয়।

    প্রশ্ন

    পুনর্নির্দেশ ইউআরআইএসে খোলা পুনঃনির্দেশগুলি থাকতে পারে না।

    খণ্ড

    পুনর্নির্দেশের ইউআরআইএস খণ্ডের উপাদান থাকতে পারে না।

    অক্ষর পুনর্নির্দেশ ইউআরআইএস সহ নির্দিষ্ট অক্ষর থাকতে পারে না:
    • ওয়াইল্ডকার্ড অক্ষর ( '*' )
    • প্রিন্টেবল এএসসিআইআই অক্ষর
    • অবৈধ শতাংশ এনকোডিংস (যে কোনও শতাংশ এনকোডিং যা URL-encoding ফর্মটি শতাংশের চিহ্ন অনুসরণ করে না এবং তারপরে দুটি হেক্সাডেসিমাল সংখ্যা অনুসরণ করে)
    • নাল অক্ষর (একটি এনকোডেড নাল চরিত্র, যেমন, %00 , %C0%80 )

    ক্রমবর্ধমান অনুমোদন

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

    উদাহরণস্বরূপ, এমন একটি অ্যাপ্লিকেশন যা লোককে সঙ্গীত ট্র্যাকগুলি নমুনা করতে দেয় এবং মিশ্রণগুলি তৈরি করতে দেয় সাইন-ইন সময়ে খুব কম সংস্থান প্রয়োজন হতে পারে, সম্ভবত সাইন ইন করা ব্যক্তির নাম ছাড়া আর কিছুই হতে পারে না However তবে, একটি সম্পূর্ণ মিশ্রণ সংরক্ষণের জন্য তাদের গুগল ড্রাইভে অ্যাক্সেসের প্রয়োজন হবে। বেশিরভাগ লোকেরা যদি এটি কেবলমাত্র তাদের গুগল ড্রাইভে অ্যাক্সেসের জন্য জিজ্ঞাসা করা হয় তবে অ্যাপ্লিকেশনটির আসলে এটির প্রয়োজন ছিল।

    এই ক্ষেত্রে, সাইন-ইন টাইমে অ্যাপ্লিকেশনটি openid এবং profile স্কোপগুলিকে বেসিক সাইন-ইন করার জন্য অনুরোধ করতে পারে এবং পরে মিশ্রণটি সংরক্ষণের জন্য প্রথম অনুরোধের সময় https://www.googleapis.com/auth/drive.file স্কোপ অনুরোধ করুন।

    ইনক্রিমেন্টাল অনুমোদন বাস্তবায়নের জন্য, আপনি অ্যাক্সেস টোকেনের জন্য অনুরোধ করার জন্য স্বাভাবিক প্রবাহটি সম্পূর্ণ করেছেন তবে নিশ্চিত করুন যে অনুমোদনের অনুরোধে পূর্বে মঞ্জুর করা স্কোপগুলি অন্তর্ভুক্ত রয়েছে। এই পদ্ধতির ফলে আপনার অ্যাপ্লিকেশনটি একাধিক অ্যাক্সেস টোকেন পরিচালনা করতে এড়াতে দেয়।

    নিম্নলিখিত নিয়মগুলি বর্ধিত অনুমোদন থেকে প্রাপ্ত অ্যাক্সেস টোকেনের ক্ষেত্রে প্রযোজ্য:

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

    পদক্ষেপ 1 এ ভাষা-নির্দিষ্ট কোডের নমুনাগুলি: অনুমোদনের পরামিতিগুলি সেট করুন এবং নমুনা এইচটিটিপি/বিশ্রামের পুনর্নির্দেশের ইউআরএল 2 ধাপে: গুগলের OAuth 2.0 সার্ভারে পুনঃনির্দেশ করুন সমস্ত ইনক্রিমেন্টাল অনুমোদন ব্যবহার করুন। নীচের কোডের নমুনাগুলি এমন কোডটিও দেখায় যা আপনাকে বর্ধিত অনুমোদনের জন্য যুক্ত করতে হবে।

    পিএইচপি

    $client->setIncludeGrantedScopes(true);

    পাইথন

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

    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.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly&
      redirect_uri=https%3A//oauth2.example.com/code&
      prompt=consent&
      include_granted_scopes=true

    একটি অ্যাক্সেস টোকেন রিফ্রেশ করা (অফলাইন অ্যাক্সেস)

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

    • আপনি যদি কোনও গুগল এপিআই ক্লায়েন্ট লাইব্রেরি ব্যবহার করেন তবে ক্লায়েন্ট অবজেক্টটি যতক্ষণ না আপনি অফলাইন অ্যাক্সেসের জন্য সেই অবজেক্টটি কনফিগার করেন ততক্ষণ অ্যাক্সেস টোকেনটি রিফ্রেশ করে।
    • আপনি যদি কোনও ক্লায়েন্ট লাইব্রেরি ব্যবহার না করে থাকেন তবে গুগলের ওএউথ ২.০ সার্ভারে ব্যবহারকারীকে পুনর্নির্দেশ করার সময় আপনাকে access_type এইচটিটিপি ক্যোয়ারী প্যারামিটারটি offline সেট করতে হবে। সেক্ষেত্রে, আপনি যখন অ্যাক্সেস টোকেনের জন্য কোনও অনুমোদনের কোড বিনিময় করেন তখন গুগলের অনুমোদনের সার্ভার একটি রিফ্রেশ টোকেন ফেরত দেয়। তারপরে, যদি অ্যাক্সেস টোকেনটির মেয়াদ শেষ হয় (বা অন্য কোনও সময়ে), আপনি নতুন অ্যাক্সেস টোকেন পেতে একটি রিফ্রেশ টোকেন ব্যবহার করতে পারেন।

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

    সার্ভার-সাইড ওয়েব অ্যাপ্লিকেশনগুলি, ইনস্টলড অ্যাপ্লিকেশনগুলি এবং ডিভাইসগুলি সমস্ত অনুমোদনের প্রক্রিয়া চলাকালীন রিফ্রেশ টোকেন গ্রহণ করে। রিফ্রেশ টোকেনগুলি সাধারণত ক্লায়েন্ট-সাইড (জাভাস্ক্রিপ্ট) ওয়েব অ্যাপ্লিকেশনগুলিতে ব্যবহৃত হয় না।

    পিএইচপি

    যদি আপনার অ্যাপ্লিকেশনটির কোনও গুগল এপিআইতে অফলাইন অ্যাক্সেসের প্রয়োজন হয় তবে এপিআই ক্লায়েন্টের অ্যাক্সেস প্রকারটি offline সেট করুন:

    $client->setAccessType("offline");

    কোনও ব্যবহারকারী অনুরোধ করা স্কোপগুলিতে অফলাইনে অ্যাক্সেস মঞ্জুর করার পরে, ব্যবহারকারী অফলাইনে থাকাকালীন আপনি ব্যবহারকারীর পক্ষে গুগল এপিআইগুলিতে অ্যাক্সেস করতে এপিআই ক্লায়েন্টকে ব্যবহার চালিয়ে যেতে পারেন। ক্লায়েন্ট অবজেক্টটি প্রয়োজন অনুসারে অ্যাক্সেস টোকেনটি রিফ্রেশ করবে।

    পাইথন

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

    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')

    কোনও ব্যবহারকারী অনুরোধ করা স্কোপগুলিতে অফলাইনে অ্যাক্সেস মঞ্জুর করার পরে, ব্যবহারকারী অফলাইনে থাকাকালীন আপনি ব্যবহারকারীর পক্ষে গুগল এপিআইগুলিতে অ্যাক্সেস করতে এপিআই ক্লায়েন্টকে ব্যবহার চালিয়ে যেতে পারেন। ক্লায়েন্ট অবজেক্টটি প্রয়োজন অনুসারে অ্যাক্সেস টোকেনটি রিফ্রেশ করবে।

    রুবি

    যদি আপনার অ্যাপ্লিকেশনটির কোনও গুগল এপিআইতে অফলাইন অ্যাক্সেসের প্রয়োজন হয় তবে এপিআই ক্লায়েন্টের অ্যাক্সেস প্রকারটি offline সেট করুন:

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

    কোনও ব্যবহারকারী অনুরোধ করা স্কোপগুলিতে অফলাইনে অ্যাক্সেস মঞ্জুর করার পরে, ব্যবহারকারী অফলাইনে থাকাকালীন আপনি ব্যবহারকারীর পক্ষে গুগল এপিআইগুলিতে অ্যাক্সেস করতে এপিআই ক্লায়েন্টকে ব্যবহার চালিয়ে যেতে পারেন। ক্লায়েন্ট অবজেক্টটি প্রয়োজন অনুসারে অ্যাক্সেস টোকেনটি রিফ্রেশ করবে।

    Node.js

    যদি আপনার অ্যাপ্লিকেশনটির কোনও গুগল এপিআইতে অফলাইন অ্যাক্সেসের প্রয়োজন হয় তবে এপিআই ক্লায়েন্টের অ্যাক্সেস প্রকারটি 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
    });

    কোনও ব্যবহারকারী অনুরোধ করা স্কোপগুলিতে অফলাইনে অ্যাক্সেস মঞ্জুর করার পরে, ব্যবহারকারী অফলাইনে থাকাকালীন আপনি ব্যবহারকারীর পক্ষে গুগল এপিআইগুলিতে অ্যাক্সেস করতে এপিআই ক্লায়েন্টকে ব্যবহার চালিয়ে যেতে পারেন। ক্লায়েন্ট অবজেক্টটি প্রয়োজন অনুসারে অ্যাক্সেস টোকেনটি রিফ্রেশ করবে।

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

    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);
    });

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

    পরবর্তী সময়ে refresh_token সেট করতে, আপনি setCredentials পদ্ধতি ব্যবহার করতে পারেন:

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

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

    HTTP/REST

    অ্যাক্সেস টোকেন রিফ্রেশ করতে, আপনার অ্যাপ্লিকেশনটি গুগলের অনুমোদনের সার্ভারে ( https://oauth2.googleapis.com/token ) একটি এইচটিটিপিএস POST অনুরোধ প্রেরণ করে যা নিম্নলিখিত পরামিতিগুলি অন্তর্ভুক্ত করে:

    ক্ষেত্র
    client_id ক্লায়েন্ট আইডি থেকে প্রাপ্ত API Console.
    client_secret ক্লায়েন্ট সিক্রেট থেকে প্রাপ্ত API Console.
    grant_type OAuth 2.0 স্পেসিফিকেশন হিসাবে সংজ্ঞায়িত হিসাবে, এই ক্ষেত্রের মানটি refresh_token সেট করতে হবে।
    refresh_token রিফ্রেশ টোকেন অনুমোদন কোড এক্সচেঞ্জ থেকে ফিরে এসেছিল।

    নিম্নলিখিত স্নিপেট একটি নমুনা অনুরোধ দেখায়:

    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

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

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

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

    একটি টোকেন প্রত্যাহার করা

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

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

    পিএইচপি

    প্রোগ্রামে একটি টোকেন প্রত্যাহার করতে, revokeToken() :

    $client->revokeToken();

    পাইথন

    প্রোগ্রামিকভাবে একটি টোকেন প্রত্যাহার করতে, https://oauth2.googleapis.com/revoke এ একটি অনুরোধ করুন যাতে টোকেনকে একটি প্যারামিটার হিসাবে অন্তর্ভুক্ত করা হয় এবং Content-Type শিরোনাম সেট করে:

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

    রুবি

    প্রোগ্রামে একটি টোকেন প্রত্যাহার করতে, oauth2.revoke শেষ পয়েন্টে একটি HTTP অনুরোধ করুন:

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

    টোকেন অ্যাক্সেস টোকেন বা রিফ্রেশ টোকেন হতে পারে। যদি টোকেনটি অ্যাক্সেস টোকেন হয় এবং এটির সাথে সম্পর্কিত রিফ্রেশ টোকেন থাকে তবে রিফ্রেশ টোকেনটিও বাতিল করা হবে।

    যদি প্রত্যাহারটি সফলভাবে প্রক্রিয়া করা হয়, তবে প্রতিক্রিয়ার স্থিতি কোডটি 200 । ত্রুটির শর্তগুলির জন্য, একটি স্ট্যাটাস কোড 400 একটি ত্রুটি কোড সহ ফিরে আসে।

    Node.js

    প্রোগ্রামে একটি টোকেন প্রত্যাহার করতে, একটি এইচটিটিপিএস পোস্টের অনুরোধটি /revoke এন্ডপয়েন্টে তৈরি করুন:

    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();

    টোকেন প্যারামিটারটি অ্যাক্সেস টোকেন বা রিফ্রেশ টোকেন হতে পারে। যদি টোকেনটি অ্যাক্সেস টোকেন হয় এবং এটির সাথে সম্পর্কিত রিফ্রেশ টোকেন থাকে তবে রিফ্রেশ টোকেনটিও বাতিল করা হবে।

    যদি প্রত্যাহারটি সফলভাবে প্রক্রিয়া করা হয়, তবে প্রতিক্রিয়ার স্থিতি কোডটি 200 । ত্রুটির শর্তগুলির জন্য, একটি স্ট্যাটাস কোড 400 একটি ত্রুটি কোড সহ ফিরে আসে।

    HTTP/REST

    প্রোগ্রামে একটি টোকেন প্রত্যাহার করতে, আপনার অ্যাপ্লিকেশনটি https://oauth2.googleapis.com/revoke এ একটি অনুরোধ করে এবং প্যারামিটার হিসাবে টোকেনকে অন্তর্ভুক্ত করে:

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

    টোকেন অ্যাক্সেস টোকেন বা রিফ্রেশ টোকেন হতে পারে। যদি টোকেনটি অ্যাক্সেস টোকেন হয় এবং এটির সাথে সম্পর্কিত রিফ্রেশ টোকেন থাকে তবে রিফ্রেশ টোকেনটিও বাতিল করা হবে।

    যদি প্রত্যাহারটি সফলভাবে প্রক্রিয়া করা হয়, তবে প্রতিক্রিয়ার HTTP স্থিতি কোড 200 । ত্রুটির শর্তগুলির জন্য, একটি এইচটিটিপি স্থিতি কোড 400 একটি ত্রুটি কোড সহ ফিরে আসে।

    সময়-ভিত্তিক অ্যাক্সেস

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

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

    ক্রস-অ্যাকাউন্ট সুরক্ষা বাস্তবায়ন

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

    গুগলের ক্রস-অ্যাকাউন্ট সুরক্ষা পরিষেবা দ্বারা আপনার অ্যাপে প্রেরিত ইভেন্টের ধরণের কয়েকটি উদাহরণ হ'ল:

    • https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
    • https://schemas.openid.net/secevent/oauth/event-type/token-revoked
    • https://schemas.openid.net/secevent/risc/event-type/account-disabled

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

    ,

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

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

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

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

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

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

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

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

    পূর্বশর্ত

    আপনার প্রকল্পের জন্য এপিআই সক্ষম করুন

    যে কোনও অ্যাপ্লিকেশন যা গুগল এপিআইকে কল করে তাদের মধ্যে সেই এপিআইগুলি সক্ষম করতে হবে API Console.

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

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

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

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

    1. Go to the Credentials page.
    2. ক্লায়েন্ট তৈরি ক্লিক করুন।
    3. ওয়েব অ্যাপ্লিকেশন অ্যাপ্লিকেশন প্রকার নির্বাচন করুন.
    4. ফর্মটি পূরণ করুন এবং তৈরি ক্লিক করুন। পিএইচপি, জাভা, পাইথন, রুবি এবং .NET এর মতো ভাষা এবং ফ্রেমওয়ার্ক ব্যবহার করে এমন অ্যাপ্লিকেশনগুলি অবশ্যই অনুমোদিত পুনঃনির্দেশ ইউআরআইএস নির্দিষ্ট করতে হবে। পুনঃনির্দেশিত ইউআরআইগুলি হ'ল এন্ডপয়েন্টগুলি যেখানে OAuth 2.0 সার্ভার প্রতিক্রিয়া প্রেরণ করতে পারে। এই শেষ পয়েন্টগুলি অবশ্যই গুগলের বৈধতা বিধি মেনে চলতে হবে।

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

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

    আপনার শংসাপত্রগুলি তৈরি করার পরে, ক্লায়েন্ট_সেক্রেট.জসন ফাইলটি থেকে ডাউনলোড করুন API Console. নিরাপদে ফাইলটি এমন কোনও স্থানে সংরক্ষণ করুন যা কেবলমাত্র আপনার অ্যাপ্লিকেশন অ্যাক্সেস করতে পারে।

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

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

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

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

    OAuth 2.0 এপিআই স্কোপস ডকুমেন্টে স্কোপগুলির একটি সম্পূর্ণ তালিকা রয়েছে যা আপনি গুগল এপিআইগুলিতে অ্যাক্সেস করতে ব্যবহার করতে পারেন।

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

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

    পিএইচপি

    এই দস্তাবেজে পিএইচপি কোডের নমুনাগুলি চালানোর জন্য আপনার প্রয়োজন:

    • কমান্ড-লাইন ইন্টারফেস (সিএলআই) এবং জেএসএন এক্সটেনশন ইনস্টল সহ পিএইচপি 8.0 বা তার বেশি।
    • সুরকার নির্ভরতা পরিচালনার সরঞ্জাম।
    • পিএইচপি -র জন্য গুগল এপিআইএস ক্লায়েন্ট লাইব্রেরি:

      composer require google/apiclient:^2.15.0

    আরও তথ্যের জন্য পিএইচপির জন্য গুগল এপিআইএস ক্লায়েন্ট লাইব্রেরি দেখুন।

    পাইথন

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

    • পাইথন 3.7 বা তার বেশি
    • পিআইপি প্যাকেজ পরিচালনার সরঞ্জাম।
    • পাইথন ২.০ প্রকাশের জন্য গুগল এপিআইএস ক্লায়েন্ট লাইব্রেরি:
      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.6 বা তার বেশি
    • রুবির জন্য গুগল এথ লাইব্রেরি:

      gem install googleauth
    • ড্রাইভ এবং ক্যালেন্ডার গুগল এপিআইগুলির জন্য ক্লায়েন্ট লাইব্রেরি:

      gem install google-apis-drive_v3 google-apis-calendar_v3
    • সিনেট্রা রুবি ওয়েব অ্যাপ্লিকেশন কাঠামো।

      gem install sinatra

    Node.js

    এই দস্তাবেজে নোড.জেএস কোডের নমুনাগুলি চালানোর জন্য আপনার প্রয়োজন:

    • রক্ষণাবেক্ষণ এলটিএস, সক্রিয় এলটিএস, বা নোড.জেএস এর বর্তমান প্রকাশ
    • গুগল এপিআইএস নোড.জেএস ক্লায়েন্ট:

      npm install googleapis crypto express express-session

    HTTP/REST

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

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

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

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

    1. আপনার অ্যাপ্লিকেশনটি প্রয়োজনীয় অনুমতিগুলি সনাক্ত করে।
    2. আপনার অ্যাপ্লিকেশন অনুরোধ করা অনুমতিগুলির তালিকা সহ ব্যবহারকারীকে গুগলে পুনর্নির্দেশ করে।
    3. ব্যবহারকারী আপনার অ্যাপ্লিকেশনটিতে অনুমতি প্রদান করবেন কিনা তা সিদ্ধান্ত নেয়।
    4. আপনার অ্যাপ্লিকেশনটি ব্যবহারকারী কী সিদ্ধান্ত নিয়েছে তা সন্ধান করে।
    5. যদি ব্যবহারকারী অনুরোধ করা অনুমতিগুলি মঞ্জুর করে তবে আপনার অ্যাপ্লিকেশনটি ব্যবহারকারীর পক্ষে এপিআই অনুরোধ করার জন্য টোকেনগুলি পুনরুদ্ধার করে।

    পদক্ষেপ 1: অনুমোদনের পরামিতিগুলি সেট করুন

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

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

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

    পিএইচপি

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

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

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

    use Google\Client;
    
    $client = new Client();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfig('client_secret.json');
    
    // Required, to set the scope value, call the addScope function
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Required, call the setRedirectUri function to specify a valid redirect URI for the
    // provided client_id
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
    
    // Recommended, 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');
    
    // Recommended, call the setState function. Using a state value can increase your assurance that
    // an incoming connection is the result of an authentication request.
    $client->setState($sample_passthrough_value);
    
    // Optional, if your application knows which user is trying to authenticate, it can use this
    // parameter to provide a hint to the Google Authentication Server.
    $client->setLoginHint('hint@example.com');
    
    // Optional, call the setPrompt function to set "consent" will prompt the user for consent
    $client->setPrompt('consent');
    
    // Optional, call the setIncludeGrantedScopes function with true to enable incremental
    // authorization
    $client->setIncludeGrantedScopes(true);

    পাইথন

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

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

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

    import google.oauth2.credentials
    import google_auth_oauthlib.flow
    
    # Required, call the from_client_secrets_file method to retrieve the client ID from a
    # client_secret.json file. The client ID (from that file) and access scopes are required. (You can
    # also use the from_client_config method, which passes the client configuration as it originally
    # appeared in a client secrets file but doesn't access the file itself.)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',
        scopes=['https://www.googleapis.com/auth/drive.metadata.readonly',
                'https://www.googleapis.com/auth/calendar.readonly'])
    
    # Required, 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(
        # Recommended, 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',
        # Optional, enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true',
        # Optional, if your application knows which user is trying to authenticate, it can use this
        # parameter to provide a hint to the Google Authentication Server.
        login_hint='hint@example.com',
        # Optional, set prompt to 'consent' will prompt the user for consent
        prompt='consent')

    রুবি

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

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

    require 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    # Required, call the from_file method to retrieve the client ID from a
    # client_secret.json file.
    client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
    # Required, scope value 
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
             'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
    # Required, Authorizers require a storage instance to manage long term persistence of
    # access and refresh tokens.
    token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
    # Required, 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.
    callback_uri = '/oauth2callback'
    
    # 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.
    authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope,
                                                    token_store, callback_uri)

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

    Node.js

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

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

    const {google} = require('googleapis');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    // Generate a secure random state value.
    const state = crypto.randomBytes(32).toString('hex');
    
    // Store state in the session
    req.session.state = state;
    
    // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
      // Include the state parameter to reduce the risk of CSRF attacks.
      state: state
    });

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

    HTTP/REST

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

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

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

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

    redirect_uri প্রয়োজন

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

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

    response_type প্রয়োজন

    গুগল ওএউথ 2.0 এন্ডপয়েন্টটি কোনও অনুমোদনের কোডটি ফেরত দেয় কিনা তা নির্ধারণ করে।

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

    scope প্রয়োজন

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

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

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

    access_type প্রস্তাবিত

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

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

    state প্রস্তাবিত

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

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

    include_granted_scopes ঐচ্ছিক

    প্রসঙ্গে অতিরিক্ত স্কোপগুলিতে অ্যাক্সেসের জন্য অনুরোধ করতে অ্যাপ্লিকেশনগুলিকে ইনক্রিমেন্টাল অনুমোদন ব্যবহার করতে সক্ষম করে। If you set this parameter's value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.

    login_hint ঐচ্ছিক

    If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

    Set the parameter value to an email address or sub identifier, which is equivalent to the user's Google ID.

    prompt ঐচ্ছিক

    A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your project requests access. আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

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

    none Do not display any authentication or consent screens. Must not be specified with other values.
    consent Prompt the user for consent.
    select_account Prompt the user to select an account.

    Step 2: Redirect to Google's OAuth 2.0 server

    Redirect the user to Google's OAuth 2.0 server to initiate the authentication and authorization process. Typically, this occurs when your application first needs to access the user's data. In the case of incremental authorization , this step also occurs when your application first needs to access additional resources that it does not yet have permission to access.

    পিএইচপি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      $auth_url = $client->createAuthUrl();
    2. Redirect the user to $auth_url :
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

    পাইথন

    This example shows how to redirect the user to the authorization URL using the Flask web application framework:

    return flask.redirect(authorization_url)

    রুবি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      auth_uri = authorizer.get_authorization_url(request: request)
    2. Redirect the user to auth_uri .

    Node.js

    1. Use the generated URL authorizationUrl from Step 1 generateAuthUrl method to request access from Google's OAuth 2.0 server.
    2. Redirect the user to authorizationUrl .
      res.redirect(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%20https%3A//www.googleapis.com/auth/calendar.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 you create the request URL, redirect the user to it.

    Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes. The response is sent back to your application using the redirect URL you specified.

    Step 3: Google prompts user for consent

    In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials and a summary of the scopes of access to be granted. The user can then consent to grant access to one or more scopes requested by your application or refuse the request.

    Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether any access was granted. That response is explained in the following step.

    ত্রুটি

    Requests to Google's OAuth 2.0 authorization endpoint may display user-facing error messages instead of the expected authentication and authorization flows. Common error codes and suggested resolutions are listed below.

    admin_policy_enforced

    The Google Account is unable to authorize one or more scopes requested due to the policies of their Google Workspace administrator. See the Google Workspace Admin help article Control which third-party & internal apps access Google Workspace data for more information about how an administrator may restrict access to all scopes or sensitive and restricted scopes until access is explicitly granted to your OAuth client ID.

    disallowed_useragent

    The authorization endpoint is displayed inside an embedded user-agent disallowed by Google's OAuth 2.0 Policies .

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

    Android developers may encounter this error message when opening authorization requests in android.webkit.WebView . Developers should instead use Android libraries such as Google Sign-In for Android or OpenID Foundation's AppAuth for Android .

    Web developers may encounter this error when an Android app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Android App Links handlers or the default browser app. The Android Custom Tabs library is also a supported option.

    iOS

    iOS and macOS developers may encounter this error when opening authorization requests in WKWebView . Developers should instead use iOS libraries such as Google Sign-In for iOS or OpenID Foundation's AppAuth for iOS .

    Web developers may encounter this error when an iOS or macOS app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Universal Links handlers or the default browser app. The SFSafariViewController library is also a supported option.

    org_internal

    The OAuth client ID in the request is part of a project limiting access to Google Accounts in a specific Google Cloud Organization . For more information about this configuration option see the User type section in the Setting up your OAuth consent screen help article.

    invalid_client

    The OAuth client secret is incorrect. Review the OAuth client configuration , including the client ID and secret used for this request.

    invalid_grant

    When refreshing an access token or using incremental authorization , the token may have expired or has been invalidated. Authenticate the user again and ask for user consent to obtain new tokens. If you are continuing to see this error, ensure that your application has been configured correctly and that you are using the correct tokens and parameters in your request. Otherwise, the user account may have been deleted or disabled.

    redirect_uri_mismatch

    The redirect_uri passed in the authorization request does not match an authorized redirect URI for the OAuth client ID. Review authorized redirect URIs in the .

    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.

    invalid_request

    There was something wrong with the request you made. এটি বেশ কয়েকটি কারণে হতে পারে:

    • The request was not properly formatted
    • The request was missing required parameters
    • The request uses an authorization method that Google doesn't support. Verify your OAuth integration uses a recommended integration method

    Step 4: Handle the OAuth 2.0 server response

    OAuth 2.0 সার্ভার অনুরোধে উল্লেখিত URL ব্যবহার করে আপনার অ্যাপ্লিকেশনের অ্যাক্সেসের অনুরোধে সাড়া দেয়।

    If the user approves the access request, then the response contains an authorization code. ব্যবহারকারী অনুরোধটি অনুমোদন না করলে, প্রতিক্রিয়াটিতে একটি ত্রুটি বার্তা রয়েছে। 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

    একটি অনুমোদন কোড প্রতিক্রিয়া:

    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 and read-only access to view your Google Calendar events:

    https://accounts.google.com/o/oauth2/v2/auth?
     scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.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 fetchAccessTokenWithAuthCode method:

    $access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    পাইথন

    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,
        'granted_scopes': credentials.granted_scopes}

    রুবি

    On your callback page, use the googleauth library to verify the authorization server response. Use the authorizer.handle_auth_callback_deferred method to save the authorization code and redirect back to the URL that originally requested authorization. This defers the exchange of the code by temporarily stashing the results in the user's session.

      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url

    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.
    app.get('/oauth2callback', async (req, res) => {
      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 if (q.state !== req.session.state) { //check state value
        console.log('State mismatch. Possible CSRF attack');
        res.end('State mismatch. Possible CSRF attack');
      } else { // 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:

    ক্ষেত্র
    client_id The client ID obtained from the .
    client_secret The client secret obtained from the .
    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 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:

    ক্ষেত্র
    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 or the refresh token expires. 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.
    refresh_token_expires_in The remaining lifetime of the refresh token in seconds. This value is only set when the user grants time-based access .
    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 https://www.googleapis.com/auth/calendar.readonly",
      "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
    }

    ত্রুটি

    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.

    Step 6: Check which scopes users granted

    When requesting multiple permissions (scopes), users may not grant your app access to all of them. Your app must verify which scopes were actually granted and gracefully handle situations where some permissions are denied, typically by disabling the features that rely on those denied scopes.

    যাইহোক, ব্যতিক্রম আছে. Google Workspace Enterprise apps with domain-wide delegation of authority , or apps marked as Trusted , bypass the granular permissions consent screen. For these apps, users won't see the granular permission consent screen. Instead, your app will either receive all requested scopes or none.

    For more detailed information, see How to handle granular permissions .

    পিএইচপি

    To check which scopes the user has granted, use the getGrantedScope() method:

    // Space-separated string of granted scopes if it exists, otherwise null.
    $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
    // Determine which scopes user granted and build a dictionary
    $granted_scopes_dict = [
      'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
      'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
    ];

    পাইথন

    The returned credentials object has a granted_scopes property, which is a list of scopes the user has granted to your 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,
        'granted_scopes': credentials.granted_scopes}

    The following function checks which scopes the user has granted to your app.

    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features

    রুবি

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the credentials object.

    # User authorized the request. Now, check which scopes were granted.
    if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
      # User authorized read-only Drive activity permission.
      # Calling the APIs, etc
    else
      # User didn't authorize read-only Drive activity permission.
      # Update UX and application accordingly
    end
    
    # Check if user authorized Calendar read permission.
    if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
      # User authorized Calendar read permission.
      # Calling the APIs, etc.
    else
      # User didn't authorize Calendar read permission.
      # Update UX and application accordingly
    end

    Node.js

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the tokens object.

    // User authorized the request. Now, check which scopes were granted.
    if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
    {
      // User authorized read-only Drive activity permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize read-only Drive activity permission.
      // Update UX and application accordingly
    }
    
    // Check if user authorized Calendar read permission.
    if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
    {
      // User authorized Calendar read permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize Calendar read permission.
      // Update UX and application accordingly
    }

    HTTP/REST

    To check whether the user has granted your application access to a particular scope, exam the scope field in the access token response. The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.

    For example, the following sample access token response indicates that the user has granted your application access to the read-only Drive activity and Calendar events permissions:

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

    Google API কল করুন

    পিএইচপি

    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());

    পাইথন

    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 3 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()

    রুবি

    After obtaining an access token, your application can use that token to make 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. For example, to call version 3 of the Drive API:
      drive = Google::Apis::DriveV3::DriveService.new
    2. Set the credentials on the service:
      drive.authorization = credentials
    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: credentials })

    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. For example, the following code uses the Google Drive API to list filenames in the user's Drive.

    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 উদাহরণ

    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

    সম্পূর্ণ উদাহরণ

    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.

    পিএইচপি

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      mkdir ~/php-oauth2-example
      cd ~/php-oauth2-example
    3. Install the Google API Client Library for PHP using Composer :
      composer require google/apiclient:^2.15.0
    4. Create the files index.php and oauth2callback.php with the following content.
    5. Run the example with the 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_secret.json');
    
    // User granted permission as an access token is in the session.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
    {
      $client->setAccessToken($_SESSION['access_token']);
      
      // Check if user granted Drive permission
      if ($_SESSION['granted_scopes_dict']['Drive']) {
        echo "Drive feature is enabled.";
        echo "</br>";
        $drive = new Drive($client);
        $files = array();
        $response = $drive->files->listFiles(array());
        foreach ($response->files as $file) {
            echo "File: " . $file->name . " (" . $file->id . ")";
            echo "</br>";
        }
      } else {
        echo "Drive feature is NOT enabled.";
        echo "</br>";
      }
    
       // Check if user granted Calendar permission
      if ($_SESSION['granted_scopes_dict']['Calendar']) {
        echo "Calendar feature is enabled.";
        echo "</br>";
      } else {
        echo "Calendar feature is NOT enabled.";
        echo "</br>";
      }
    }
    else
    {
      // Redirect users to outh2call.php which redirects users to Google OAuth 2.0
      $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();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfigFile('client_secret.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
    
    // Required, to set the scope value, call the addScope function.
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Enable incremental authorization. Recommended as a best practice.
    $client->setIncludeGrantedScopes(true);
    
    // Recommended, 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");
    
    // Generate a URL for authorization as it doesn't contain code and error
    if (!isset($_GET['code']) && !isset($_GET['error']))
    {
      // Generate and set state value
      $state = bin2hex(random_bytes(16));
      $client->setState($state);
      $_SESSION['state'] = $state;
    
      // Generate a url that asks permissions.
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    }
    
    // User authorized the request and authorization code is returned to exchange access and
    // refresh tokens.
    if (isset($_GET['code']))
    {
      // Check the state value
      if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
        die('State mismatch. Possible CSRF attack.');
      }
    
      // Get access and refresh tokens (if access_type is offline)
      $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    
      /** Save access and refresh token to the session variables.
        * ACTION ITEM: In a production app, you likely want to save the
        *              refresh token in a secure persistent storage instead. */
      $_SESSION['access_token'] = $token;
      $_SESSION['refresh_token'] = $client->getRefreshToken();
      
      // Space-separated string of granted scopes if it exists, otherwise null.
      $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
      // Determine which scopes user granted and build a dictionary
      $granted_scopes_dict = [
        'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
        'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
      ];
      $_SESSION['granted_scopes_dict'] = $granted_scopes_dict;
      
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    
    // An error response e.g. error=access_denied
    if (isset($_GET['error']))
    {
      echo "Error: ". $_GET['error'];
    }
    ?>

    পাইথন

    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 five links:

    • Call Drive API: This link points to a page that tries to execute a sample API request if users granted the permission. If necessary, it starts the authorization flow. If successful, the page displays the API response.
    • Mock page to call Calendar API: This link points to a maockpage that tries to execute a sample Calendar API request if users granted the permission. 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"
    
    # The OAuth 2.0 access scope allows for access to the
    # authenticated user's account and requires requests to use an SSL connection.
    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
              'https://www.googleapis.com/auth/calendar.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('/drive')
    def drive_api_request():
      if 'credentials' not in flask.session:
        return flask.redirect('authorize')
    
      features = flask.session['features']
    
      if features['drive']:
        # 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)
      else:
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
        return '<p>Drive feature is not enabled.</p>'
    
    @app.route('/calendar')
        def calendar_api_request():
          if 'credentials' not in flask.session:
            return flask.redirect('authorize')
    
          features = flask.session['features']
    
          if features['calendar']:
            # User authorized Calendar read permission.
            # Calling the APIs, etc.
            return ('<p>User granted the Google Calendar read permission. '+
                    'This sample code does not include code to call Calendar</p>')
          else:
            # User didn't authorize Calendar read permission.
            # Update UX and application accordingly
            return '<p>Calendar feature is not enabled.</p>'
    
    @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
      
      credentials = credentials_to_dict(credentials)
      flask.session['credentials'] = credentials
    
      # Check which scopes user granted
      features = check_granted_scopes(credentials)
      flask.session['features'] = features
      return flask.redirect('/')
      
    
    @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,
              'granted_scopes': credentials.granted_scopes}
    
    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features
    
    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'
    
      # This disables the requested scopes and granted scopes check.
      # If users only grant partial request, the warning would not be thrown.
      os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '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 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    require 'sinatra'
    
    configure do
      enable :sessions
    
      # Required, call the from_file method to retrieve the client ID from a
      # client_secret.json file.
      set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
      # Required, scope value
      # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
      scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
               'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
      # Required, Authorizers require a storage instance to manage long term persistence of
      # access and refresh tokens.
      set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
      # Required, 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.
      set :callback_uri, '/oauth2callback'
    
      # 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.
      set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope,
                              settings.token_store, callback_uri: settings.callback_uri)
    end
    
    get '/' do
      # NOTE: Assumes the user is already authenticated to the app
      user_id = request.session['user_id']
    
      # Fetch stored credentials for the user from the given request session.
      # nil if none present
      credentials = settings.authorizer.get_credentials(user_id, request)
    
      if credentials.nil?
        # Generate a url that asks the user to authorize requested scope(s).
        # Then, redirect user to the url.
        redirect settings.authorizer.get_authorization_url(request: request)
      end
      
      # User authorized the request. Now, check which scopes were granted.
      if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
        # User authorized read-only Drive activity permission.
        # Example of using Google Drive API to list filenames in user's Drive.
        drive = Google::Apis::DriveV3::DriveService.new
        files = drive.list_files(options: { authorization: credentials })
        "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
      else
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
      end
    
      # Check if user authorized Calendar read permission.
      if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
        # User authorized Calendar read permission.
        # Calling the APIs, etc.
      else
        # User didn't authorize Calendar read permission.
        # Update UX and application accordingly
      end
    end
    
    # Receive the callback from Google's OAuth 2.0 server.
    get '/oauth2callback' do
      # Handle the result of the oauth callback. Defers the exchange of the code by
      # temporarily stashing the results in the user's session.
      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url
    end

    Node.js

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      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 following content.
    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');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    /* 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 app = express();
    
      app.use(session({
        secret: 'your_secure_secret_key', // Replace with a strong secret
        resave: false,
        saveUninitialized: false,
      }));
    
      // Example on redirecting user to Google's OAuth 2.0 server.
      app.get('/', async (req, res) => {
        // Generate a secure random state value.
        const state = crypto.randomBytes(32).toString('hex');
        // Store state in the session
        req.session.state = state;
    
        // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
          // Include the state parameter to reduce the risk of CSRF attacks.
          state: state
        });
    
        res.redirect(authorizationUrl);
      });
    
      // Receive the callback from Google's OAuth 2.0 server.
      app.get('/oauth2callback', async (req, res) => {
        // 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 if (q.state !== req.session.state) { //check state value
          console.log('State mismatch. Possible CSRF attack');
          res.end('State mismatch. Possible CSRF attack');
        } 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;
          
          // User authorized the request. Now, check which scopes were granted.
          if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
          {
            // User authorized read-only Drive activity permission.
            // 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.');
              }
            });
          }
          else
          {
            // User didn't authorize read-only Drive activity permission.
            // Update UX and application accordingly
          }
    
          // Check if user authorized Calendar read permission.
          if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
          {
            // User authorized Calendar read permission.
            // Calling the APIs, etc.
          }
          else
          {
            // User didn't authorize Calendar read permission.
            // Update UX and application accordingly
          }
        }
      });
    
      // Example on revoking a token
      app.get('/revoke', async (req, res) => {
        // 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();
      });
    
    
      const server = http.createServer(app);
      server.listen(8080);
    }
    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__)
    
    # To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit
    # https://console.cloud.google.com/apis/credentials.
    CLIENT_ID = '123456789.apps.googleusercontent.com'
    CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
    
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.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.
    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: 
        # User authorized the request. Now, check which scopes were granted.
        if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']:
          # User authorized read-only Drive activity permission.
          # Example of using Google Drive API to list filenames in user's Drive.
          headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
          req_uri = 'https://www.googleapis.com/drive/v2/files'
          r = requests.get(req_uri, headers=headers).text
        else:
          # User didn't authorize read-only Drive activity permission.
          # Update UX and application accordingly
          r = 'User did not authorize Drive permission.'
    
        # Check if user authorized Calendar read permission.
        if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']:
          # User authorized Calendar read permission.
          # Calling the APIs, etc.
          r += 'User authorized Calendar permission.'
        else:
          # User didn't authorize Calendar read permission.
          # Update UX and application accordingly
          r += 'User did not authorize Calendar permission.'
    
      return r
    
    @app.route('/oauth2callback')
    def oauth2callback():
      if 'code' not in flask.request.args:
        state = str(uuid.uuid4())
        flask.session['state'] = state
        # Generate a url that asks permissions for the Drive activity
        # and Google Calendar scope. Then, redirect user to the url.
        auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                    '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
                                                                              SCOPE, state)
        return flask.redirect(auth_uri)
      else:
        if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
          return 'State mismatch. Possible CSRF attack.', 400
    
        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'}
    
        # Exchange authorization code for access and refresh tokens (if access_type is offline)
        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.

    বৈধতা নিয়ম
    স্কিম

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

    হোস্ট

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

    ডোমেইন
  • 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” .
  • ব্যবহারকারীর তথ্য

    Redirect URIs cannot contain the userinfo subcomponent.

    পথ

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

    প্রশ্ন

    Redirect URIs cannot contain open redirects .

    খণ্ড

    Redirect URIs cannot contain the fragment component.

    অক্ষর 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 )

    ক্রমবর্ধমান অনুমোদন

    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.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly&
      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. আপনি সর্বদা সাম্প্রতিক টোকেনগুলি সংরক্ষণ করছেন তা নিশ্চিত করার একটি সহজ উপায় হল টোকেন ইভেন্ট ব্যবহার করা:

    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:

    ক্ষেত্র
    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 https://www.googleapis.com/auth/calendar.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

    কিছু ক্ষেত্রে একজন ব্যবহারকারী একটি অ্যাপ্লিকেশনে দেওয়া অ্যাক্সেস প্রত্যাহার করতে চাইতে পারেন। 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.

    Time-based access

    Time-based access allows a user to grant your app access to their data for a limited duration to complete an action. Time-based access is available in select Google products during the consent flow, giving users the option to grant access for a limited period of time. An example is the Data Portability API which enables a one-time transfer of data.

    When a user grants your application time-based access, the refresh token will expire after the specified duration. Note that refresh tokens may be invalidated earlier under specific circumstances; see these cases for details. The refresh_token_expires_in field returned in the authorization code exchange response represents the time remaining until the refresh token expires in such cases.

    Implementing Cross-Account Protection

    An additional step you should take to protect your users' accounts is implementing Cross-Account Protection by utilizing Google's Cross-Account Protection Service. This service lets you subscribe to security event notifications which provide information to your application about major changes to the user account. You can then use the information to take action depending on how you decide to respond to events.

    Some examples of the event types sent to your app by Google's Cross-Account Protection Service are:

    • https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
    • https://schemas.openid.net/secevent/oauth/event-type/token-revoked
    • https://schemas.openid.net/secevent/risc/event-type/account-disabled

    See the Protect user accounts with Cross-Account Protection page for more information on how to implement Cross Account Protection and for the full list of available events.

    ,

    This document explains how web server applications use Google API Client Libraries or Google OAuth 2.0 endpoints to implement OAuth 2.0 authorization to access Google APIs.

    OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.

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

    Web server applications frequently also use service accounts to authorize API requests, particularly when calling Cloud APIs to access project-based data rather than user-specific data. Web server applications can use service accounts in conjunction with user authorization.

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

    The language-specific examples on this page use Google API Client Libraries to implement OAuth 2.0 authorization. To run the code samples, you must first install the client library for your language.

    When you use a Google API Client Library to handle your application's OAuth 2.0 flow, the client library performs many actions that the application would otherwise need to handle on its own. For example, it determines when the application can use or refresh stored access tokens as well as when the application must reacquire consent. The client library also generates correct redirect URLs and helps to implement redirect handlers that exchange authorization codes for access tokens.

    Google API Client Libraries for server-side applications are available for the following languages:

    পূর্বশর্ত

    Enable APIs for your project

    Any application that calls Google APIs needs to enable those APIs in the API Console.

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

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

    Create authorization credentials

    Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

    1. Go to the Credentials page.
    2. Click Create Client .
    3. ওয়েব অ্যাপ্লিকেশন অ্যাপ্লিকেশন প্রকার নির্বাচন করুন.
    4. Fill in the form and click Create . Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs . The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. These endpoints must adhere to Google's validation rules .

      For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080 . With that in mind, please note that all of the examples in this document use http://localhost:8080 as the redirect URI.

      We recommend that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page.

    After creating your credentials, download the client_secret.json file from the API Console. Securely store the file in a location that only your application can access.

    Identify access scopes

    Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

    Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.

    We also recommend that your application request access to authorization scopes via an incremental authorization process, in which your application requests access to user data in context. This best practice helps users to more easily understand why your application needs the access it is requesting.

    The OAuth 2.0 API Scopes document contains a full list of scopes that you might use to access Google APIs.

    Language-specific requirements

    To run any of the code samples in this document, you'll need a Google account, access to the Internet, and a web browser. If you are using one of the API client libraries, also see the language-specific requirements below.

    পিএইচপি

    To run the PHP code samples in this document, you'll need:

    • PHP 8.0 or greater with the command-line interface (CLI) and JSON extension installed.
    • The Composer dependency management tool.
    • The Google APIs Client Library for PHP:

      composer require google/apiclient:^2.15.0

    See Google APIs Client Library for PHP for more information.

    পাইথন

    To run the Python code samples in this document, you'll need:

    • Python 3.7 or greater
    • The pip package management tool.
    • The Google APIs Client Library for Python 2.0 release:
      pip install --upgrade google-api-python-client
    • The google-auth , google-auth-oauthlib , and google-auth-httplib2 for user authorization.
      pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
    • The Flask Python web application framework.
      pip install --upgrade flask
    • The requests HTTP library.
      pip install --upgrade requests

    Review the Google API Python client library release note if you aren't able to upgrade python and associated migration guide.

    রুবি

    To run the Ruby code samples in this document, you'll need:

    • Ruby 2.6 or greater
    • The Google Auth Library for Ruby:

      gem install googleauth
    • The client libraries for Drive and Calendar Google APIs:

      gem install google-apis-drive_v3 google-apis-calendar_v3
    • The Sinatra Ruby web application framework.

      gem install sinatra

    Node.js

    To run the Node.js code samples in this document, you'll need:

    • The maintenance LTS, active LTS, or current release of Node.js.
    • The Google APIs Node.js Client:

      npm install googleapis crypto express express-session

    HTTP/REST

    You do not need to install any libraries to be able to directly call the OAuth 2.0 endpoints.

    Obtaining OAuth 2.0 access tokens

    The following steps show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.

    The list below quickly summarizes these steps:

    1. Your application identifies the permissions it needs.
    2. Your application redirects the user to Google along with the list of requested permissions.
    3. The user decides whether to grant the permissions to your application.
    4. Your application finds out what the user decided.
    5. If the user granted the requested permissions, your application retrieves tokens needed to make API requests on the user's behalf.

    Step 1: Set authorization parameters

    Your first step is to create the authorization request. That request sets parameters that identify your application and define the permissions that the user will be asked to grant to your application.

    • If you use a Google client library for OAuth 2.0 authentication and authorization, you create and configure an object that defines these parameters.
    • If you call the Google OAuth 2.0 endpoint directly, you'll generate a URL and set the parameters on that URL.

    The tabs below define the supported authorization parameters for web server applications. The language-specific examples also show how to use a client library or authorization library to configure an object that sets those parameters.

    পিএইচপি

    The following code snippet creates a Google\Client() object, which defines the parameters in the authorization request.

    That object uses information from your client_secret.json file to identify your application. (See creating authorization credentials for more about that file.) The object also identifies the scopes that your application is requesting permission to access and the URL to your application's auth endpoint, which will handle the response from Google's OAuth 2.0 server. Finally, the code sets the optional access_type and include_granted_scopes parameters.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    use Google\Client;
    
    $client = new Client();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfig('client_secret.json');
    
    // Required, to set the scope value, call the addScope function
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Required, call the setRedirectUri function to specify a valid redirect URI for the
    // provided client_id
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
    
    // Recommended, 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');
    
    // Recommended, call the setState function. Using a state value can increase your assurance that
    // an incoming connection is the result of an authentication request.
    $client->setState($sample_passthrough_value);
    
    // Optional, if your application knows which user is trying to authenticate, it can use this
    // parameter to provide a hint to the Google Authentication Server.
    $client->setLoginHint('hint@example.com');
    
    // Optional, call the setPrompt function to set "consent" will prompt the user for consent
    $client->setPrompt('consent');
    
    // Optional, call the setIncludeGrantedScopes function with true to enable incremental
    // authorization
    $client->setIncludeGrantedScopes(true);

    পাইথন

    The following code snippet uses the google-auth-oauthlib.flow module to construct the authorization request.

    The code constructs a Flow object, which identifies your application using information from the client_secret.json file that you downloaded after creating authorization credentials . That object also identifies the scopes that your application is requesting permission to access and the URL to your application's auth endpoint, which will handle the response from Google's OAuth 2.0 server. Finally, the code sets the optional access_type and include_granted_scopes parameters.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    import google.oauth2.credentials
    import google_auth_oauthlib.flow
    
    # Required, call the from_client_secrets_file method to retrieve the client ID from a
    # client_secret.json file. The client ID (from that file) and access scopes are required. (You can
    # also use the from_client_config method, which passes the client configuration as it originally
    # appeared in a client secrets file but doesn't access the file itself.)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',
        scopes=['https://www.googleapis.com/auth/drive.metadata.readonly',
                'https://www.googleapis.com/auth/calendar.readonly'])
    
    # Required, 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(
        # Recommended, 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',
        # Optional, enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true',
        # Optional, if your application knows which user is trying to authenticate, it can use this
        # parameter to provide a hint to the Google Authentication Server.
        login_hint='hint@example.com',
        # Optional, set prompt to 'consent' will prompt the user for consent
        prompt='consent')

    রুবি

    Use the client_secrets.json file that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with the URL to your application's auth endpoint, which will handle the response from the OAuth 2.0 server.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    require 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    # Required, call the from_file method to retrieve the client ID from a
    # client_secret.json file.
    client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
    # Required, scope value 
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
             'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
    # Required, Authorizers require a storage instance to manage long term persistence of
    # access and refresh tokens.
    token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
    # Required, 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.
    callback_uri = '/oauth2callback'
    
    # 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.
    authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope,
                                                    token_store, callback_uri)

    Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URLs and applying access tokens to HTTP requests.

    Node.js

    The following code snippet creates a google.auth.OAuth2 object, which defines the parameters in the authorization request.

    That object uses information from your client_secret.json file to identify your application. To ask for permissions from a user to retrieve an access token, you redirect them to a consent page. To create a consent page URL:

    const {google} = require('googleapis');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    // Generate a secure random state value.
    const state = crypto.randomBytes(32).toString('hex');
    
    // Store state in the session
    req.session.state = state;
    
    // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
      // Include the state parameter to reduce the risk of CSRF attacks.
      state: state
    });

    Important Note - The refresh_token is only returned on the first authorization. আরো বিস্তারিত এখানে .

    HTTP/REST

    Google's OAuth 2.0 endpoint is at https://accounts.google.com/o/oauth2/v2/auth . This endpoint is accessible only over HTTPS. Plain HTTP connections are refused.

    The Google authorization server supports the following query string parameters for web server applications:

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

    The client ID for your application. You can find this value in the .

    redirect_uri প্রয়োজন

    Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in your client's . If this value doesn't match an authorized redirect URI for the provided client_id you will get a redirect_uri_mismatch error.

    Note that the http or https scheme, case, and trailing slash (' / ') must all match.

    response_type প্রয়োজন

    Determines whether the Google OAuth 2.0 endpoint returns an authorization code.

    Set the parameter value to code for web server applications.

    scope প্রয়োজন

    A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. These values inform the consent screen that Google displays to the user.

    Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

    We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization , you help users to more easily understand why your application needs the access it is requesting.

    access_type প্রস্তাবিত

    Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online , which is the default value, and offline .

    Set the value to offline if your application needs to refresh access tokens when the user is not present at the browser. This is the method of refreshing access tokens described later in this document. This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.

    state প্রস্তাবিত

    Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the URL query component ( ? ) of the redirect_uri after the user consents to or denies your application's access request.

    You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery . See the OpenID Connect documentation for an example of how to create and confirm a state token.

    include_granted_scopes ঐচ্ছিক

    Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter's value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.

    login_hint ঐচ্ছিক

    If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

    Set the parameter value to an email address or sub identifier, which is equivalent to the user's Google ID.

    prompt ঐচ্ছিক

    A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your project requests access. আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

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

    none Do not display any authentication or consent screens. Must not be specified with other values.
    consent Prompt the user for consent.
    select_account Prompt the user to select an account.

    Step 2: Redirect to Google's OAuth 2.0 server

    Redirect the user to Google's OAuth 2.0 server to initiate the authentication and authorization process. Typically, this occurs when your application first needs to access the user's data. In the case of incremental authorization , this step also occurs when your application first needs to access additional resources that it does not yet have permission to access.

    পিএইচপি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      $auth_url = $client->createAuthUrl();
    2. Redirect the user to $auth_url :
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

    পাইথন

    This example shows how to redirect the user to the authorization URL using the Flask web application framework:

    return flask.redirect(authorization_url)

    রুবি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      auth_uri = authorizer.get_authorization_url(request: request)
    2. Redirect the user to auth_uri .

    Node.js

    1. Use the generated URL authorizationUrl from Step 1 generateAuthUrl method to request access from Google's OAuth 2.0 server.
    2. Redirect the user to authorizationUrl .
      res.redirect(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%20https%3A//www.googleapis.com/auth/calendar.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 you create the request URL, redirect the user to it.

    Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes. The response is sent back to your application using the redirect URL you specified.

    Step 3: Google prompts user for consent

    In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials and a summary of the scopes of access to be granted. The user can then consent to grant access to one or more scopes requested by your application or refuse the request.

    Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether any access was granted. That response is explained in the following step.

    ত্রুটি

    Requests to Google's OAuth 2.0 authorization endpoint may display user-facing error messages instead of the expected authentication and authorization flows. Common error codes and suggested resolutions are listed below.

    admin_policy_enforced

    The Google Account is unable to authorize one or more scopes requested due to the policies of their Google Workspace administrator. See the Google Workspace Admin help article Control which third-party & internal apps access Google Workspace data for more information about how an administrator may restrict access to all scopes or sensitive and restricted scopes until access is explicitly granted to your OAuth client ID.

    disallowed_useragent

    The authorization endpoint is displayed inside an embedded user-agent disallowed by Google's OAuth 2.0 Policies .

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

    Android developers may encounter this error message when opening authorization requests in android.webkit.WebView . Developers should instead use Android libraries such as Google Sign-In for Android or OpenID Foundation's AppAuth for Android .

    Web developers may encounter this error when an Android app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Android App Links handlers or the default browser app. The Android Custom Tabs library is also a supported option.

    iOS

    iOS and macOS developers may encounter this error when opening authorization requests in WKWebView . Developers should instead use iOS libraries such as Google Sign-In for iOS or OpenID Foundation's AppAuth for iOS .

    Web developers may encounter this error when an iOS or macOS app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Universal Links handlers or the default browser app. The SFSafariViewController library is also a supported option.

    org_internal

    The OAuth client ID in the request is part of a project limiting access to Google Accounts in a specific Google Cloud Organization . For more information about this configuration option see the User type section in the Setting up your OAuth consent screen help article.

    invalid_client

    The OAuth client secret is incorrect. Review the OAuth client configuration , including the client ID and secret used for this request.

    invalid_grant

    When refreshing an access token or using incremental authorization , the token may have expired or has been invalidated. Authenticate the user again and ask for user consent to obtain new tokens. If you are continuing to see this error, ensure that your application has been configured correctly and that you are using the correct tokens and parameters in your request. Otherwise, the user account may have been deleted or disabled.

    redirect_uri_mismatch

    The redirect_uri passed in the authorization request does not match an authorized redirect URI for the OAuth client ID. Review authorized redirect URIs in the .

    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.

    invalid_request

    There was something wrong with the request you made. এটি বেশ কয়েকটি কারণে হতে পারে:

    • The request was not properly formatted
    • The request was missing required parameters
    • The request uses an authorization method that Google doesn't support. Verify your OAuth integration uses a recommended integration method

    Step 4: Handle the OAuth 2.0 server response

    OAuth 2.0 সার্ভার অনুরোধে উল্লেখিত URL ব্যবহার করে আপনার অ্যাপ্লিকেশনের অ্যাক্সেসের অনুরোধে সাড়া দেয়।

    If the user approves the access request, then the response contains an authorization code. ব্যবহারকারী অনুরোধটি অনুমোদন না করলে, প্রতিক্রিয়াটিতে একটি ত্রুটি বার্তা রয়েছে। 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

    একটি অনুমোদন কোড প্রতিক্রিয়া:

    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 and read-only access to view your Google Calendar events:

    https://accounts.google.com/o/oauth2/v2/auth?
     scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.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 fetchAccessTokenWithAuthCode method:

    $access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    পাইথন

    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,
        'granted_scopes': credentials.granted_scopes}

    রুবি

    On your callback page, use the googleauth library to verify the authorization server response. Use the authorizer.handle_auth_callback_deferred method to save the authorization code and redirect back to the URL that originally requested authorization. This defers the exchange of the code by temporarily stashing the results in the user's session.

      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url

    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.
    app.get('/oauth2callback', async (req, res) => {
      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 if (q.state !== req.session.state) { //check state value
        console.log('State mismatch. Possible CSRF attack');
        res.end('State mismatch. Possible CSRF attack');
      } else { // 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:

    ক্ষেত্র
    client_id The client ID obtained from the .
    client_secret The client secret obtained from the .
    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 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:

    ক্ষেত্র
    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 or the refresh token expires. 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.
    refresh_token_expires_in The remaining lifetime of the refresh token in seconds. This value is only set when the user grants time-based access .
    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 https://www.googleapis.com/auth/calendar.readonly",
      "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
    }

    ত্রুটি

    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.

    Step 6: Check which scopes users granted

    When requesting multiple permissions (scopes), users may not grant your app access to all of them. Your app must verify which scopes were actually granted and gracefully handle situations where some permissions are denied, typically by disabling the features that rely on those denied scopes.

    যাইহোক, ব্যতিক্রম আছে. Google Workspace Enterprise apps with domain-wide delegation of authority , or apps marked as Trusted , bypass the granular permissions consent screen. For these apps, users won't see the granular permission consent screen. Instead, your app will either receive all requested scopes or none.

    For more detailed information, see How to handle granular permissions .

    পিএইচপি

    To check which scopes the user has granted, use the getGrantedScope() method:

    // Space-separated string of granted scopes if it exists, otherwise null.
    $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
    // Determine which scopes user granted and build a dictionary
    $granted_scopes_dict = [
      'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
      'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
    ];

    পাইথন

    The returned credentials object has a granted_scopes property, which is a list of scopes the user has granted to your 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,
        'granted_scopes': credentials.granted_scopes}

    The following function checks which scopes the user has granted to your app.

    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features

    রুবি

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the credentials object.

    # User authorized the request. Now, check which scopes were granted.
    if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
      # User authorized read-only Drive activity permission.
      # Calling the APIs, etc
    else
      # User didn't authorize read-only Drive activity permission.
      # Update UX and application accordingly
    end
    
    # Check if user authorized Calendar read permission.
    if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
      # User authorized Calendar read permission.
      # Calling the APIs, etc.
    else
      # User didn't authorize Calendar read permission.
      # Update UX and application accordingly
    end

    Node.js

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the tokens object.

    // User authorized the request. Now, check which scopes were granted.
    if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
    {
      // User authorized read-only Drive activity permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize read-only Drive activity permission.
      // Update UX and application accordingly
    }
    
    // Check if user authorized Calendar read permission.
    if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
    {
      // User authorized Calendar read permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize Calendar read permission.
      // Update UX and application accordingly
    }

    HTTP/REST

    To check whether the user has granted your application access to a particular scope, exam the scope field in the access token response. The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.

    For example, the following sample access token response indicates that the user has granted your application access to the read-only Drive activity and Calendar events permissions:

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

    Google API কল করুন

    পিএইচপি

    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());

    পাইথন

    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 3 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()

    রুবি

    After obtaining an access token, your application can use that token to make 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. For example, to call version 3 of the Drive API:
      drive = Google::Apis::DriveV3::DriveService.new
    2. Set the credentials on the service:
      drive.authorization = credentials
    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: credentials })

    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. For example, the following code uses the Google Drive API to list filenames in the user's Drive.

    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 উদাহরণ

    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

    সম্পূর্ণ উদাহরণ

    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.

    পিএইচপি

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      mkdir ~/php-oauth2-example
      cd ~/php-oauth2-example
    3. Install the Google API Client Library for PHP using Composer :
      composer require google/apiclient:^2.15.0
    4. Create the files index.php and oauth2callback.php with the following content.
    5. Run the example with the 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_secret.json');
    
    // User granted permission as an access token is in the session.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
    {
      $client->setAccessToken($_SESSION['access_token']);
      
      // Check if user granted Drive permission
      if ($_SESSION['granted_scopes_dict']['Drive']) {
        echo "Drive feature is enabled.";
        echo "</br>";
        $drive = new Drive($client);
        $files = array();
        $response = $drive->files->listFiles(array());
        foreach ($response->files as $file) {
            echo "File: " . $file->name . " (" . $file->id . ")";
            echo "</br>";
        }
      } else {
        echo "Drive feature is NOT enabled.";
        echo "</br>";
      }
    
       // Check if user granted Calendar permission
      if ($_SESSION['granted_scopes_dict']['Calendar']) {
        echo "Calendar feature is enabled.";
        echo "</br>";
      } else {
        echo "Calendar feature is NOT enabled.";
        echo "</br>";
      }
    }
    else
    {
      // Redirect users to outh2call.php which redirects users to Google OAuth 2.0
      $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();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfigFile('client_secret.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
    
    // Required, to set the scope value, call the addScope function.
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Enable incremental authorization. Recommended as a best practice.
    $client->setIncludeGrantedScopes(true);
    
    // Recommended, 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");
    
    // Generate a URL for authorization as it doesn't contain code and error
    if (!isset($_GET['code']) && !isset($_GET['error']))
    {
      // Generate and set state value
      $state = bin2hex(random_bytes(16));
      $client->setState($state);
      $_SESSION['state'] = $state;
    
      // Generate a url that asks permissions.
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    }
    
    // User authorized the request and authorization code is returned to exchange access and
    // refresh tokens.
    if (isset($_GET['code']))
    {
      // Check the state value
      if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
        die('State mismatch. Possible CSRF attack.');
      }
    
      // Get access and refresh tokens (if access_type is offline)
      $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    
      /** Save access and refresh token to the session variables.
        * ACTION ITEM: In a production app, you likely want to save the
        *              refresh token in a secure persistent storage instead. */
      $_SESSION['access_token'] = $token;
      $_SESSION['refresh_token'] = $client->getRefreshToken();
      
      // Space-separated string of granted scopes if it exists, otherwise null.
      $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
      // Determine which scopes user granted and build a dictionary
      $granted_scopes_dict = [
        'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
        'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
      ];
      $_SESSION['granted_scopes_dict'] = $granted_scopes_dict;
      
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    
    // An error response e.g. error=access_denied
    if (isset($_GET['error']))
    {
      echo "Error: ". $_GET['error'];
    }
    ?>

    পাইথন

    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 five links:

    • Call Drive API: This link points to a page that tries to execute a sample API request if users granted the permission. If necessary, it starts the authorization flow. If successful, the page displays the API response.
    • Mock page to call Calendar API: This link points to a maockpage that tries to execute a sample Calendar API request if users granted the permission. 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"
    
    # The OAuth 2.0 access scope allows for access to the
    # authenticated user's account and requires requests to use an SSL connection.
    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
              'https://www.googleapis.com/auth/calendar.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('/drive')
    def drive_api_request():
      if 'credentials' not in flask.session:
        return flask.redirect('authorize')
    
      features = flask.session['features']
    
      if features['drive']:
        # 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)
      else:
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
        return '<p>Drive feature is not enabled.</p>'
    
    @app.route('/calendar')
        def calendar_api_request():
          if 'credentials' not in flask.session:
            return flask.redirect('authorize')
    
          features = flask.session['features']
    
          if features['calendar']:
            # User authorized Calendar read permission.
            # Calling the APIs, etc.
            return ('<p>User granted the Google Calendar read permission. '+
                    'This sample code does not include code to call Calendar</p>')
          else:
            # User didn't authorize Calendar read permission.
            # Update UX and application accordingly
            return '<p>Calendar feature is not enabled.</p>'
    
    @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
      
      credentials = credentials_to_dict(credentials)
      flask.session['credentials'] = credentials
    
      # Check which scopes user granted
      features = check_granted_scopes(credentials)
      flask.session['features'] = features
      return flask.redirect('/')
      
    
    @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,
              'granted_scopes': credentials.granted_scopes}
    
    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features
    
    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'
    
      # This disables the requested scopes and granted scopes check.
      # If users only grant partial request, the warning would not be thrown.
      os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '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 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    require 'sinatra'
    
    configure do
      enable :sessions
    
      # Required, call the from_file method to retrieve the client ID from a
      # client_secret.json file.
      set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
      # Required, scope value
      # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
      scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
               'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
      # Required, Authorizers require a storage instance to manage long term persistence of
      # access and refresh tokens.
      set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
      # Required, 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.
      set :callback_uri, '/oauth2callback'
    
      # 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.
      set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope,
                              settings.token_store, callback_uri: settings.callback_uri)
    end
    
    get '/' do
      # NOTE: Assumes the user is already authenticated to the app
      user_id = request.session['user_id']
    
      # Fetch stored credentials for the user from the given request session.
      # nil if none present
      credentials = settings.authorizer.get_credentials(user_id, request)
    
      if credentials.nil?
        # Generate a url that asks the user to authorize requested scope(s).
        # Then, redirect user to the url.
        redirect settings.authorizer.get_authorization_url(request: request)
      end
      
      # User authorized the request. Now, check which scopes were granted.
      if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
        # User authorized read-only Drive activity permission.
        # Example of using Google Drive API to list filenames in user's Drive.
        drive = Google::Apis::DriveV3::DriveService.new
        files = drive.list_files(options: { authorization: credentials })
        "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
      else
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
      end
    
      # Check if user authorized Calendar read permission.
      if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
        # User authorized Calendar read permission.
        # Calling the APIs, etc.
      else
        # User didn't authorize Calendar read permission.
        # Update UX and application accordingly
      end
    end
    
    # Receive the callback from Google's OAuth 2.0 server.
    get '/oauth2callback' do
      # Handle the result of the oauth callback. Defers the exchange of the code by
      # temporarily stashing the results in the user's session.
      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url
    end

    Node.js

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      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 following content.
    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');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    /* 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 app = express();
    
      app.use(session({
        secret: 'your_secure_secret_key', // Replace with a strong secret
        resave: false,
        saveUninitialized: false,
      }));
    
      // Example on redirecting user to Google's OAuth 2.0 server.
      app.get('/', async (req, res) => {
        // Generate a secure random state value.
        const state = crypto.randomBytes(32).toString('hex');
        // Store state in the session
        req.session.state = state;
    
        // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
          // Include the state parameter to reduce the risk of CSRF attacks.
          state: state
        });
    
        res.redirect(authorizationUrl);
      });
    
      // Receive the callback from Google's OAuth 2.0 server.
      app.get('/oauth2callback', async (req, res) => {
        // 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 if (q.state !== req.session.state) { //check state value
          console.log('State mismatch. Possible CSRF attack');
          res.end('State mismatch. Possible CSRF attack');
        } 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;
          
          // User authorized the request. Now, check which scopes were granted.
          if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
          {
            // User authorized read-only Drive activity permission.
            // 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.');
              }
            });
          }
          else
          {
            // User didn't authorize read-only Drive activity permission.
            // Update UX and application accordingly
          }
    
          // Check if user authorized Calendar read permission.
          if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
          {
            // User authorized Calendar read permission.
            // Calling the APIs, etc.
          }
          else
          {
            // User didn't authorize Calendar read permission.
            // Update UX and application accordingly
          }
        }
      });
    
      // Example on revoking a token
      app.get('/revoke', async (req, res) => {
        // 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();
      });
    
    
      const server = http.createServer(app);
      server.listen(8080);
    }
    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__)
    
    # To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit
    # https://console.cloud.google.com/apis/credentials.
    CLIENT_ID = '123456789.apps.googleusercontent.com'
    CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
    
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.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.
    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: 
        # User authorized the request. Now, check which scopes were granted.
        if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']:
          # User authorized read-only Drive activity permission.
          # Example of using Google Drive API to list filenames in user's Drive.
          headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
          req_uri = 'https://www.googleapis.com/drive/v2/files'
          r = requests.get(req_uri, headers=headers).text
        else:
          # User didn't authorize read-only Drive activity permission.
          # Update UX and application accordingly
          r = 'User did not authorize Drive permission.'
    
        # Check if user authorized Calendar read permission.
        if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']:
          # User authorized Calendar read permission.
          # Calling the APIs, etc.
          r += 'User authorized Calendar permission.'
        else:
          # User didn't authorize Calendar read permission.
          # Update UX and application accordingly
          r += 'User did not authorize Calendar permission.'
    
      return r
    
    @app.route('/oauth2callback')
    def oauth2callback():
      if 'code' not in flask.request.args:
        state = str(uuid.uuid4())
        flask.session['state'] = state
        # Generate a url that asks permissions for the Drive activity
        # and Google Calendar scope. Then, redirect user to the url.
        auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                    '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
                                                                              SCOPE, state)
        return flask.redirect(auth_uri)
      else:
        if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
          return 'State mismatch. Possible CSRF attack.', 400
    
        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'}
    
        # Exchange authorization code for access and refresh tokens (if access_type is offline)
        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.

    বৈধতা নিয়ম
    স্কিম

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

    হোস্ট

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

    ডোমেইন
  • 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” .
  • ব্যবহারকারীর তথ্য

    Redirect URIs cannot contain the userinfo subcomponent.

    পথ

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

    প্রশ্ন

    Redirect URIs cannot contain open redirects .

    খণ্ড

    Redirect URIs cannot contain the fragment component.

    অক্ষর 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 )

    ক্রমবর্ধমান অনুমোদন

    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.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly&
      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. আপনি সর্বদা সাম্প্রতিক টোকেনগুলি সংরক্ষণ করছেন তা নিশ্চিত করার একটি সহজ উপায় হল টোকেন ইভেন্ট ব্যবহার করা:

    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:

    ক্ষেত্র
    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 https://www.googleapis.com/auth/calendar.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

    কিছু ক্ষেত্রে একজন ব্যবহারকারী একটি অ্যাপ্লিকেশনে দেওয়া অ্যাক্সেস প্রত্যাহার করতে চাইতে পারেন। 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.

    Time-based access

    Time-based access allows a user to grant your app access to their data for a limited duration to complete an action. Time-based access is available in select Google products during the consent flow, giving users the option to grant access for a limited period of time. An example is the Data Portability API which enables a one-time transfer of data.

    When a user grants your application time-based access, the refresh token will expire after the specified duration. Note that refresh tokens may be invalidated earlier under specific circumstances; see these cases for details. The refresh_token_expires_in field returned in the authorization code exchange response represents the time remaining until the refresh token expires in such cases.

    Implementing Cross-Account Protection

    An additional step you should take to protect your users' accounts is implementing Cross-Account Protection by utilizing Google's Cross-Account Protection Service. This service lets you subscribe to security event notifications which provide information to your application about major changes to the user account. You can then use the information to take action depending on how you decide to respond to events.

    Some examples of the event types sent to your app by Google's Cross-Account Protection Service are:

    • https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
    • https://schemas.openid.net/secevent/oauth/event-type/token-revoked
    • https://schemas.openid.net/secevent/risc/event-type/account-disabled

    See the Protect user accounts with Cross-Account Protection page for more information on how to implement Cross Account Protection and for the full list of available events.

    ,

    This document explains how web server applications use Google API Client Libraries or Google OAuth 2.0 endpoints to implement OAuth 2.0 authorization to access Google APIs.

    OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.

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

    Web server applications frequently also use service accounts to authorize API requests, particularly when calling Cloud APIs to access project-based data rather than user-specific data. Web server applications can use service accounts in conjunction with user authorization.

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

    The language-specific examples on this page use Google API Client Libraries to implement OAuth 2.0 authorization. To run the code samples, you must first install the client library for your language.

    When you use a Google API Client Library to handle your application's OAuth 2.0 flow, the client library performs many actions that the application would otherwise need to handle on its own. For example, it determines when the application can use or refresh stored access tokens as well as when the application must reacquire consent. The client library also generates correct redirect URLs and helps to implement redirect handlers that exchange authorization codes for access tokens.

    Google API Client Libraries for server-side applications are available for the following languages:

    পূর্বশর্ত

    Enable APIs for your project

    Any application that calls Google APIs needs to enable those APIs in the API Console.

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

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

    Create authorization credentials

    Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

    1. Go to the Credentials page.
    2. Click Create Client .
    3. ওয়েব অ্যাপ্লিকেশন অ্যাপ্লিকেশন প্রকার নির্বাচন করুন.
    4. Fill in the form and click Create . Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs . The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. These endpoints must adhere to Google's validation rules .

      For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080 . With that in mind, please note that all of the examples in this document use http://localhost:8080 as the redirect URI.

      We recommend that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page.

    After creating your credentials, download the client_secret.json file from the API Console. Securely store the file in a location that only your application can access.

    Identify access scopes

    Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

    Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.

    We also recommend that your application request access to authorization scopes via an incremental authorization process, in which your application requests access to user data in context. This best practice helps users to more easily understand why your application needs the access it is requesting.

    The OAuth 2.0 API Scopes document contains a full list of scopes that you might use to access Google APIs.

    Language-specific requirements

    To run any of the code samples in this document, you'll need a Google account, access to the Internet, and a web browser. If you are using one of the API client libraries, also see the language-specific requirements below.

    পিএইচপি

    To run the PHP code samples in this document, you'll need:

    • PHP 8.0 or greater with the command-line interface (CLI) and JSON extension installed.
    • The Composer dependency management tool.
    • The Google APIs Client Library for PHP:

      composer require google/apiclient:^2.15.0

    See Google APIs Client Library for PHP for more information.

    পাইথন

    To run the Python code samples in this document, you'll need:

    • Python 3.7 or greater
    • The pip package management tool.
    • The Google APIs Client Library for Python 2.0 release:
      pip install --upgrade google-api-python-client
    • The google-auth , google-auth-oauthlib , and google-auth-httplib2 for user authorization.
      pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
    • The Flask Python web application framework.
      pip install --upgrade flask
    • The requests HTTP library.
      pip install --upgrade requests

    Review the Google API Python client library release note if you aren't able to upgrade python and associated migration guide.

    রুবি

    To run the Ruby code samples in this document, you'll need:

    • Ruby 2.6 or greater
    • The Google Auth Library for Ruby:

      gem install googleauth
    • The client libraries for Drive and Calendar Google APIs:

      gem install google-apis-drive_v3 google-apis-calendar_v3
    • The Sinatra Ruby web application framework.

      gem install sinatra

    Node.js

    To run the Node.js code samples in this document, you'll need:

    • The maintenance LTS, active LTS, or current release of Node.js.
    • The Google APIs Node.js Client:

      npm install googleapis crypto express express-session

    HTTP/REST

    You do not need to install any libraries to be able to directly call the OAuth 2.0 endpoints.

    Obtaining OAuth 2.0 access tokens

    The following steps show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.

    The list below quickly summarizes these steps:

    1. Your application identifies the permissions it needs.
    2. Your application redirects the user to Google along with the list of requested permissions.
    3. The user decides whether to grant the permissions to your application.
    4. Your application finds out what the user decided.
    5. If the user granted the requested permissions, your application retrieves tokens needed to make API requests on the user's behalf.

    Step 1: Set authorization parameters

    Your first step is to create the authorization request. That request sets parameters that identify your application and define the permissions that the user will be asked to grant to your application.

    • If you use a Google client library for OAuth 2.0 authentication and authorization, you create and configure an object that defines these parameters.
    • If you call the Google OAuth 2.0 endpoint directly, you'll generate a URL and set the parameters on that URL.

    The tabs below define the supported authorization parameters for web server applications. The language-specific examples also show how to use a client library or authorization library to configure an object that sets those parameters.

    পিএইচপি

    The following code snippet creates a Google\Client() object, which defines the parameters in the authorization request.

    That object uses information from your client_secret.json file to identify your application. (See creating authorization credentials for more about that file.) The object also identifies the scopes that your application is requesting permission to access and the URL to your application's auth endpoint, which will handle the response from Google's OAuth 2.0 server. Finally, the code sets the optional access_type and include_granted_scopes parameters.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    use Google\Client;
    
    $client = new Client();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfig('client_secret.json');
    
    // Required, to set the scope value, call the addScope function
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Required, call the setRedirectUri function to specify a valid redirect URI for the
    // provided client_id
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
    
    // Recommended, 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');
    
    // Recommended, call the setState function. Using a state value can increase your assurance that
    // an incoming connection is the result of an authentication request.
    $client->setState($sample_passthrough_value);
    
    // Optional, if your application knows which user is trying to authenticate, it can use this
    // parameter to provide a hint to the Google Authentication Server.
    $client->setLoginHint('hint@example.com');
    
    // Optional, call the setPrompt function to set "consent" will prompt the user for consent
    $client->setPrompt('consent');
    
    // Optional, call the setIncludeGrantedScopes function with true to enable incremental
    // authorization
    $client->setIncludeGrantedScopes(true);

    পাইথন

    The following code snippet uses the google-auth-oauthlib.flow module to construct the authorization request.

    The code constructs a Flow object, which identifies your application using information from the client_secret.json file that you downloaded after creating authorization credentials . That object also identifies the scopes that your application is requesting permission to access and the URL to your application's auth endpoint, which will handle the response from Google's OAuth 2.0 server. Finally, the code sets the optional access_type and include_granted_scopes parameters.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    import google.oauth2.credentials
    import google_auth_oauthlib.flow
    
    # Required, call the from_client_secrets_file method to retrieve the client ID from a
    # client_secret.json file. The client ID (from that file) and access scopes are required. (You can
    # also use the from_client_config method, which passes the client configuration as it originally
    # appeared in a client secrets file but doesn't access the file itself.)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',
        scopes=['https://www.googleapis.com/auth/drive.metadata.readonly',
                'https://www.googleapis.com/auth/calendar.readonly'])
    
    # Required, 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(
        # Recommended, 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',
        # Optional, enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true',
        # Optional, if your application knows which user is trying to authenticate, it can use this
        # parameter to provide a hint to the Google Authentication Server.
        login_hint='hint@example.com',
        # Optional, set prompt to 'consent' will prompt the user for consent
        prompt='consent')

    রুবি

    Use the client_secrets.json file that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with the URL to your application's auth endpoint, which will handle the response from the OAuth 2.0 server.

    For example, this code requests read-only, offline access to a user's Google Drive metadata and Calendar events:

    require 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    # Required, call the from_file method to retrieve the client ID from a
    # client_secret.json file.
    client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
    # Required, scope value 
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
             'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
    # Required, Authorizers require a storage instance to manage long term persistence of
    # access and refresh tokens.
    token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
    # Required, 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.
    callback_uri = '/oauth2callback'
    
    # 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.
    authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope,
                                                    token_store, callback_uri)

    Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URLs and applying access tokens to HTTP requests.

    Node.js

    The following code snippet creates a google.auth.OAuth2 object, which defines the parameters in the authorization request.

    That object uses information from your client_secret.json file to identify your application. To ask for permissions from a user to retrieve an access token, you redirect them to a consent page. To create a consent page URL:

    const {google} = require('googleapis');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    // Generate a secure random state value.
    const state = crypto.randomBytes(32).toString('hex');
    
    // Store state in the session
    req.session.state = state;
    
    // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
      // Include the state parameter to reduce the risk of CSRF attacks.
      state: state
    });

    Important Note - The refresh_token is only returned on the first authorization. আরো বিস্তারিত এখানে .

    HTTP/REST

    Google's OAuth 2.0 endpoint is at https://accounts.google.com/o/oauth2/v2/auth . This endpoint is accessible only over HTTPS. Plain HTTP connections are refused.

    The Google authorization server supports the following query string parameters for web server applications:

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

    The client ID for your application. You can find this value in the .

    redirect_uri প্রয়োজন

    Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in your client's . If this value doesn't match an authorized redirect URI for the provided client_id you will get a redirect_uri_mismatch error.

    Note that the http or https scheme, case, and trailing slash (' / ') must all match.

    response_type প্রয়োজন

    Determines whether the Google OAuth 2.0 endpoint returns an authorization code.

    Set the parameter value to code for web server applications.

    scope প্রয়োজন

    A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. These values inform the consent screen that Google displays to the user.

    Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

    We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization , you help users to more easily understand why your application needs the access it is requesting.

    access_type প্রস্তাবিত

    Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online , which is the default value, and offline .

    Set the value to offline if your application needs to refresh access tokens when the user is not present at the browser. This is the method of refreshing access tokens described later in this document. This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.

    state প্রস্তাবিত

    Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the URL query component ( ? ) of the redirect_uri after the user consents to or denies your application's access request.

    You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery . See the OpenID Connect documentation for an example of how to create and confirm a state token.

    include_granted_scopes ঐচ্ছিক

    Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter's value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.

    login_hint ঐচ্ছিক

    If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

    Set the parameter value to an email address or sub identifier, which is equivalent to the user's Google ID.

    prompt ঐচ্ছিক

    A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your project requests access. আরও তথ্যের জন্য পুনরায় সম্মতি দেওয়ার অনুরোধ দেখুন।

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

    none Do not display any authentication or consent screens. Must not be specified with other values.
    consent Prompt the user for consent.
    select_account Prompt the user to select an account.

    Step 2: Redirect to Google's OAuth 2.0 server

    Redirect the user to Google's OAuth 2.0 server to initiate the authentication and authorization process. Typically, this occurs when your application first needs to access the user's data. In the case of incremental authorization , this step also occurs when your application first needs to access additional resources that it does not yet have permission to access.

    পিএইচপি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      $auth_url = $client->createAuthUrl();
    2. Redirect the user to $auth_url :
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

    পাইথন

    This example shows how to redirect the user to the authorization URL using the Flask web application framework:

    return flask.redirect(authorization_url)

    রুবি

    1. Generate a URL to request access from Google's OAuth 2.0 server:
      auth_uri = authorizer.get_authorization_url(request: request)
    2. Redirect the user to auth_uri .

    Node.js

    1. Use the generated URL authorizationUrl from Step 1 generateAuthUrl method to request access from Google's OAuth 2.0 server.
    2. Redirect the user to authorizationUrl .
      res.redirect(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%20https%3A//www.googleapis.com/auth/calendar.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 you create the request URL, redirect the user to it.

    Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes. The response is sent back to your application using the redirect URL you specified.

    Step 3: Google prompts user for consent

    In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user's authorization credentials and a summary of the scopes of access to be granted. The user can then consent to grant access to one or more scopes requested by your application or refuse the request.

    Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether any access was granted. That response is explained in the following step.

    ত্রুটি

    Requests to Google's OAuth 2.0 authorization endpoint may display user-facing error messages instead of the expected authentication and authorization flows. Common error codes and suggested resolutions are listed below.

    admin_policy_enforced

    The Google Account is unable to authorize one or more scopes requested due to the policies of their Google Workspace administrator. See the Google Workspace Admin help article Control which third-party & internal apps access Google Workspace data for more information about how an administrator may restrict access to all scopes or sensitive and restricted scopes until access is explicitly granted to your OAuth client ID.

    disallowed_useragent

    The authorization endpoint is displayed inside an embedded user-agent disallowed by Google's OAuth 2.0 Policies .

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

    Android developers may encounter this error message when opening authorization requests in android.webkit.WebView . Developers should instead use Android libraries such as Google Sign-In for Android or OpenID Foundation's AppAuth for Android .

    Web developers may encounter this error when an Android app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Android App Links handlers or the default browser app. The Android Custom Tabs library is also a supported option.

    iOS

    iOS and macOS developers may encounter this error when opening authorization requests in WKWebView . Developers should instead use iOS libraries such as Google Sign-In for iOS or OpenID Foundation's AppAuth for iOS .

    Web developers may encounter this error when an iOS or macOS app opens a general web link in an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from your site. Developers should allow general links to open in the default link handler of the operating system, which includes both Universal Links handlers or the default browser app. The SFSafariViewController library is also a supported option.

    org_internal

    The OAuth client ID in the request is part of a project limiting access to Google Accounts in a specific Google Cloud Organization . For more information about this configuration option see the User type section in the Setting up your OAuth consent screen help article.

    invalid_client

    The OAuth client secret is incorrect. Review the OAuth client configuration , including the client ID and secret used for this request.

    invalid_grant

    When refreshing an access token or using incremental authorization , the token may have expired or has been invalidated. Authenticate the user again and ask for user consent to obtain new tokens. If you are continuing to see this error, ensure that your application has been configured correctly and that you are using the correct tokens and parameters in your request. Otherwise, the user account may have been deleted or disabled.

    redirect_uri_mismatch

    The redirect_uri passed in the authorization request does not match an authorized redirect URI for the OAuth client ID. Review authorized redirect URIs in the .

    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.

    invalid_request

    There was something wrong with the request you made. এটি বেশ কয়েকটি কারণে হতে পারে:

    • The request was not properly formatted
    • The request was missing required parameters
    • The request uses an authorization method that Google doesn't support. Verify your OAuth integration uses a recommended integration method

    Step 4: Handle the OAuth 2.0 server response

    OAuth 2.0 সার্ভার অনুরোধে উল্লেখিত URL ব্যবহার করে আপনার অ্যাপ্লিকেশনের অ্যাক্সেসের অনুরোধে সাড়া দেয়।

    If the user approves the access request, then the response contains an authorization code. ব্যবহারকারী অনুরোধটি অনুমোদন না করলে, প্রতিক্রিয়াটিতে একটি ত্রুটি বার্তা রয়েছে। 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

    একটি অনুমোদন কোড প্রতিক্রিয়া:

    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 and read-only access to view your Google Calendar events:

    https://accounts.google.com/o/oauth2/v2/auth?
     scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.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 fetchAccessTokenWithAuthCode method:

    $access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    পাইথন

    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,
        'granted_scopes': credentials.granted_scopes}

    রুবি

    On your callback page, use the googleauth library to verify the authorization server response. Use the authorizer.handle_auth_callback_deferred method to save the authorization code and redirect back to the URL that originally requested authorization. This defers the exchange of the code by temporarily stashing the results in the user's session.

      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url

    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.
    app.get('/oauth2callback', async (req, res) => {
      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 if (q.state !== req.session.state) { //check state value
        console.log('State mismatch. Possible CSRF attack');
        res.end('State mismatch. Possible CSRF attack');
      } else { // 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:

    ক্ষেত্র
    client_id The client ID obtained from the .
    client_secret The client secret obtained from the .
    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 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:

    ক্ষেত্র
    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 or the refresh token expires. 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.
    refresh_token_expires_in The remaining lifetime of the refresh token in seconds. This value is only set when the user grants time-based access .
    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 https://www.googleapis.com/auth/calendar.readonly",
      "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
    }

    ত্রুটি

    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.

    Step 6: Check which scopes users granted

    When requesting multiple permissions (scopes), users may not grant your app access to all of them. Your app must verify which scopes were actually granted and gracefully handle situations where some permissions are denied, typically by disabling the features that rely on those denied scopes.

    যাইহোক, ব্যতিক্রম আছে. Google Workspace Enterprise apps with domain-wide delegation of authority , or apps marked as Trusted , bypass the granular permissions consent screen. For these apps, users won't see the granular permission consent screen. Instead, your app will either receive all requested scopes or none.

    For more detailed information, see How to handle granular permissions .

    পিএইচপি

    To check which scopes the user has granted, use the getGrantedScope() method:

    // Space-separated string of granted scopes if it exists, otherwise null.
    $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
    // Determine which scopes user granted and build a dictionary
    $granted_scopes_dict = [
      'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
      'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
    ];

    পাইথন

    The returned credentials object has a granted_scopes property, which is a list of scopes the user has granted to your 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,
        'granted_scopes': credentials.granted_scopes}

    The following function checks which scopes the user has granted to your app.

    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features

    রুবি

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the credentials object.

    # User authorized the request. Now, check which scopes were granted.
    if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
      # User authorized read-only Drive activity permission.
      # Calling the APIs, etc
    else
      # User didn't authorize read-only Drive activity permission.
      # Update UX and application accordingly
    end
    
    # Check if user authorized Calendar read permission.
    if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
      # User authorized Calendar read permission.
      # Calling the APIs, etc.
    else
      # User didn't authorize Calendar read permission.
      # Update UX and application accordingly
    end

    Node.js

    When requesting multiple scopes at once, check which scopes were granted through the scope property of the tokens object.

    // User authorized the request. Now, check which scopes were granted.
    if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
    {
      // User authorized read-only Drive activity permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize read-only Drive activity permission.
      // Update UX and application accordingly
    }
    
    // Check if user authorized Calendar read permission.
    if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
    {
      // User authorized Calendar read permission.
      // Calling the APIs, etc.
    }
    else
    {
      // User didn't authorize Calendar read permission.
      // Update UX and application accordingly
    }

    HTTP/REST

    To check whether the user has granted your application access to a particular scope, exam the scope field in the access token response. The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.

    For example, the following sample access token response indicates that the user has granted your application access to the read-only Drive activity and Calendar events permissions:

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

    Google API কল করুন

    পিএইচপি

    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());

    পাইথন

    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 3 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()

    রুবি

    After obtaining an access token, your application can use that token to make 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. For example, to call version 3 of the Drive API:
      drive = Google::Apis::DriveV3::DriveService.new
    2. Set the credentials on the service:
      drive.authorization = credentials
    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: credentials })

    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. For example, the following code uses the Google Drive API to list filenames in the user's Drive.

    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 উদাহরণ

    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

    সম্পূর্ণ উদাহরণ

    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.

    পিএইচপি

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      mkdir ~/php-oauth2-example
      cd ~/php-oauth2-example
    3. Install the Google API Client Library for PHP using Composer :
      composer require google/apiclient:^2.15.0
    4. Create the files index.php and oauth2callback.php with the following content.
    5. Run the example with the 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_secret.json');
    
    // User granted permission as an access token is in the session.
    if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
    {
      $client->setAccessToken($_SESSION['access_token']);
      
      // Check if user granted Drive permission
      if ($_SESSION['granted_scopes_dict']['Drive']) {
        echo "Drive feature is enabled.";
        echo "</br>";
        $drive = new Drive($client);
        $files = array();
        $response = $drive->files->listFiles(array());
        foreach ($response->files as $file) {
            echo "File: " . $file->name . " (" . $file->id . ")";
            echo "</br>";
        }
      } else {
        echo "Drive feature is NOT enabled.";
        echo "</br>";
      }
    
       // Check if user granted Calendar permission
      if ($_SESSION['granted_scopes_dict']['Calendar']) {
        echo "Calendar feature is enabled.";
        echo "</br>";
      } else {
        echo "Calendar feature is NOT enabled.";
        echo "</br>";
      }
    }
    else
    {
      // Redirect users to outh2call.php which redirects users to Google OAuth 2.0
      $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();
    
    // Required, call the setAuthConfig function to load authorization credentials from
    // client_secret.json file.
    $client->setAuthConfigFile('client_secret.json');
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
    
    // Required, to set the scope value, call the addScope function.
    $client->addScope([Google\Service\Drive::DRIVE_METADATA_READONLY, Google\Service\Calendar::CALENDAR_READONLY]);
    
    // Enable incremental authorization. Recommended as a best practice.
    $client->setIncludeGrantedScopes(true);
    
    // Recommended, 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");
    
    // Generate a URL for authorization as it doesn't contain code and error
    if (!isset($_GET['code']) && !isset($_GET['error']))
    {
      // Generate and set state value
      $state = bin2hex(random_bytes(16));
      $client->setState($state);
      $_SESSION['state'] = $state;
    
      // Generate a url that asks permissions.
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    }
    
    // User authorized the request and authorization code is returned to exchange access and
    // refresh tokens.
    if (isset($_GET['code']))
    {
      // Check the state value
      if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
        die('State mismatch. Possible CSRF attack.');
      }
    
      // Get access and refresh tokens (if access_type is offline)
      $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    
      /** Save access and refresh token to the session variables.
        * ACTION ITEM: In a production app, you likely want to save the
        *              refresh token in a secure persistent storage instead. */
      $_SESSION['access_token'] = $token;
      $_SESSION['refresh_token'] = $client->getRefreshToken();
      
      // Space-separated string of granted scopes if it exists, otherwise null.
      $granted_scopes = $client->getOAuth2Service()->getGrantedScope();
    
      // Determine which scopes user granted and build a dictionary
      $granted_scopes_dict = [
        'Drive' => str_contains($granted_scopes, Google\Service\Drive::DRIVE_METADATA_READONLY),
        'Calendar' => str_contains($granted_scopes, Google\Service\Calendar::CALENDAR_READONLY)
      ];
      $_SESSION['granted_scopes_dict'] = $granted_scopes_dict;
      
      $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
    
    // An error response e.g. error=access_denied
    if (isset($_GET['error']))
    {
      echo "Error: ". $_GET['error'];
    }
    ?>

    পাইথন

    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 five links:

    • Call Drive API: This link points to a page that tries to execute a sample API request if users granted the permission. If necessary, it starts the authorization flow. If successful, the page displays the API response.
    • Mock page to call Calendar API: This link points to a maockpage that tries to execute a sample Calendar API request if users granted the permission. 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"
    
    # The OAuth 2.0 access scope allows for access to the
    # authenticated user's account and requires requests to use an SSL connection.
    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
              'https://www.googleapis.com/auth/calendar.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('/drive')
    def drive_api_request():
      if 'credentials' not in flask.session:
        return flask.redirect('authorize')
    
      features = flask.session['features']
    
      if features['drive']:
        # 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)
      else:
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
        return '<p>Drive feature is not enabled.</p>'
    
    @app.route('/calendar')
        def calendar_api_request():
          if 'credentials' not in flask.session:
            return flask.redirect('authorize')
    
          features = flask.session['features']
    
          if features['calendar']:
            # User authorized Calendar read permission.
            # Calling the APIs, etc.
            return ('<p>User granted the Google Calendar read permission. '+
                    'This sample code does not include code to call Calendar</p>')
          else:
            # User didn't authorize Calendar read permission.
            # Update UX and application accordingly
            return '<p>Calendar feature is not enabled.</p>'
    
    @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
      
      credentials = credentials_to_dict(credentials)
      flask.session['credentials'] = credentials
    
      # Check which scopes user granted
      features = check_granted_scopes(credentials)
      flask.session['features'] = features
      return flask.redirect('/')
      
    
    @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,
              'granted_scopes': credentials.granted_scopes}
    
    def check_granted_scopes(credentials):
      features = {}
      if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['granted_scopes']:
        features['drive'] = True
      else:
        features['drive'] = False
    
      if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['granted_scopes']:
        features['calendar'] = True
      else:
        features['calendar'] = False
    
      return features
    
    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'
    
      # This disables the requested scopes and granted scopes check.
      # If users only grant partial request, the warning would not be thrown.
      os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '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 'googleauth'
    require 'googleauth/web_user_authorizer'
    require 'googleauth/stores/redis_token_store'
    
    require 'google/apis/drive_v3'
    require 'google/apis/calendar_v3'
    
    require 'sinatra'
    
    configure do
      enable :sessions
    
      # Required, call the from_file method to retrieve the client ID from a
      # client_secret.json file.
      set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json')
    
      # Required, scope value
      # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
      scope = ['Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY',
               'Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY']
    
      # Required, Authorizers require a storage instance to manage long term persistence of
      # access and refresh tokens.
      set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
    
      # Required, 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.
      set :callback_uri, '/oauth2callback'
    
      # 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.
      set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope,
                              settings.token_store, callback_uri: settings.callback_uri)
    end
    
    get '/' do
      # NOTE: Assumes the user is already authenticated to the app
      user_id = request.session['user_id']
    
      # Fetch stored credentials for the user from the given request session.
      # nil if none present
      credentials = settings.authorizer.get_credentials(user_id, request)
    
      if credentials.nil?
        # Generate a url that asks the user to authorize requested scope(s).
        # Then, redirect user to the url.
        redirect settings.authorizer.get_authorization_url(request: request)
      end
      
      # User authorized the request. Now, check which scopes were granted.
      if credentials.scope.include?(Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY)
        # User authorized read-only Drive activity permission.
        # Example of using Google Drive API to list filenames in user's Drive.
        drive = Google::Apis::DriveV3::DriveService.new
        files = drive.list_files(options: { authorization: credentials })
        "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
      else
        # User didn't authorize read-only Drive activity permission.
        # Update UX and application accordingly
      end
    
      # Check if user authorized Calendar read permission.
      if credentials.scope.include?(Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY)
        # User authorized Calendar read permission.
        # Calling the APIs, etc.
      else
        # User didn't authorize Calendar read permission.
        # Update UX and application accordingly
      end
    end
    
    # Receive the callback from Google's OAuth 2.0 server.
    get '/oauth2callback' do
      # Handle the result of the oauth callback. Defers the exchange of the code by
      # temporarily stashing the results in the user's session.
      target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
      redirect target_url
    end

    Node.js

    এই উদাহরণ চালানোর জন্য:

    1. মধ্যে 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. যেমন:
      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 following content.
    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');
    const crypto = require('crypto');
    const express = require('express');
    const session = require('express-session');
    
    /**
     * 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 two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    const scopes = [
      'https://www.googleapis.com/auth/drive.metadata.readonly',
      'https://www.googleapis.com/auth/calendar.readonly'
    ];
    
    /* 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 app = express();
    
      app.use(session({
        secret: 'your_secure_secret_key', // Replace with a strong secret
        resave: false,
        saveUninitialized: false,
      }));
    
      // Example on redirecting user to Google's OAuth 2.0 server.
      app.get('/', async (req, res) => {
        // Generate a secure random state value.
        const state = crypto.randomBytes(32).toString('hex');
        // Store state in the session
        req.session.state = state;
    
        // Generate a url that asks permissions for the Drive activity and Google Calendar 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,
          // Include the state parameter to reduce the risk of CSRF attacks.
          state: state
        });
    
        res.redirect(authorizationUrl);
      });
    
      // Receive the callback from Google's OAuth 2.0 server.
      app.get('/oauth2callback', async (req, res) => {
        // 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 if (q.state !== req.session.state) { //check state value
          console.log('State mismatch. Possible CSRF attack');
          res.end('State mismatch. Possible CSRF attack');
        } 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;
          
          // User authorized the request. Now, check which scopes were granted.
          if (tokens.scope.includes('https://www.googleapis.com/auth/drive.metadata.readonly'))
          {
            // User authorized read-only Drive activity permission.
            // 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.');
              }
            });
          }
          else
          {
            // User didn't authorize read-only Drive activity permission.
            // Update UX and application accordingly
          }
    
          // Check if user authorized Calendar read permission.
          if (tokens.scope.includes('https://www.googleapis.com/auth/calendar.readonly'))
          {
            // User authorized Calendar read permission.
            // Calling the APIs, etc.
          }
          else
          {
            // User didn't authorize Calendar read permission.
            // Update UX and application accordingly
          }
        }
      });
    
      // Example on revoking a token
      app.get('/revoke', async (req, res) => {
        // 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();
      });
    
    
      const server = http.createServer(app);
      server.listen(8080);
    }
    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__)
    
    # To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit
    # https://console.cloud.google.com/apis/credentials.
    CLIENT_ID = '123456789.apps.googleusercontent.com'
    CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
    
    # Access scopes for two non-Sign-In scopes: Read-only Drive activity and Google Calendar.
    SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/calendar.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.
    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: 
        # User authorized the request. Now, check which scopes were granted.
        if 'https://www.googleapis.com/auth/drive.metadata.readonly' in credentials['scope']:
          # User authorized read-only Drive activity permission.
          # Example of using Google Drive API to list filenames in user's Drive.
          headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
          req_uri = 'https://www.googleapis.com/drive/v2/files'
          r = requests.get(req_uri, headers=headers).text
        else:
          # User didn't authorize read-only Drive activity permission.
          # Update UX and application accordingly
          r = 'User did not authorize Drive permission.'
    
        # Check if user authorized Calendar read permission.
        if 'https://www.googleapis.com/auth/calendar.readonly' in credentials['scope']:
          # User authorized Calendar read permission.
          # Calling the APIs, etc.
          r += 'User authorized Calendar permission.'
        else:
          # User didn't authorize Calendar read permission.
          # Update UX and application accordingly
          r += 'User did not authorize Calendar permission.'
    
      return r
    
    @app.route('/oauth2callback')
    def oauth2callback():
      if 'code' not in flask.request.args:
        state = str(uuid.uuid4())
        flask.session['state'] = state
        # Generate a url that asks permissions for the Drive activity
        # and Google Calendar scope. Then, redirect user to the url.
        auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                    '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
                                                                              SCOPE, state)
        return flask.redirect(auth_uri)
      else:
        if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
          return 'State mismatch. Possible CSRF attack.', 400
    
        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'}
    
        # Exchange authorization code for access and refresh tokens (if access_type is offline)
        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.

    বৈধতা নিয়ম
    স্কিম

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

    হোস্ট

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

    ডোমেইন
  • 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” .
  • ব্যবহারকারীর তথ্য

    Redirect URIs cannot contain the userinfo subcomponent.

    পথ

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

    প্রশ্ন

    Redirect URIs cannot contain open redirects .

    খণ্ড

    Redirect URIs cannot contain the fragment component.

    অক্ষর 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 )

    ক্রমবর্ধমান অনুমোদন

    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.metadata.readonly%20https%3A//www.googleapis.com/auth/calendar.readonly&
      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. আপনি সর্বদা সাম্প্রতিক টোকেনগুলি সংরক্ষণ করছেন তা নিশ্চিত করার একটি সহজ উপায় হল টোকেন ইভেন্ট ব্যবহার করা:

    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:

    ক্ষেত্র
    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 https://www.googleapis.com/auth/calendar.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

    কিছু ক্ষেত্রে একজন ব্যবহারকারী একটি অ্যাপ্লিকেশনে দেওয়া অ্যাক্সেস প্রত্যাহার করতে চাইতে পারেন। 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.

    Time-based access

    Time-based access allows a user to grant your app access to their data for a limited duration to complete an action. Time-based access is available in select Google products during the consent flow, giving users the option to grant access for a limited period of time. An example is the Data Portability API which enables a one-time transfer of data.

    When a user grants your application time-based access, the refresh token will expire after the specified duration. Note that refresh tokens may be invalidated earlier under specific circumstances; see these cases for details. The refresh_token_expires_in field returned in the authorization code exchange response represents the time remaining until the refresh token expires in such cases.

    Implementing Cross-Account Protection

    An additional step you should take to protect your users' accounts is implementing Cross-Account Protection by utilizing Google's Cross-Account Protection Service. This service lets you subscribe to security event notifications which provide information to your application about major changes to the user account. You can then use the information to take action depending on how you decide to respond to events.

    Some examples of the event types sent to your app by Google's Cross-Account Protection Service are:

    • https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
    • https://schemas.openid.net/secevent/oauth/event-type/token-revoked
    • https://schemas.openid.net/secevent/risc/event-type/account-disabled

    See the Protect user accounts with Cross-Account Protection page for more information on how to implement Cross Account Protection and for the full list of available events.