Wednesday, July 1, 2015

Using OAuth 2.0 for Server to Server Applications

Original taken here https://developers.google.com/identity/protocols/OAuth2ServiceAccount
http://blog.mszcool.com/index.php/2013/12/asp-net-4-5-1-webapi-general-integration-with-oauth2-and-oauth-authentication-servers/


Using OAuth 2.0 for Server to Server Applications


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:
  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. 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.
  4. In the sidebar on the left, select Credentials.
  5. To set up a new service account, do the following:
    1. Under the OAuth heading, select Create new Client ID.
    2. When prompted, select Service Account and click Create Client ID.
    3. 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:
  1. Go to your Google Apps domain’s Admin console.
  2. 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.
  3. Select Show more and then Advanced settings from the list of options.
  4. Select Manage API client access in the Authentication section.
  5. In the Client Name field enter the service account's Client ID.
  6. 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.
  7. 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.

Preparing to make an authorized API call


After you obtain the client ID and private key from the Developers Console, your application needs to complete the following steps:
  1. Create a JSON Web Token (JWT, pronounced "jot"), which includes a header, a claim set, and a signature.
  2. Request an access token from the Google OAuth 2.0 Authorization Server.
  3. Handle the JSON response that the Authorization Server returns.
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.
Your server application uses a JWT to
      request a token from the Google Authorization Server, then uses the token
      to call a Google API endpoint. No end user is involved.
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.
A JWT is composed as follows:
{Base64url encoded header}.{Base64url encoded claim set}.{Base64url encoded signature}
The base string for the signature is as follows:
{Base64url encoded header}.{Base64url encoded claim set}
Forming the JWT header
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.
NameDescription
issThe email address of the service account.
scopeA space-delimited list of the permissions that the application requests.
audA descriptor of the intended target of the assertion. When making an access token request this value is alwayshttps://www.googleapis.com/oauth2/v3/token.
expThe 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.
iatThe 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:
{
  "iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
  "scope":"https://www.googleapis.com/auth/devstorage.readonly",
  "aud":"https://www.googleapis.com/oauth2/v3/token",
  "exp":1328554385,
  "iat":1328550785
}
Additional claims
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.
NameDescription
subThe 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:
{
  "iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
  "sub":"some.user@example.com",
  "scope":"https://www.googleapis.com/auth/prediction",
  "aud":"https://www.googleapis.com/oauth2/v3/token",
  "exp":1328554385,
  "iat":1328550785
}
Encoding the JWT claim set
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:
{
  "iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
  "scope":"https://www.googleapis.com/auth/prediction",
  "aud":"https://www.googleapis.com/oauth2/v3/token",
  "exp":1328554385,
  "iat":1328550785
}
eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ
Computing the signature
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:
{Base64url encoded header}.{Base64url encoded claim set}
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):
{Base64url encoded header}.
{Base64url encoded claim set}.
{Base64url encoded signature}
Below is an example of a JWT before Base64url encoding:
{"alg":"RS256","typ":"JWT"}.
{
"iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
"scope":"https://www.googleapis.com/auth/prediction",
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":1328554385,
"iat":1328550785
}.
[signature bytes]
Below is an example of a JWT that has been signed and is ready for transmission:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ.
ixOUGehweEVX_UKXv5BbbwVEdcz6AYS-6uQV6fGorGKrHf3LIJnyREw9evE-gs2bmMaQI5_UbabvI4k-mQE4kBqtmSpTzxYBL1TCd7Kv5nTZoUC1CmwmWCFqT9RE6D7XSgPUh_jF1qskLa2w0rxMSjwruNKbysgRNctZPln7cqQ

