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

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

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

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

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

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

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

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

সার্ভার-সাইড অ্যাপ্লিকেশনের জন্য 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. YouTube Data API খুঁজে বের করতে এবং সক্ষম করতে লাইব্রেরি পৃষ্ঠাটি ব্যবহার করুন। আপনার অ্যাপ্লিকেশন ব্যবহার করবে এমন অন্য কোনও API খুঁজুন এবং সেগুলিও সক্ষম করুন।

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

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

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

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

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

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

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

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

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

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

YouTube Data API v3 নিম্নলিখিত স্কোপ ব্যবহার করে:

ব্যাপ্তি বর্ণনা
https://www. googleapis. com/ auth/ youtube আপনার YouTube অ্যাকাউন্ট পরিচালনা করুন
https://www. googleapis. com/ auth/ youtube. channel-memberships. creator আপনার বর্তমান সক্রিয় চ্যানেল সদস্যদের তালিকা, তাদের বর্তমান স্তর এবং তারা কখন সদস্য হয়েছেন তা দেখুন
https://www. googleapis. com/ auth/ youtube. force-ssl আপনার YouTube ভিডিও, রেটিং, মন্তব্য এবং ক্যাপশনগুলি দেখুন, সম্পাদনা করুন এবং স্থায়ীভাবে মুছুন৷
https://www. googleapis. com/ auth/ youtube. readonly আপনার YouTube অ্যাকাউন্ট দেখুন
https://www. googleapis. com/ auth/ youtube. upload আপনার YouTube ভিডিও পরিচালনা করুন
https://www. googleapis. com/ auth/ youtubepartner YouTube-এ আপনার সম্পদ এবং সংশ্লিষ্ট বিষয়বস্তু দেখুন ও পরিচালনা করুন
https://www. googleapis. com/ auth/ youtubepartner-channel-audit একটি YouTube অংশীদারের সাথে অডিট প্রক্রিয়া চলাকালীন প্রাসঙ্গিক আপনার YouTube চ্যানেলের ব্যক্তিগত তথ্য দেখুন৷

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

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

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

পিএইচপি

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

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

    composer require google/apiclient:^2.15.0

আরও তথ্যের জন্য PHP-এর জন্য 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 পাইথন ক্লায়েন্ট লাইব্রেরি রিলিজ নোটটি পর্যালোচনা করুন।

রুবি

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

  • রুবি ২.৬ বা তার বেশি
  • রুবির জন্য গুগল অথ লাইব্রেরি:

    gem install googleauth
  • সিনাত্রা রুবি ওয়েব অ্যাপ্লিকেশন ফ্রেমওয়ার্ক।

    gem install sinatra

নোড.জেএস

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

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

    npm install googleapis crypto express express-session

HTTP/বিশ্রাম

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

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

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

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

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

ধাপ ১: অনুমোদনের প্যারামিটার সেট করুন

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

  • যদি আপনি 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 প্যারামিটার সেট করে।

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

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_YOUTUBE::YOUTUBE_FORCE_SSL);

// 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 ফাইল থেকে তথ্য ব্যবহার করে আপনার অ্যাপ্লিকেশন সনাক্ত করে যা আপনি অনুমোদন শংসাপত্র তৈরি করার পরে ডাউনলোড করেছেন। এই অবজেক্টটি আপনার অ্যাপ্লিকেশন যে স্কোপগুলিতে অ্যাক্সেসের অনুমতি চাইছে এবং আপনার অ্যাপ্লিকেশনের auth এন্ডপয়েন্টের URL সনাক্ত করে, যা Google এর OAuth 2.0 সার্ভার থেকে প্রতিক্রিয়া পরিচালনা করবে। অবশেষে, কোডটি ঐচ্ছিক access_type এবং include_granted_scopes প্যারামিটার সেট করে।

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

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/youtube.force-ssl'])

# 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 ফাইলটি ব্যবহার করুন। যখন আপনি একটি ক্লায়েন্ট অবজেক্ট কনফিগার করেন, তখন আপনি আপনার অ্যাপ্লিকেশনের অ্যাক্সেস করার জন্য প্রয়োজনীয় স্কোপগুলি নির্দিষ্ট করেন, সাথে আপনার অ্যাপ্লিকেশনের auth এন্ডপয়েন্টের URLও উল্লেখ করেন, যা OAuth 2.0 সার্ভার থেকে প্রতিক্রিয়া পরিচালনা করবে।

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

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

