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

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

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

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

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

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

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

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

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

পূর্বশর্ত

আপনার প্রোজেক্টের জন্য এপিআই (API) সক্রিয় করুন

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

আপনার প্রোজেক্টের জন্য একটি API সক্রিয় করতে:

  1. গুগল এপিআই কনসোলে এপিআই লাইব্রেরিটি খুলুন
  2. অনুরোধ করা হলে, একটি প্রজেক্ট নির্বাচন করুন অথবা নতুন একটি তৈরি করুন।
  3. এপিআই লাইব্রেরিতে প্রোডাক্ট ফ্যামিলি এবং জনপ্রিয়তা অনুসারে শ্রেণীবদ্ধ করে সমস্ত উপলব্ধ এপিআই তালিকাভুক্ত করা আছে। আপনি যে এপিআইটি সক্রিয় করতে চান তা যদি তালিকায় দৃশ্যমান না হয়, তবে সেটি খুঁজে পেতে সার্চ ব্যবহার করুন, অথবা এটি যে প্রোডাক্ট ফ্যামিলির অন্তর্গত, সেখানে 'ভিউ অল'-এ ক্লিক করুন।
  4. যে API-টি সক্রিয় করতে চান, সেটি নির্বাচন করুন, তারপর ' Enable' বোতামে ক্লিক করুন।
  5. অনুরোধ করা হলে, বিলিং চালু করুন।
  6. অনুরোধ করা হলে, এপিআই-এর পরিষেবার শর্তাবলী পড়ুন এবং গ্রহণ করুন।

অনুমোদনের প্রমাণপত্র তৈরি করুন

যে কোনো অ্যাপ্লিকেশন যা গুগল এপিআই (Google API) অ্যাক্সেস করার জন্য OAuth 2.0 ব্যবহার করে, সেটির অবশ্যই এমন অনুমোদন ক্রেডেনশিয়াল (authorization credentials) থাকতে হবে যা গুগলের OAuth 2.0 সার্ভারের কাছে অ্যাপ্লিকেশনটিকে শনাক্ত করে। নিম্নলিখিত ধাপগুলোতে আপনার প্রোজেক্টের জন্য ক্রেডেনশিয়াল তৈরি করার পদ্ধতি ব্যাখ্যা করা হয়েছে। এরপর আপনার অ্যাপ্লিকেশনগুলো সেই ক্রেডেনশিয়াল ব্যবহার করে আপনার প্রোজেক্টের জন্য সক্রিয় করা এপিআইগুলো অ্যাক্সেস করতে পারবে।

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

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

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

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

অ্যাক্সেসের পরিধি শনাক্ত করুন

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

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

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

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

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

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

পিএইচপি

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

  • পিএইচপি ৮.০ বা তার উচ্চতর সংস্করণ, সাথে কমান্ড-লাইন ইন্টারফেস (সিএলআই) এবং জেএসওএন এক্সটেনশন ইনস্টল করা থাকতে হবে।
  • কম্পোজার ডিপেন্ডেন্সি ম্যানেজমেন্ট টুল।
  • পিএইচপি-এর জন্য গুগল এপিআই ক্লায়েন্ট লাইব্রেরি:

    composer require google/apiclient:^2.15.0

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

পাইথন

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

  • পাইথন ৩.৭ বা তার বেশি
  • পিপ প্যাকেজ ম্যানেজমেন্ট টুল।
  • পাইথনের জন্য গুগল এপিআই ক্লায়েন্ট লাইব্রেরির ২.০ সংস্করণ:
    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 এইচটিটিপি লাইব্রেরি।
    pip install --upgrade requests

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

রুবি

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

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

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

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

    gem install sinatra

নোড.জেএস

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

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

    npm install googleapis crypto express express-session

HTTP/REST

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

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

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

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

  1. আপনার অ্যাপ্লিকেশনটি তার প্রয়োজনীয় অনুমতিগুলো শনাক্ত করে।
  2. আপনার অ্যাপ্লিকেশনটি ব্যবহারকারীকে অনুরোধকৃত অনুমতিগুলোর তালিকা সহ গুগলে পুনঃনির্দেশিত করে।
  3. আপনার অ্যাপ্লিকেশনটিকে অনুমতি দেওয়া হবে কিনা, সেই সিদ্ধান্ত ব্যবহারকারীই নেন।
  4. আপনার অ্যাপ্লিকেশনটি ব্যবহারকারীর সিদ্ধান্ত জেনে নেয়।
  5. যদি ব্যবহারকারী অনুরোধ করা অনুমতিগুলো দিয়ে থাকেন, তাহলে আপনার অ্যাপ্লিকেশনটি ব্যবহারকারীর পক্ষ থেকে এপিআই (API) অনুরোধ করার জন্য প্রয়োজনীয় টোকেনগুলো সংগ্রহ করে।