Making the access token request

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:
NameDescription
grant_typeUse the following string, URL-encoded as necessary: urn:ietf:params:oauth:grant-type:jwt-bearer
assertionThe 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
Below is the same request, using curl:
curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU3MzM4MSwiaWF0IjoxMzI4NTY5NzgxfQ.RZVpzWygMLuL-n3GwjW1_yhQhrqDacyvaXkuf8HcJl8EtXYjGjMaW5oiM5cgAaIorrqgYlp4DPF_GuncFqg9uDZrx7pMmCZ_yHfxhSCXru3gbXrZvAIicNQZMFxrEEn4REVuq7DjkTMyCMGCY1dpMa8aWfTQFt3Eh7smLchaZsU
' https://www.googleapis.com/oauth2/v3/token

Handling the response

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:
{
  "access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
  "token_type" : "Bearer",
  "expires_in" : 3600
}
Access tokens expire in one hour and can be reused until they expire.

Calling Google APIs


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):
curl -H "Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg" https://www.googleapis.com/plus/v1/people/me
Or, alternatively, the query string parameter option:
curl https://www.googleapis.com/plus/v1/people/me?access_token=1/fFBGRNJru1FQd44AzqT3Zg

When access tokens expire

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.

Wednesday, June 24, 2015

Что нужно учесть при разработке API


Preambule:
Как API разрабатывается в Гугле:
http://lanyrd.com/2010/io2010/smwf/


Оригинал
http://habrahabr.ru/post/181988/


Разработка web API перевод

Интро


Это краткий перевод основных тезисов из брошюры «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. Многие разработчки используют глаголы для описания объектов. Ясное дело, что в работе часто приходится моделировать сложные сущности. И эти сущности взаимодействуют между собой. Но при попытке ввести глаголы для моделирования сущностей и их связей, мы, скорее всего, получим большое количество труднозапоминаемых и непонятных вызовов:
/getAllDogs
/getAllLeashedDogs
/getDog
/newDog
/saveDog

Видите эти вызовы? Это ужас.

Вместо глаголов — HTTP

Мы только что описали собак с помощью двух базовых URL адресов с существительными. Теперь нам нужно работать с созданными сущностями. Чаще всего требуются операции чтения, создания, редактирования и удаления (CRUD — Create — Read — Update — Delete). Для этого нам прекрасно подойдут HTTP-методы GETPOSTPUT и 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
HTTP Status Code: 401
{"status" : "401", "message":"Authenticate","code": 20003, "more info": "http://www.twilio.com/docs/errors/20003"}

Twilio проделали хорошую работу и для каждой ошибки в API подобрали адекватный код ошибки HTTP. Как и Facebook, ребята предоставляют информацию об ошибке еще и в теле ответа. И, что самое прикольное, они дают ссылку на документацию по проблеме.
SimpleGeo
HTTP Status Code: 401
{"code" : 401, "message": "Authentication Required"}

SimpleGeo дают сообщение об ошибке в коде HTTP и снабжают его небольшим пояснением в теле ответа.

Используйте коды ответов HTTP

Смело берите HTTP коды ответов и сопоставляйте с ответами вашего API. Всего в частом употреблении находится около 70-ти кодов. Мало кто из разработчиков помнит их все, так что из этих 70-ти лучше взять примерно 10. Кстати, так поступает большая часть провайдеров API.
Google GData
200 201 304 400 401 403 404 409 410 500

Netflix
200 201 304 400 401 403 404 412 500

Digg
200 400 401 403 404 410 500 503

Какие коды ошибок HTTP стоит использовать?

Возможно только 3 варианта ответов API
  1. Запрос прошел успешно
  2. На вход были переданы неправильные данные — клиентская ошибка
  3. Произошла ошибка при обработке данных — серверная ошибка

Так что можно взять за основу 3 кода ответов:
  1. 200 OK
  2. 400 Bad Request (некорректный запрос)
  3. 500 Internal server error (внутренняя ошибка сервера)

Если 3-х кодов вам недостаточно — возьмите еще 5:
  1. 201 Created (Запись создана)
  2. 304 Not Modified (Данные не изменились)
  3. 404 Not Found (Данные не найдены)
  4. 401 Unauthorized (Неавторизованный доступ)
  5. 403 Forbidden (Доступ запрещен)