require 'google/apis/youtube_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 
scope = 'https://www.googleapis.com/auth/youtube.force-ssl'

# 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 অনুরোধগুলিতে অ্যাক্সেস টোকেন প্রয়োগ করা।

নোড.জেএস

নিম্নলিখিত কোড স্নিপেটটি একটি 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 YouTube API
const scopes = [
  'https://www.googleapis.com/auth/youtube.force-ssl'
];

// 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/বিশ্রাম

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

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

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

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

redirect_uri প্রয়োজনীয়

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

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

response_type প্রয়োজনীয়

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

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

scope প্রয়োজনীয়

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

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

YouTube Data API v3 নিম্নলিখিত স্কোপ ব্যবহার করে:

ব্যাপ্তি বর্ণনা
https://www. googleapis. com/ auth/ youtube আপনার YouTube অ্যাকাউন্ট পরিচালনা করুন
https://www. googleapis. com/ auth/ youtube. channel-memberships. creator আপনার বর্তমান সক্রিয় চ্যানেল সদস্যদের তালিকা, তাদের বর্তমান স্তর এবং তারা কখন সদস্য হয়েছেন তা দেখুন
https://www. googleapis. com/ auth/ youtube. force-ssl আপনার YouTube ভিডিও, রেটিং, মন্তব্য এবং ক্যাপশনগুলি দেখুন, সম্পাদনা করুন এবং স্থায়ীভাবে মুছুন৷
https://www. googleapis. com/ auth/ youtube. readonly আপনার YouTube অ্যাকাউন্ট দেখুন
https://www. googleapis. com/ auth/ youtube. upload আপনার YouTube ভিডিও পরিচালনা করুন
https://www. googleapis. com/ auth/ youtubepartner YouTube-এ আপনার সম্পদ এবং সংশ্লিষ্ট বিষয়বস্তু দেখুন ও পরিচালনা করুন
https://www. googleapis. com/ auth/ youtubepartner-channel-audit একটি YouTube অংশীদারের সাথে অডিট প্রক্রিয়া চলাকালীন প্রাসঙ্গিক আপনার YouTube চ্যানেলের ব্যক্তিগত তথ্য দেখুন৷

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

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

access_type প্রস্তাবিত

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

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

state প্রস্তাবিত

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

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

include_granted_scopes ঐচ্ছিক

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

login_hint ঐচ্ছিক

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

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

prompt ঐচ্ছিক

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

সম্ভাব্য মানগুলি হল:

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

ধাপ ২: 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));

পাইথন

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

return flask.redirect(authorization_url)

রুবি

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

নোড.জেএস

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

HTTP/বিশ্রাম

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

নিচের নমুনা URLটি এমন একটি স্কোপে অফলাইন অ্যাক্সেস ( access_type=offline ) অনুরোধ করে যা ব্যবহারকারীর YouTube অ্যাকাউন্ট দেখার অ্যাক্সেসের অনুমতি দেয়। এটি ক্রমবর্ধমান অনুমোদন ব্যবহার করে নিশ্চিত করে যে নতুন অ্যাক্সেস টোকেন ব্যবহারকারী পূর্বে অ্যাপ্লিকেশন অ্যাক্সেস মঞ্জুর করেছেন এমন যেকোনো স্কোপকে কভার করে। URLটি প্রয়োজনীয় redirect_uri , response_type , এবং client_id প্যারামিটারের পাশাপাশি state প্যারামিটারের জন্য মানও সেট করে। URLটিতে পঠনযোগ্যতার জন্য লাইন ব্রেক এবং স্পেস রয়েছে।

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=code&
 client_id=client_id

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

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

ধাপ ৩: গুগল ব্যবহারকারীর কাছ থেকে সম্মতির অনুরোধ জানায়

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

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

ত্রুটি

Google এর OAuth 2.0 অনুমোদনের শেষ বিন্দুতে অনুরোধ করলে প্রত্যাশিত প্রমাণীকরণ এবং অনুমোদন প্রবাহের পরিবর্তে ব্যবহারকারী-মুখী ত্রুটি বার্তা প্রদর্শিত হতে পারে। সাধারণ ত্রুটি কোড এবং প্রস্তাবিত সমাধানগুলি হল:

admin_policy_enforced

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

disallowed_useragent

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

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

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

org_internal

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

invalid_client

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

deleted_client

