The Google OAuth 2.0 system supports server-to-server interactions such as those between a web application and a Google service. For this scenario you need a service account, which is an account that belongs to your application instead of to an individual end user. Your application calls Google APIs on behalf of the service account, so users aren't directly involved. This scenario is sometimes called "two-legged OAuth," or "2LO." (The related term "three-legged OAuth" refers to scenarios in which your application calls Google APIs on behalf of end users, and in which user consent is sometimes required.)
Typically, an application uses a service account when the application uses Google APIs to work with its own data rather than a user's data. For example, an application that uses Google Cloud Datastore for data persistence would use a service account to authenticate its calls to the Google Cloud Datastore API.
If you have a Google Apps domain—if you use Google Apps for Work, for example—an administrator of the Google Apps domain can authorize an application to access user data on behalf of users in the Google Apps domain. For example, an application that uses the Google Calendar API to add events to the calendars of all users in a Google Apps domain would use a service account to access the Google Calendar API on behalf of users. Authorizing a service account to access data on behalf of users in a domain is sometimes referred to as "delegating domain-wide authority" to a service account.
This document describes how an application can complete the server-to-server OAuth 2.0 flow by using either a Google APIs client library (recommended) or HTTP.
Contents
Overview
To support server-to-server interactions, first create a service account for your project in the Developers Console. If you want to access user data for users in your Google Apps domain, then delegate domain-wide access to the service account.
Then, your application prepares to make authorized API calls by using the service account's credentials to request an access token from the OAuth 2.0 auth server.
Finally, your application can use the access token to call Google APIs.
Creating a service account
A service account's credentials include a generated email address that is unique, a client ID, and at least one public/private key pair.
If your application runs on Google App Engine, a service account is set up automatically when you create your project.
If your application runs on Google Compute Engine, a service account is also set up automatically when you create your project, but you must specify the scopes that your application needs access to when you create a Google Compute Engine instance. For more information, see Preparing an instance to use service accounts.
If your application doesn't run on Google App Engine or Google Compute Engine, you must obtain these credentials in the Google Developers Console. To generate service-account credentials, or to view the public credentials that you've already generated, do the following:
In the sidebar on the left, expand APIs & auth. Next, click APIs. Select the Enabled APIs link in the API section to see a list of all your enabled APIs. Make sure that the API is on the list of enabled APIs. If you have not enabled it, select the API from the list of APIs, then select the Enable API button for the API.
In the sidebar on the left, select Credentials.
To set up a new service account, do the following:
Under the OAuth heading, select Create new Client ID.
When prompted, select Service Account and click Create Client ID.
A dialog box appears. To proceed, click Okay, got it.
Your new Public/Private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely. The Console shows your private key's password only at this initial moment of service account creation--the password will not be shown again. You now have Generate New JSON Key and Generate New P12 Key options, and the ability to delete.
You can return to the Developers Console at any time to view the client ID, email address, and public key fingerprints, or to generate additional public/private key pairs. For more details about service account credentials in the Developers Console, see Service accounts in the Developers Console help file.
Take note of the service account's email address and store the service account's P12 private key file in a location accessible to your application. Your application needs them to make authorized API calls.
Delegating domain-wide authority to the service account
If your application accesses user data, the service account that you created needs to be granted access to the Google Apps domain’s user data that you want to access.
The following steps must be performed by an administrator of the Google Apps domain:
Select Security from the list of controls. If you don't see Security listed, select More controls from the gray bar at the bottom of the page, then select Security from the list of controls. If you can't see the controls, make sure you're signed in as an administrator for the domain.
Select Show more and then Advanced settings from the list of options.
Select Manage API client access in the Authentication section.
In the Client Name field enter the service account's Client ID.
In the One or More API Scopes field enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide access to the Google Drive API and the Google Calendar API, enter:https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar.
Click Authorize.
Your application now has the authority to make API calls as users in your domain (to "impersonate" users). When you prepare to make authorized API calls, you specify the user to impersonate.
If the response includes an access token, you can use the access token to call a Google API. (If the response does not include an access token, your JWT and token request might not be properly formed, or the service account might not have permission to access the requested scopes.)
When the access token expires, your application generates another JWT, signs it, and requests another access token.
The rest of this section describes the specifics of creating a JWT, signing the JWT, forming the access token request, and handling the response.
Creating a JWT
A JWT is composed of three parts: a header, a claim set, and a signature. The header and claim set are JSON objects. These JSON objects are serialized to UTF-8 bytes, then encoded using the Base64url encoding. This encoding provides resilience against encoding changes due to repeated encoding operations. The header, claim set, and signature are concatenated together with a period (.) character.
The header consists of two fields that indicate the signing algorithm and the format of the assertion. Both fields are mandatory, and each field has only one value. As additional algorithms and formats are introduced, this header will change accordingly.
Service accounts rely on the RSA SHA-256 algorithm and the JWT token format. As a result, the JSON representation of the header is as follows:
{"alg":"RS256","typ":"JWT"}
The Base64url representation of this is as follows:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
Forming the JWT claim set
The JWT claim set contains information about the JWT, including the permissions being requested (scopes), the target of the token, the issuer, the time the token was issued, and the lifetime of the token. Most of the fields are mandatory. Like the JWT header, the JWT claim set is a JSON object and is used in the calculation of the signature.
Required claims
The required claims in the JWT claim set are shown below. They may appear in any order in the claim set.
Name
Description
iss
The email address of the service account.
scope
A space-delimited list of the permissions that the application requests.
aud
A descriptor of the intended target of the assertion. When making an access token request this value is alwayshttps://www.googleapis.com/oauth2/v3/token.
exp
The expiration time of the assertion, specified as seconds since 00:00:00 UTC, January 1, 1970. This value has a maximum of 1 hour after the issued time.
iat
The time the assertion was issued, specified as seconds since 00:00:00 UTC, January 1, 1970.
The JSON representation of the required fields in a JWT claim set is shown below:
In some enterprise cases, an application can request permission to act on behalf of a particular user in an organization. Permission to perform this type of impersonation must be granted before an application can impersonate a user, and is usually handled by a domain administrator. For more information on domain administration, see Managing API client access.
To obtain an access token that grants an application delegated access to a resource, include the email address of the user in the JWT claim set as the value of the sub field.
Name
Description
sub
The email address of the user for which the application is requesting delegated access.
If an application does not have permission to impersonate a user, the response to an access token request that includes the sub field will be an error.
An example of a JWT claim set that includes the sub field is shown below:
Like the JWT header, the JWT claim set should be serialized to UTF-8 and Base64url-safe encoded. Below are examples of a JSON representation and Base64url-safe representation JWT Claim set:
JSON Web Signature (JWS) is the specification that guides the mechanics of generating the signature for the JWT. The input for the signature is the byte array of the following content:
The signing algorithm in the JWT header must be used when computing the signature. The only signing algorithm supported by the Google OAuth 2.0 Authorization Server is RSA using SHA-256 hashing algorithm. This is expressed as RS256 in the alg field in the JWT header.
Sign the UTF-8 representation of the input using SHA256withRSA (also known as RSASSA-PKCS1-V1_5-SIGN with the SHA-256 hash function) with the private key obtained from the Google Developers Console. The output will be a byte array.
The signature must then be Base64url encoded. The header, claim set, and signature are concatenated together with a period (.) character. The result is the JWT. It should be the following (line breaks added for clarity):
After generating the signed JWT, an application can use it to request an access token. This access token request is an HTTPS POSTrequest, and the body is URL encoded. The URL is shown below:
https://www.googleapis.com/oauth2/v3/token
The following parameters are required in the HTTPS POST request:
Name
Description
grant_type
Use the following string, URL-encoded as necessary: urn:ietf:params:oauth:grant-type:jwt-bearer
assertion
The JWT, including signature.
Below is a raw dump of the HTTPS POST request used in an access token request:
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU3MzM4MSwiaWF0IjoxMzI4NTY5NzgxfQ.ixOUGehweEVX_UKXv5BbbwVEdcz6AYS-6uQV6fGorGKrHf3LIJnyREw9evE-gs2bmMaQI5_UbabvI4k-mQE4kBqtmSpTzxYBL1TCd7Kv5nTZoUC1CmwmWCFqT9RE6D7XSgPUh_jF1qskLa2w0rxMSjwruNKbysgRNctZPln7cqQ
If the JWT and access token request are properly formed and the service account has permission to perform the operation, then the JSON response from the Authorization Server includes an access token. The following is an example response:
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 or service account. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization: Bearer HTTP header. 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 People API).
You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.
Examples
A call to the people.get endpoint (the People API) using the access_token query string parameter might look like the following, though you'll need to specify your own access token:
GET https://www.googleapis.com/plus/v1/people/userId?access_token=1/fFBGRNJru1FQd44AzqT3Zg
Here is a call to the same API for the authenticated user (me) using the Authorization: Bearer HTTP header:
GET /plus/v1/people/me HTTP/1.1
Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg
Host: googleapis.com
You can try out with the curl command-line application. Here's an example using the HTTP header option (preferred):
Access tokens issued by the Google OAuth 2.0 Authorization Server expire one hour after they are issued. When an access token expires, then the application should generate another JWT, sign it, and request another access token.
Это краткий перевод основных тезисов из брошюры «Web API Design. Crafting Interfaces that Developers Love» Брайана Маллоя из компании Apigee Labs. Apigee занимается разработкой различных API-сервисов и консталтингом. Кстати, среди клиентов этой компании засветились такие гиганты, как Best Buy, Cisco, Dell и Ebay.
В тексте попадаются комментарии переводчика, они выделены курсивом.
Собираем API-интерфейсы, которые понравятся другим разработчикам
Понятные URL для вызовов API
Первый принцип хорошего REST-дизайна — делать вещи понятно и просто. Начинать стоит с основных URL адресов для ваших вызовов API.
Ваши адреса вызовов должны быть понятными даже без документации. Для этого возьмите себе за правило описывать любую сущность с помощью коротких и ясных базовых URL адресов, содержащих максимум 2 параметра. Вот отличный пример:
/dogs для работы со списком собак /dogs/12345 для работы с отдельной собакой
Существительные — это хорошо, а глаголы — плохо
Держите глаголы как можно дальше от базовых URL сущностей вашего API. Многие разработчки используют глаголы для описания объектов. Ясное дело, что в работе часто приходится моделировать сложные сущности. И эти сущности взаимодействуют между собой. Но при попытке ввести глаголы для моделирования сущностей и их связей, мы, скорее всего, получим большое количество труднозапоминаемых и непонятных вызовов:
Мы только что описали собак с помощью двух базовых URL адресов с существительными. Теперь нам нужно работать с созданными сущностями. Чаще всего требуются операции чтения, создания, редактирования и удаления (CRUD — Create — Read — Update — Delete). Для этого нам прекрасно подойдут HTTP-методы GET, POST, PUT и DELETE.
POST /dogs — создать новую собаку GET /dogs — получить список собак PUT /dogs — редактирование всех собак сразу DELETE /dogs — удаление всех собак
POST /dogs/12345 — вернуть ошибку (собака 12345 уже создана) GET /dogs/12345 — показать информацию о собаке PUT /dogs/12345 — редактировать собаку 12345 DELETE /dogs/12345 — удалить
Базовые URL выглядят просто, глаголы не используются, все интуитивно и понятно. Красота!
Множественное число
Хорошо использовать для описания базовых URL существительные во множественном числе. Хуже — в единственном числе. Плохо — смешивать адреса с существительными в единственном и множественном числе.
/checkins у Foursquare /deals y GroupOn /Product y Zappos
Конкретные имена лучше абстрактных
Абстрактные названия — это часто считается крутым у архитекторов API. И это совсем не круто для тех, кто потом с этим API будет работать. /blogs, /videos, /news, /articles — это выглядит очевидным. А вот /items и /assets — нет.
Связи
Одни ресурсы всегдя связаны с другими ресурсами. Есть ли очевидный и простой способ показать эти связи через API? При этом помня о нашем разделении на существительные и глаголы?
GET /owners/5678/dogs POST /owners/5678/dogs
Мы только что представили связь двух ресурсов в простом виде. Метод GET в этом случае вернет нам список собак владельца 5678, а метод POST — добавит владельцу 5678 еще одну собаку. Связи очень удобно представлять в виде /ресурс/идентификатор/ресурс.
Сложные вещи нужно прятать за знаком «?»
Почти у каждого API есть куча параметров, которые можно читать, обновлять, фильтровать и работать с ними всякими другими способами. Но все эти параметры не должны быть видны в базовых адресах. Лучше всего указывать параметры внутри обращения к базовым адресам.
GET /dogs?color=red&state=running&location=park
А что насчет ошибок?
Хороший механизм обработки ошибок — это часть любого хорошего API. Давайте посмотрим, как выглядят ошибки в популярных API.
Facebook HTTP Status Code: 200 {"type" : "OauthException", "message":"(#803) Some of the aliases you requested do not exist: foo.bar"}
Не важно, как выполнится запрос — Facebook всегда вернет нам код 200 OK.
Twilio проделали хорошую работу и для каждой ошибки в API подобрали адекватный код ошибки HTTP. Как и Facebook, ребята предоставляют информацию об ошибке еще и в теле ответа. И, что самое прикольное, они дают ссылку на документацию по проблеме.
SimpleGeo дают сообщение об ошибке в коде HTTP и снабжают его небольшим пояснением в теле ответа.
Используйте коды ответов HTTP
Смело берите HTTP коды ответов и сопоставляйте с ответами вашего API. Всего в частом употреблении находится около 70-ти кодов. Мало кто из разработчиков помнит их все, так что из этих 70-ти лучше взять примерно 10. Кстати, так поступает большая часть провайдеров API.
На вход были переданы неправильные данные — клиентская ошибка
Произошла ошибка при обработке данных — серверная ошибка
Так что можно взять за основу 3 кода ответов:
200 OK
400 Bad Request (некорректный запрос)
500 Internal server error (внутренняя ошибка сервера)
Если 3-х кодов вам недостаточно — возьмите еще 5:
201 Created (Запись создана)
304 Not Modified (Данные не изменились)
404 Not Found (Данные не найдены)
401 Unauthorized (Неавторизованный доступ)
403 Forbidden (Доступ запрещен)
Лучше всего не следовать этой практике слепо. Оценивайте пользу от использования HTTP кодов ответов в каждом конкретном случае. Скорее всего, использование кодов ответов не везде будет оправданным и уместным. Например, если вы пишете бэкенд для небольшого веб-приложения — то легко можно ограничиться кодами ошибок в теле ответа. А еще стандартый ответ 200 OK позволит создать два механимза обработки ошибок: для ошибок сервера и для ошибок самого API. В общем — думайте, взвешивайте. А потом принимайте решение.
И, конечно же, при ошибке всегда нужно прикладывать сообщение для разработчиков. А приложить к сообщению ссылку на документацию по проблеме — это еще лучше.
Twilio требует при каждом запросе к API передавать время, когда приложение разработчика было скомпилировано. На основе этой даты Twilio определяет, какую версию API нужно предоставить приложению. Это умный и интересный подход, но слишком сложный. А еще можно легко запутаться с датами.
Salesforce.com вставляет v20.0 в середину адреса API запроса. И это очень хороший подход. Но не стоит использовать точку в нумерации версии — это провоцирует излишне частые изменения в интерфейсе API. Можно сколь угодно часто менять логику работы внутри API, но вот сами интерфейсы должны меняться максимально редко. Так что лучше обойтись без точки и не искушать себя.
Facebook тоже использует нумерацию версий в запросе, но прячет её в параметры запроса. И этот подход плох тем, что после очередного внедрения новой версии API все приложения, не передающие версию в запросе, начинают глючить.
Как реализовать версии в API?
Используйте префикс v, целые числа и располагайте номер версии в левой части адреса. Например, /v1/dogs. Держите в рабочем виде как минимум одну предыдущую версию
Еще можно указывать версию в заголовках ответа сервера. Это может давать некоторые дополнительные возможности при работе с API. Но если вы используете множество разных версий и требуете обязательно указывать их в заголовках — это симптом большой проблемы.
Частичный ответ
Частичный ответ позволяет разработчикам запросить только ту информацию, которая им нужна. Например, запросы к некоторым API могут вернуть кучу лишней информации, которая почти не используется: всякие таймстампы, метаданные и т.д. Чтобы не запрашивать лишнюю информацию, в Google придумали частичный ответ.
Перечислять необходимые поля через запятую в адресе запроса — это очень простой и удобный подход. Берите его на вооружение.
Сделайте простую паджинацию
Отдавать все записи по первому же запросу — очень плохая идея. Поэтому вы должны обязательно предусмотреть паджинацию. Давайте посмотрим, как в популярных API можно вытащить записи с 50 по 75.
Facebook: смещение 50 и лимит 25 Twitter: страница 3 и 25 записей на страницу Linkedin: с 50-й записи прочитать 25
Мы рекомендуем использовать лимит и смещение. Этот подход более интуитивен.
/dogs?limit=25&offset=50
Еще стоит приложить к каждому ответу мета-информацию: текущая страница, сколько всего записей доступно.
Предусмотрите значения по умолчанию: если пользователь не передал в запросе параметры паджинации, считайте лимит равным 10 и смещение — равным 0 (вывести первые 10 записей).
А что насчет действий?
Не все API-ресуры являются записями, которые можно читать, редактировать и удалять. Бывают и API-действия. Переводы, вычисления, конвертации — все это действия.
Лучше всего для таких запросов использовать глаголы, а не существительные.
/convert?from=EUR&to=USD&amount=100
Убедитесь, что даже просто глядя на список вызовов в документации можно отличить сущности от действий.
Поддержка нескольких форматов
Здорово поддерживать несколько форматов ответа.
Google ?alt=json Foursquare /venue.json Digg ?type=json
Кстати, Digg позволяет установить формат ответа и через HTTP-заголовок Accept.
Мы рекомендуем подход Foursquare.
/dogs.json /dogs/1234.json
Еще можно предусмотреть ответы API не только в разных форматах, но и ответы для разных типов клиентов. Например, можно сделать API, способное работать одновременно с iOS-приложением и фронт-эндом веб-приложения. Это может выглядеть так: /dogs.ios и /dogs.web.
Формат по умолчанию
JSON — пожалуй, лучший формат по умолчанию. Он менее многословен, чем XML. Его поддерживают все популярные языки. Его можно сразу же использовать на фронт-энде веб-приложения.
Существует много конвенций именования переменных. Нам, как спецам по Ruby on Rails, конвенция Twitter близка по духу. Но лучшим подходом мы считаем подход Foursquare: — camelCase (переменные с маленькой буквы, классы — с большой). Такой способ именования наиболее симпатичен для подачи данных в JSON: данные выглядят похоже на JavaScript. Что, в общем, логично для JSON.
Хоть автор и советует почаще использовать camelCase, лучше все же подумать о клиенте и потом уже принимать решение. Например, с вашим API может общаться программа, написанная на C, а ей лучше использовать несколько_другую_конвенцию.
Поиск
Глобальный поиск оформить просто:
/search?q=search+word
Поиск по конкретным сущностям можно легко представить, опираясь на то, что мы узнали ранее:
/owners/5678/dogs?q=red
А чтобы представлять данные в разных форматах, мы вспомним о расширениях:
/search.xml?q=search+word
Соберите все API вызовы на одном домене
Facebook предоставляет два домена.
api.facebook.com этот адрес появился первым graph.facebook.com этот адрес ввели после внедрения глобального графа
Foursquare ограничились одним адресом
api.foursquare.com
Twitter завели 3 адреса, 2 из которых ориентированы на посты и поиск
Легко догадаться, как Facebook и Twitter завели себе по несколько адресов: проще направлять запросы в разные кластеры через DNS, чем через логику. Но мы делаем приятный API для разработчиков, поэтому опять выберем подход Foursquare.
На всякий случай напомню, что разработчикам небольшого бэкенда для веб-приложения не надо выделять отдельный домен, чтобы не создавать проблемы с кроссдоменными ajax-запросами на фронт-энде.
Делайте редиректы
Если кто-то обращается к вашему API-домену и не передает никаких параметров — смело делайте редирект на домен с документацией для разработчиков. Заведите несколько интуитивно понятных доменов для документации и делайте редирект на основной домен разработчиков.
Как мы уже говорили ранее, лучше всего отправлять код ошибки не только в теле ответа API, но и в HTTP коде ответа. Но как быть, если клиент выбрасывает исключение при получении любого кода HTTP, отличного от 200? Для таких случаев ребята из Twitter предусмотрели блестящее и простое решение — добавлять параметр к запросу.
В результате ошибки будут приходить с кодом 200. Предусмотрите в своем API параметр suppress_response_codes и сделайте его равным true по умолчанию.
А что если клиент поддерживает ограниченный набор HTTP методов?
В таком случае нужно эмулировать полноценный REST API с помощью GET-параметров.
чтение /dogs создание /dogs?method=post редактирование /dogs/1234?method=put удаление /dogs/1234?method=delete
Будьте аккуратны с таким подходом! Если вы будете неаккуратно обращаться с такими ссылками и не обеспечите им должной безопасности, боты (вроде поискового робота Google) могут вызывать такие ссылки. И вы получите бесконечно создающиеся и удаляющиеся записи при каждом заходе бота.
Авторизация
Этот вопрос сложный, и мы с моими коллегами никогда не можем прийти к согласию быстро. Давайте посмотрим, что делают ведущие игроки.
PayPal Permissions Service API Facebook OAuth 2.0 Twitter 1.0a
Обратите внимание на то, что PayPal реализовали свою систему авторизации еще до того, как был изобретен OAuth.
Если вам требуется авторизация пользователей через сторонние приложения — только OAuth. И ни в коем случае не делайте что-то вроде OAuth, но «немного другое».
«Болтливые» API
«Болтливые» — это значит, что для выполнения популярных операций приходится выполнять 3-4 вызова API подряд. Это плохо.
Попробуйте посмотреть на ваши вызовы глазами пользователя. Вы увидите, что примерно 80% вызовов принимают и отдают данные одинаковой структуры. Это значит, что вполне можно сделать псевдонимы для последовательностей вызовов. После этого пользователь сможет единожды направить данные на вход, и вся цепочка вызовов выполнится сама.
With the advent of OWIN middleware and Identity framework, traditional forms authentication is outdated since OWIN middleware and Identity framework takes care of everything in a better and organized manner. But sometimes, existing applications cannot be migrated to Identity framework due to one or the other reason, but Form Authentication user login is needed. For such situations, here is the workaround.
Background
There was an existing ASP.NET application using role based forms authentication, and was supposed to be migrated to ASP.NET MVC, but for some reason, the client wanted to stick to forms authentication.
Using the Code
To implement forms authentication, interception of both request and response is required which is done with the help of DelegatingHandler.
The following jquery code shows how to make a Login call.
HideCopy Code
$(document).ready(
function () {
$("#btnSubmit").click(function () {
var usrname = $("#username").val();
var pwd = $("#password").val();
$.post("http://localhost:50750/api/loginctrl/login",
{ username: usrname, password: pwd }, function (result) {
alert(JSON.stringify(result));
});
});
});
Registering Delegating Handler
Before starting the execution of the project, custom Delegating Handler is to be registered with Application's Message Handlers. In this app, Delegating handler is registered inside Global.asax's Application_Startmethod.