Лучше всего не следовать этой практике слепо. Оценивайте пользу от использования HTTP кодов ответов
в каждом конкретном случае. Скорее всего, использование кодов ответов не везде будет оправданным и уместным. Например, если вы пишете бэкенд для небольшого веб-приложения — то легко можно ограничиться кодами ошибок в теле ответа. А еще стандартый ответ 200 OK позволит создать два механимза обработки ошибок: для ошибок сервера и для ошибок самого API. В общем — думайте, взвешивайте. А потом принимайте решение.


И, конечно же, при ошибке всегда нужно прикладывать сообщение для разработчиков. А приложить к сообщению ссылку на документацию по проблеме — это еще лучше.

Никогда не выпускайте API без указания версии

Twilio /2010-04-01/Accounts
salesforce.com /services/data/v20.0/sobjects/Account
Facebook ?v=1.0

Twilio требует при каждом запросе к API передавать время, когда приложение разработчика было скомпилировано. На основе этой даты Twilio определяет, какую версию API нужно предоставить приложению. Это умный и интересный подход, но слишком сложный. А еще можно легко запутаться с датами.

Salesforce.com вставляет v20.0 в середину адреса API запроса. И это очень хороший подход. Но не стоит использовать точку в нумерации версии — это провоцирует излишне частые изменения в интерфейсе API. Можно сколь угодно часто менять логику работы внутри API, но вот сами интерфейсы должны меняться максимально редко. Так что лучше обойтись без точки и не искушать себя.

Facebook тоже использует нумерацию версий в запросе, но прячет её в параметры запроса. И этот подход плох тем, что после очередного внедрения новой версии API все приложения, не передающие версию в запросе, начинают глючить.

Как реализовать версии в API?


Используйте префикс v, целые числа и располагайте номер версии в левой части адреса. Например, /v1/dogs.
Держите в рабочем виде как минимум одну предыдущую версию

Еще можно указывать версию в заголовках ответа сервера. Это может давать некоторые дополнительные возможности при работе с API. Но если вы используете множество разных версий и требуете обязательно указывать их в заголовках — это симптом большой проблемы.

Частичный ответ

Частичный ответ позволяет разработчикам запросить только ту информацию, которая им нужна. Например, запросы к некоторым API могут вернуть кучу лишней информации, которая почти не используется: всякие таймстампы, метаданные и т.д. Чтобы не запрашивать лишнюю информацию, в Google придумали частичный ответ.
Linkedin /people: (id, first-name, last-name, industry)
Facebook /joe.smith/friends?fields=id,name,picture
Google ?fields=title, media:group(media:thumbnail)

Перечислять необходимые поля через запятую в адресе запроса — это очень простой и удобный подход. Берите его на вооружение.

Сделайте простую паджинацию

Отдавать все записи по первому же запросу — очень плохая идея. Поэтому вы должны обязательно предусмотреть паджинацию. Давайте посмотрим, как в популярных 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. Его поддерживают все популярные языки. Его можно сразу же использовать на фронт-энде веб-приложения.

Названия атрибутов

Атрибуты можно называть разными способами.
Twitter created_at
Bing DateTime
Foursquare createdAt

Существует много конвенций именования переменных. Нам, как спецам по 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 из которых ориентированы на посты и поиск
stream.twitter.com
api.twitter.com
search.twitter.com

Легко догадаться, как Facebook и Twitter завели себе по несколько адресов: проще направлять запросы в разные кластеры через DNS, чем через логику. Но мы делаем приятный API для разработчиков, поэтому опять выберем подход Foursquare.

На всякий случай напомню, что разработчикам небольшого бэкенда для веб-приложения не надо выделять отдельный домен, чтобы не создавать проблемы с кроссдоменными ajax-запросами на фронт-энде.

Делайте редиректы

Если кто-то обращается к вашему API-домену и не передает никаких параметров — смело делайте редирект на домен с документацией для разработчиков. Заведите несколько интуитивно понятных доменов для документации и делайте редирект на основной домен разработчиков.
api.* -> developers.*
dev.* -> developers.*
developer.* -> developers.*