অনুরোধটি করার জন্য ব্যবহৃত OAuth ক্লায়েন্টটি মুছে ফেলা হয়েছে। অব্যবহৃত ক্লায়েন্টের ক্ষেত্রে মুছে ফেলা ম্যানুয়ালি বা স্বয়ংক্রিয়ভাবে ঘটতে পারে। মুছে ফেলা ক্লায়েন্টগুলি মুছে ফেলার 30 দিনের মধ্যে পুনরুদ্ধার করা যেতে পারে। আরও জানুন

invalid_grant

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

redirect_uri_mismatch

অনুমোদনের অনুরোধে পাস করা redirect_uri OAuth ক্লায়েন্ট আইডির জন্য অনুমোদিত পুনর্নির্দেশ URI-এর সাথে মেলে না। অনুমোদিত পুনর্নির্দেশ URI গুলি পর্যালোচনা করুন Google Cloud ConsoleClients page.

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

invalid_request

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

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

ধাপ ৪: 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%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=code&
 client_id=client_id

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

ধাপ ৫: রিফ্রেশ এবং অ্যাক্সেস টোকেনের জন্য অনুমোদন কোড বিনিময় করুন

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

পিএইচপি

একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করতে, 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/youtube.force-ssl'],
    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 browser session storage, but for security: client_id, client_secret,
# and token_uri are instead stored only on the backend server.
credentials = flow.credentials
flask.session['credentials'] = {
    'token': credentials.token,
    'refresh_token': credentials.refresh_token,
    '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

নোড.জেএস

একটি অ্যাক্সেস টোকেনের জন্য একটি অনুমোদন কোড বিনিময় করতে, 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/বিশ্রাম

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

ক্ষেত্র
client_id থেকে প্রাপ্ত ক্লায়েন্ট আইডি Cloud ConsoleClients page.
client_secret ঐচ্ছিক

ক্লায়েন্টের গোপন তথ্য যা থেকে প্রাপ্ত Cloud ConsoleClients page.

code প্রাথমিক অনুরোধ থেকে অনুমোদন কোডটি ফিরে এসেছে।
grant_type OAuth 2.0 স্পেসিফিকেশনে সংজ্ঞায়িত হিসাবে , এই ক্ষেত্রের মান authorization_code এ সেট করা আবশ্যক।
redirect_uri আপনার প্রকল্পের জন্য তালিকাভুক্ত পুনঃনির্দেশ URI গুলির মধ্যে একটি Cloud ConsoleClients page প্রদত্ত 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&
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/youtube.force-ssl",
  "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

ত্রুটি

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

invalid_grant

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

ধাপ ৬: ব্যবহারকারীরা কোন স্কোপগুলি মঞ্জুর করেছেন তা পরীক্ষা করুন

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

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

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

পিএইচপি

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

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

পাইথন

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

credentials = flow.credentials
flask.session['credentials'] = {
    'token': credentials.token,
    'refresh_token': credentials.refresh_token,
    'granted_scopes': credentials.granted_scopes}

রুবি

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

# User authorized the request. Now, check which scopes were granted.
if credentials.scope.include?(Google::Apis::YoutubeV3::AUTH_YOUTUBE_FORCE_SSL)
  # User authorized permission to see, edit, and permanently delete the
  # YouTube videos, ratings, comments and captions.
  # Calling the APIs, etc
else
  # User didn't authorize the permission.
  # Update UX and application accordingly
end

নোড.জেএস

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

// User authorized the request. Now, check which scopes were granted.
if (tokens.scope.includes('https://www.googleapis.com/auth/youtube.force-ssl'))
{
  // User authorized permission to see, edit, and permanently delete the
  // YouTube videos, ratings, comments and captions.
  // Calling the APIs, etc.
}
else
{
  // User didn't authorize read-only Drive activity permission.
  // Update UX and application accordingly
}

HTTP/বিশ্রাম

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

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

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

গুগল এপিআই-তে কল করুন

পিএইচপি

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

  1. যদি আপনার কোনও নতুন Google\Client অবজেক্টে অ্যাক্সেস টোকেন প্রয়োগ করার প্রয়োজন হয় — উদাহরণস্বরূপ, যদি আপনি কোনও ব্যবহারকারীর সেশনে অ্যাক্সেস টোকেনটি সংরক্ষণ করে থাকেন — তাহলে setAccessToken পদ্ধতিটি ব্যবহার করুন:
    $client->setAccessToken($access_token);
  2. আপনি যে API কল করতে চান তার জন্য একটি পরিষেবা অবজেক্ট তৈরি করুন। আপনি যে API কল করতে চান তার জন্য কনস্ট্রাক্টরকে একটি অনুমোদিত Google\Client অবজেক্ট সরবরাহ করে একটি পরিষেবা অবজেক্ট তৈরি করুন। উদাহরণস্বরূপ, YouTube ডেটা API কল করতে:
    $youtube = new Google_Service_YouTube($client);
  3. পরিষেবা অবজেক্ট দ্বারা প্রদত্ত ইন্টারফেস ব্যবহার করে API পরিষেবাতে অনুরোধ করুন। উদাহরণস্বরূপ, অনুমোদিত ব্যবহারকারীর YouTube চ্যানেল সম্পর্কে ডেটা পুনরুদ্ধার করতে:
    $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));