ধাপ ১: অনুমোদনের পরামিতি নির্ধারণ করুন

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

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

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

পিএইচপি

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

এই অবজেক্টটি আপনার অ্যাপ্লিকেশন শনাক্ত করার জন্য আপনার client_secret.json ফাইলের তথ্য ব্যবহার করে। (ঐ ফাইলটি সম্পর্কে আরও জানতে ‘অথরাইজেশন ক্রেডেনশিয়াল তৈরি করা’ দেখুন।) অবজেক্টটি সেই স্কোপগুলোকেও শনাক্ত করে যেগুলোতে আপনার অ্যাপ্লিকেশন অ্যাক্সেস করার অনুমতি চাইছে এবং আপনার অ্যাপ্লিকেশনের অথ এন্ডপয়েন্টের URL-টিও শনাক্ত করে, যা গুগলের OAuth 2.0 সার্ভার থেকে আসা রেসপন্সটি পরিচালনা করবে। সবশেষে, কোডটি ঐচ্ছিক 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 ) অবজেক্ট তৈরি করে, যা অথরাইজেশন ক্রেডেনশিয়াল তৈরি করার পর আপনার ডাউনলোড করা client_secret.json ফাইলের তথ্য ব্যবহার করে আপনার অ্যাপ্লিকেশনকে শনাক্ত করে। এই অবজেক্টটি আরও শনাক্ত করে সেই স্কোপগুলোকে, যেগুলোতে আপনার অ্যাপ্লিকেশন অ্যাক্সেস করার অনুমতি চাইছে, এবং আপনার অ্যাপ্লিকেশনের অথ এন্ডপয়েন্টের ইউআরএল (URL), যা গুগলের OAuth 2.0 সার্ভার থেকে আসা রেসপন্সটি পরিচালনা করবে। সবশেষে, কোডটি ঐচ্ছিক 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')

রুবি

আপনার অ্যাপ্লিকেশনে একটি ক্লায়েন্ট অবজেক্ট কনফিগার করতে আপনার তৈরি করা client_secrets.json ফাইলটি ব্যবহার করুন। একটি ক্লায়েন্ট অবজেক্ট কনফিগার করার সময়, আপনি আপনার অ্যাপ্লিকেশনের অ্যাক্সেস করার জন্য প্রয়োজনীয় স্কোপগুলো নির্দিষ্ট করেন, সাথে আপনার অ্যাপ্লিকেশনের অথেন্টিকেশন এন্ডপয়েন্টের URL-টিও দেন, যা 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 অপারেশনগুলো সম্পাদন করতে ক্লায়েন্ট অবজেক্ট ব্যবহার করে, যেমন অনুমোদনের অনুরোধের 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 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 -এ অবস্থিত। এই এন্ডপয়েন্টটি শুধুমাত্র HTTPS-এর মাধ্যমে অ্যাক্সেসযোগ্য। সাধারণ HTTP সংযোগ গ্রহণ করা হয় না।

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

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

আপনার অ্যাপ্লিকেশনের ক্লায়েন্ট আইডি। আপনি এই মানটি ক্লাউড কনসোল ক্লায়েন্টস পৃষ্ঠায় খুঁজে পাবেন।

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

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

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

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

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

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

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

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

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

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

access_type সুপারিশকৃত

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

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

state সুপারিশকৃত

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

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

include_granted_scopes ঐচ্ছিক

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

login_hint ঐচ্ছিক

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

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

prompt ঐচ্ছিক

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

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

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

ধাপ ২: গুগলের OAuth 2.0 সার্ভারে রিডাইরেক্ট করুন

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

পিএইচপি

  1. গুগলের 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. গুগলের OAuth 2.0 সার্ভারে অ্যাক্সেসের অনুরোধ করার জন্য একটি URL তৈরি করুন:
    auth_uri = authorizer.get_authorization_url(request: request)
  2. ব্যবহারকারীকে auth_uri তে পুনঃনির্দেশিত করুন।

নোড.জেএস

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

HTTP/REST

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

পাঠযোগ্যতার জন্য লাইন ব্রেক এবং স্পেস সহ একটি উদাহরণ 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//developers.google.com/oauthplayground&
 client_id=client_id

রিকোয়েস্ট ইউআরএল তৈরি করার পর, ব্যবহারকারীকে সেখানে রিডাইরেক্ট করুন।

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

ধাপ ৩: গুগল ব্যবহারকারীর কাছে সম্মতি চায়

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

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

ত্রুটি

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

admin_policy_enforced

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

disallowed_useragent

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

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

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

org_internal

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

invalid_client

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

deleted_client

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

invalid_grant

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

redirect_uri_mismatch

অনুমোদন অনুরোধে পাঠানো redirect_uri টি OAuth ক্লায়েন্ট আইডির জন্য কোনো অনুমোদিত রিডাইরেক্ট URI-এর সাথে মেলে না। Google Cloud Console-এর Clients পৃষ্ঠায় অনুমোদিত রিডাইরেক্ট URI-গুলো পর্যালোচনা করুন।

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