Коды HTTP ответов и исключения на клиенте

Как мы уже говорили ранее, лучше всего отправлять код ошибки не только в теле ответа API, но и в HTTP коде ответа. Но как быть, если клиент выбрасывает исключение при получении любого кода HTTP, отличного от 200? Для таких случаев ребята из Twitter предусмотрели блестящее и простое решение — добавлять параметр к запросу.
/public_timelines.json?suppress_response_code=true

В результате ошибки будут приходить с кодом 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% вызовов принимают и отдают данные одинаковой структуры. Это значит, что вполне можно сделать псевдонимы для последовательностей вызовов. После этого пользователь сможет единожды направить данные на вход, и вся цепочка вызовов выполнится сама.

Tuesday, June 23, 2015

Web API Authentication, Authorization


Forms Authentication using Web API


If using Identity framework is not possible, one can add the old school forms authentication method.

Introduction

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.
public class BasicAuthMessageHandler : DelegatingHandler
    {
        private const string BasicAuthResponseHeader = "WWW-Authenticate";
        private const string BasicAuthResponseHeaderValue = "Basic";

        public adminPrincipalProvider PrincipalProvider = new adminPrincipalProvider();

        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authValue = request.Headers.Authorization;
            if (authValue != null && authValue.Parameter != "undefined" && 
    !String.IsNullOrWhiteSpace(authValue.Parameter))
            {
                string email = authValue.Parameter;
                if (HttpContext.Current.Session == null || 
  HttpContext.Current.Session["userToken"] == null || 
  string.IsNullOrEmpty(HttpContext.Current.Session["userToken"].ToString()))
                {
                    HttpContext.Current.Session["userToken"] = email;
                }
                else
                {
                    email = HttpContext.Current.Session["userToken"].ToString();
                }

                if (!string.IsNullOrEmpty(email))
                {
                    IPrincipal principalObj = PrincipalProvider.createPrincipal(email, "Admin");
                    Thread.CurrentPrincipal = principalObj;
                    HttpContext.Current.User = principalObj;
                }
            }
            return base.SendAsync(request, cancellationToken)
               .ContinueWith(task =>
               {
                   var response = task.Result;
                   if (response.StatusCode == HttpStatusCode.Unauthorized
                       && !response.Headers.Contains(BasicAuthResponseHeader))
                   {
                       response.Headers.Add(BasicAuthResponseHeader
                           , BasicAuthResponseHeaderValue);
                   }
                   return response;
               });
        }
    }
Principal object is used to assign role to a validated user, this principal object is added to HttpContext's user property.

Controller Login & Logout Web Method

       [HttpPost, AllowAnonymous, Route("login")]
        public async Task<HttpResponseMessage> Login([FromBody]LoginRequest request)
        {
            var loginService = new LoginService();
            LoginResponse response = await loginService.LoginAsync(request.username, request.password);
            if (response.Success)
            {
                FormsAuthentication.SetAuthCookie(response.Token, false);
            }
            return Request.CreateResponse(HttpStatusCode.OK, response);
        }

        [HttpPost, AllowAnonymous, Route("logout")]
        public void Signout()
        {
            FormsAuthentication.SignOut();

            if (HttpContext.Current.Session != null)
                HttpContext.Current.Session.Abandon();
        }
To setup role based authorization on webmethods, the following attributes are to be added on the top of webmethod's implementation.
[HttpGet, Authorize(Roles = "admin"), Route("name")]

Calling from Client

The following jquery code shows how to make a Login call.
$(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.
 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var basicAuthMessageHandler = new WebAPI_FormsAuth.Helper.BasicAuthMessageHandler();
            basicAuthMessageHandler.PrincipalProvider = 
   new WebAPI_FormsAuth.Helper.adminPrincipalProvider();
            //start message handler
            GlobalConfiguration.Configuration.MessageHandlers.Add(basicAuthMessageHandler);
        }




http://weblog.west-wind.com/posts/2013/Apr/18/A-WebAPI-Basic-Authentication-Authorization-Filter