পাইথন

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

  1. আপনি যে API কল করতে চান তার জন্য একটি পরিষেবা অবজেক্ট তৈরি করুন। আপনি googleapiclient.discovery লাইব্রেরির build পদ্ধতিতে API এর নাম এবং সংস্করণ এবং ব্যবহারকারীর শংসাপত্র সহ কল ​​করে একটি পরিষেবা অবজেক্ট তৈরি করতে পারেন: উদাহরণস্বরূপ, YouTube Data API এর সংস্করণ 3 কল করতে:
    from googleapiclient.discovery import build
    
    youtube = build('youtube', 'v3', credentials=credentials)
  2. পরিষেবা অবজেক্ট দ্বারা প্রদত্ত ইন্টারফেস ব্যবহার করে API পরিষেবাতে অনুরোধ করুন। উদাহরণস্বরূপ, অনুমোদিত ব্যবহারকারীর YouTube চ্যানেল সম্পর্কে ডেটা পুনরুদ্ধার করতে:
    channel = youtube.channels().list(mine=True, part='snippet').execute()

রুবি

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

  1. আপনি যে API-কে কল করতে চান তার জন্য একটি পরিষেবা অবজেক্ট তৈরি করুন। উদাহরণস্বরূপ, YouTube Data API-এর সংস্করণ 3 কল করতে:
    youtube = Google::Apis::YoutubeV3::YouTubeService.new
  2. Set the credentials on the service:
    youtube.authorization = credentials
  3. Make requests to the API service using the interface provided by the service object . For example, to retrieve data about the authorized user's YouTube channel:
    channel = youtube.list_channels(part, :mine => mine)

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

channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })

নোড.জেএস

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 YouTube API to list channels.
var service = google.youtube('v3');
service.channels.list({
  auth: oauth2Client,
  part: 'snippet,contentDetails,statistics',
  forUsername: 'GoogleDevelopers'
}, function (err, response) {
  if (err) {
    console.log('The API returned an error: ' + err);
    return;
  }
  var channels = response.data.items;
  if (channels.length == 0) {
    console.log('No channel found.');
  } else {
    console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
      'it has %s views.',
      channels[0].id,
      channels[0].snippet.title,
      channels[0].statistics.viewCount);
  }
});

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 YouTube Data API ).

Note that the YouTube Data API supports service accounts only for YouTube content owners that own and manage multiple YouTube channels, such as record labels and movie studios.

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 youtube.channels endpoint (the YouTube Data API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

GET /youtube/v3/channels?part=snippet&mine=true 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/youtube/v3/channels?access_token=access_token&part=snippet&mine=true

curl examples

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

curl -H "Authorization: Bearer access_token" https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true

Or, alternatively, the query string parameter option:

curl https://www.googleapis.com/youtube/v3/channels?access_token=access_token&part=snippet&mine=true

Complete example

The following example prints a JSON-formatted object showing information about a user's YouTube channel after the user authenticates and authorizes the application to manage the user's YouTube account.

পিএইচপি

To run this example:

  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. For example:
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Install the Google API Client Library for PHP using Composer :
    composer require google/apiclient:^2.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']);
  
  $youtube = new Google_Service_YouTube($client);
  $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
  echo json_encode($channel);
  
}
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_YOUTUBE::YOUTUBE_FORCE_SSL);

// 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();
  
  $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:

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

import os
import flask
import json
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/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

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

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

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

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

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

  channel = youtube.channels().list(mine=True, part='snippet').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(**channel)