invalid_request

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

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

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//developers.google.com/oauthplayground&
 client_id=client_id

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

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

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

পিএইচপি

অথরাইজেশন কোডকে অ্যাক্সেস টোকেনে রূপান্তর করতে, 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 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 লাইব্রেরি ব্যবহার করুন। অথরাইজেশন কোডটি সংরক্ষণ করতে এবং যে URL থেকে মূলত অথরাইজেশনের অনুরোধ করা হয়েছিল সেখানে রিডাইরেক্ট করতে authorizer.handle_auth_callback_deferred মেথডটি ব্যবহার করুন। এটি ব্যবহারকারীর সেশনে ফলাফলগুলো সাময়িকভাবে সংরক্ষণ করে কোডের আদান-প্রদানকে বিলম্বিত করে।

  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/REST

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

ক্ষেত্র
client_id ক্লাউড কনসোল ক্লায়েন্টস পৃষ্ঠা থেকে ক্লায়েন্ট আইডিটি পাওয়া গেছে।
client_secret ঐচ্ছিক

ক্লাউড কনসোল ক্লায়েন্টস পৃষ্ঠা থেকে ক্লায়েন্ট সিক্রেটটি পাওয়া গেছে।

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

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

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//developers.google.com/oauthplayground&
grant_type=authorization_code

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

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

ক্ষেত্র
access_token যে টোকেনটি আপনার অ্যাপ্লিকেশন একটি গুগল এপিআই অনুরোধ অনুমোদন করার জন্য পাঠায়।
expires_in অ্যাক্সেস টোকেনটির অবশিষ্ট মেয়াদ সেকেন্ডে।
refresh_token একটি টোকেন যা ব্যবহার করে আপনি একটি নতুন অ্যাক্সেস টোকেন পেতে পারেন। রিফ্রেশ টোকেনগুলো ততক্ষণ পর্যন্ত বৈধ থাকে যতক্ষণ না ব্যবহারকারী অ্যাক্সেস প্রত্যাহার করে নেয় অথবা রিফ্রেশ টোকেনটির মেয়াদ শেষ হয়ে যায়। আবার, এই ফিল্ডটি এই রেসপন্সে কেবল তখনই উপস্থিত থাকবে, যদি আপনি গুগলের অথরাইজেশন সার্ভারে করা প্রাথমিক অনুরোধে 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 প্রসেসটি পুনরায় চালু করে একটি নতুন কোডের অনুরোধ করুন।

ধাপ ৬: ব্যবহারকারীরা কোন কোন স্কোপ মঞ্জুর করেছেন তা যাচাই করুন

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

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

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

পিএইচপি

ব্যবহারকারী কোন কোন স্কোপের অনুমতি দিয়েছেন তা পরীক্ষা করতে, 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,
    '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

নোড.জেএস

একসাথে একাধিক স্কোপের জন্য অনুরোধ করার সময়, 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"
  }

গুগল এপিআই কল করুন

পিএইচপি

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

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

পাইথন

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

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

রুবি

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

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

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

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

নোড.জেএস

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 examples

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

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

Or, alternatively, the query string parameter option:

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

Complete example

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

পিএইচপি

To run this example:

  1. In the API Console, add the URL of the local machine to the list of redirect URLs. For example, add http://localhost:8080 .
  2. Create a new directory and change to it. For example:
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Install the Google API Client Library for PHP using Composer :
    composer require google/apiclient:^2.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 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/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 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 browser session storage.
    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'))

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

    return flask.jsonify(**files)
  else:
    # User didn't authorize read-only Drive activity permission.
    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.')

  # 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 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="/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="/drive">Call Drive API directly</a></td>' +
          '<td> Use stored credentials to call the API, you still might not be prompted to reauthorize ' +
          '    the application.</td></tr>' +
          '<tr><td><a href="/calendar">Call Calendar API directly</a></td>' +
          '<td> Use stored credentials to call the API, 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="/authorize">authorize</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

নোড.জেএস

To run this example:

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

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.

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

    Redirect URIs cannot contain the userinfo subcomponent.

    পথ

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

    নোড.জেএস

    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//developers.google.com/oauthplayground&
      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.

    নোড.জেএস

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

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

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

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

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

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

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

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

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

    HTTP/REST

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

    Fields
    client_id The client ID obtained from the API Console .
    client_secret ঐচ্ছিক

    The client secret obtained from the API Console .

    grant_type As defined in the OAuth 2.0 specification , this field's value must be set to refresh_token .
    refresh_token The refresh token returned from the authorization code exchange.

    The following snippet shows a sample request:

    POST /token HTTP/1.1
    Host: oauth2.googleapis.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=your_client_id&
    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.

    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.