@app.route('/authorize')
def authorize():
  # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)

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

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

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

  return flask.redirect(authorization_url)

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

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

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

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

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

  # Load client secrets from the server-side file.
  with open(CLIENT_SECRETS_FILE, 'r') as f:
      client_config = json.load(f)['web']

  # Load user-specific credentials from the session.
  session_credentials = flask.session['credentials']

  # Reconstruct the credentials object.
  credentials = google.oauth2.credentials.Credentials(
      refresh_token=session_credentials.get('refresh_token'),
      scopes=session_credentials.get('granted_scopes'),
      token=session_credentials.get('token'),
      client_id=client_config.get('client_id'),
      client_secret=client_config.get('client_secret'),
      token_uri=client_config.get('token_uri'))

  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:
    # Clear the user's session credentials after successful revocation
    if 'credentials' in flask.session:
        del flask.session['credentials']
        del flask.session['features']
    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,
          'granted_scopes': credentials.granted_scopes}

def print_index_table():
  return ('<table>' + 
          '<tr><td><a href="/test">Test an API request</a></td>' +
          '<td>Submit an API request and see a formatted JSON response. ' +
          '    Go through the authorization flow if there are no stored ' +
          '    credentials for the user.</td></tr>' + 
          '<tr><td><a href="/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/youtube_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 retrieving data about the user's YouTube channel.
  scope = 'Google::Apis::YoutubeV3::AUTH_YOUTUBE_FORCE_SSL'

  # 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 read-only YouTube Data API permission.
  # Example of using YouTube Data API to list user's YouTube channel
  youtube = Google::Apis::YoutubeV3::YouTubeService.new
  channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })
  
  "<pre>#{JSON.pretty_generate(channel.to_h)}</pre>"
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

নোড.জেএস

To run this example:

  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. For example:
    mkdir ~/nodejs-oauth2-example
    cd ~/nodejs-oauth2-example
  4. Install the Google API Client Library for Node.js using npm :
    npm install googleapis
  5. Create the files main.js with the 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 YouTube API
const scopes = [
  'https://www.googleapis.com/auth/youtube.force-ssl'
];

/* 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;
      
      // Example of using YouTube API to list channels.
      var service = google.youtube('v3');
      service.channels.list({
        auth: oauth2Client,
        part: 'snippet,contentDetails,statistics',
        forUsername: 'GoogleDevelopers'
      }, function (err, response) {
        if (err) {
          console.log('The API returned an error: ' + err);
          return;
        }
        var channels = response.data.items;
        if (channels.length == 0) {
          console.log('No channel found.');
        } else {
          console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
            'it has %s views.',
            channels[0].id,
            channels[0].snippet.title,
            channels[0].statistics.viewCount);
        }
      });
    }
  });

  // 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 YouTube API
SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl'

# 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: 
    headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
    req_uri = 'https://www.googleapis.com/youtube/v3/channels/list'
    r = requests.get(req_uri, headers=headers)
    return r.text 

@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.

Validation rules
পরিকল্পনা

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” .
  • Userinfo

    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 .

    Fragment

    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 )

    Incremental authorization

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

    For example, suppose an app helps users identify interesting local events. The app lets users view videos about the events, rate the videos, and add the videos to playlists. Users can also use the app to add events to their Google Calendars.

    In this case, at sign-in time, the app might not need or request access to any scopes. However, if the user tried to rate a video, add a video to a playlist, or perform another YouTube action, the app could request access to the https://www.googleapis.com/auth/youtube.force-ssl scope. Similarly, the app could request access to the https://www.googleapis.com/auth/calendar scope if the user tried to add a calendar event.

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

    নোড.জেএস

    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

    In this example, the calling application requests access to retrieve the user's YouTube Analytics data in addition to any other access that the user has already granted to the application.

    GET https://accounts.google.com/o/oauth2/v2/auth?
      scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly&
      access_type=offline&
      state=security_token%3D138rk%3Btarget_url%3Dhttp...index&
      redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
      response_type=code&
      client_id=client_id&
      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.

    PHP

    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.

    নোড.জেএস

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

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

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

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

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

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

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

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

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

    HTTP/REST

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

    ক্ষেত্র
    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&
    refresh_token=refresh_token&
    grant_type=refresh_token

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

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

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

    Token revocation

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

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

    পিএইচপি

    To programmatically revoke a token, call revokeToken() :

    $client->revokeToken();

    পাইথন

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

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

    রুবি

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

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

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

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

    নোড.জেএস

    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.