Wednesday, July 22, 2015

HTTP Status Codes in API

http://www.restapitutorial.com/httpstatuscodes.html


1xx Informational[edit]

Request received, continuing process.
This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. Since HTTP/1.0 did not define any 1xx status codes, servers must not[note 1] send a 1xx response to an HTTP/1.0 client except under experimental conditions.
100 Continue
This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).
101 Switching Protocols
This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.
102 Processing (WebDAV; RFC 2518)
As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[3] This prevents the client from timing out and assuming the request was lost.

2xx Success[edit]

This class of status codes indicates the action requested by the client was received, understood, accepted and processed successfully.
200 OK
Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request, the response will contain an entity describing or containing the result of the action.
201 Created
The request has been fulfilled and resulted in a new resource being created.
202 Accepted
The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
203 Non-Authoritative Information (since HTTP/1.1)
The server successfully processed the request, but is returning information that may be from another source.
204 No Content
The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request.
205 Reset Content
The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.
206 Partial Content (RFC 7233)
The server is delivering only part of the resource (byte serving) due to a range header sent by the client. The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.
207 Multi-Status (WebDAV; RFC 4918)
The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.[4]
208 Already Reported (WebDAV; RFC 5842)
The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again.
226 IM Used (RFC 3229)
The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.[5]

3xx Redirection[edit]

This class of status code indicates the client must take additional action to complete the request. Many of these status codes are used in URL redirection.
A user agent may carry out the additional action with no user interaction only if the method used in the second request is GET or HEAD. A user agent should not automatically redirect a request more than five times, since such redirections usually indicate an infinite loop.
300 Multiple Choices
Indicates multiple options for the resource that the client may follow. It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.
301 Moved Permanently
This and all future requests should be directed to the given URI.
302 Found
This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"),[6] but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.[7] However, some Web applications and frameworks use the 302 status code as if it were the 303.[8]
303 See Other (since HTTP/1.1)
The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.
304 Not Modified (RFC 7232)
Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. This means that there is no need to retransmit the resource, since the client still has a previously-downloaded copy.
305 Use Proxy (since HTTP/1.1)
The requested resource is only available through a proxy, whose address is provided in the response. Many HTTP clients (such as Mozilla[9] and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.[10]
306 Switch Proxy
No longer used. Originally meant "Subsequent requests should use the specified proxy."[11]
307 Temporary Redirect (since HTTP/1.1)
In this case, the request should be repeated with another URI; however, future requests should still use the original URI. In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request. For instance, a POST request should be repeated using another POST request.[12]
308 Permanent Redirect (RFC 7538)
The request, and all future requests should be repeated using another URI. 307 and 308 (as proposed) parallel the behaviours of 302 and 301, but do not allow the HTTP method to change. So, for example, submitting a form to a permanently redirected resource may continue smoothly.[13]
308 Resume Incomplete (Google)
This code is used in the Resumable HTTP Requests Proposal to resume aborted PUT or POST requests.[14]

4xx Client Error[edit]

A 404 error on the German language Wikipedia.
404 error on German Wikipedia
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents should display any included entity to the user.
400 Bad Request
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).[15]
401 Unauthorized (RFC 7235)
Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.
402 Payment Required
Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, but that has not happened, and this code is not usually used. YouTube uses this status if a particular IP address has made excessive requests, and requires the person to enter aCAPTCHA.[citation needed]
403 Forbidden
The request was a valid request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.
404 Not Found
The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible.
405 Method Not Allowed
A request was made of a resource using a request method not supported by that resource; for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.
406 Not Acceptable
The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.
407 Proxy Authentication Required (RFC 7235)
The client must first authenticate itself with the proxy.
408 Request Timeout
The server timed out waiting for the request. According to HTTP specifications: "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
409 Conflict
Indicates that the request could not be processed because of conflict in the request, such as an edit conflict in the case of multiple updates.
410 Gone
Indicates that the resource requested is no longer available and will not be available again. This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. Clients such as search engines should remove the resource from their indices.[16] Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
411 Length Required
The request did not specify the length of its content, which is required by the requested resource.
412 Precondition Failed (RFC 7232)
The server does not meet one of the preconditions that the requester put on the request.
413 Payload Too Large (RFC 7231)
The request is larger than the server is willing or able to process. Called "Request Entity Too Large " previously.
414 Request-URI Too Long
The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request, in which case it should be converted to a POST request.
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
416 Requested Range Not Satisfiable (RFC 7233)
The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. For example, if the client asked for a part of the file that lies beyond the end of the file.
417 Expectation Failed
The server cannot meet the requirements of the Expect request-header field.
418 I'm a teapot (RFC 2324)
This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by tea pots requested to brew coffee.
419 Authentication Timeout (not in RFC 2616)
Not a part of the HTTP standard, 419 Authentication Timeout denotes that previously valid authentication has expired. It is used as an alternative to 401 Unauthorized in order to differentiate from otherwise authenticated clients being denied access to specific server resources.[citation needed]
420 Method Failure (Spring Framework)
Not part of the HTTP standard, but defined by Spring in the HttpStatus class to be used when a method failed. This status code is deprecated by Spring.
420 Enhance Your Calm (Twitter)
Not part of the HTTP standard, but returned by version 1 of the Twitter Search and Trends API when the client is being rate limited.[17] Other services may wish to implement the 429 Too Many Requests response code instead.
421 Misdirected Request (HTTP/2)
The request was directed at a server that is not able to produce a response (for example because a connection reuse).[18]
422 Unprocessable Entity (WebDAV; RFC 4918)
The request was well-formed but was unable to be followed due to semantic errors.[4]
423 Locked (WebDAV; RFC 4918)
The resource that is being accessed is locked.[4]
424 Failed Dependency (WebDAV; RFC 4918)
The request failed due to failure of a previous request (e.g., a PROPPATCH).[4]
426 Upgrade Required
The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.
428 Precondition Required (RFC 6585)
The origin server requires the request to be conditional. Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."[19]
429 Too Many Requests (RFC 6585)
The user has sent too many requests in a given amount of time. Intended for use with rate limiting schemes.[19]
431 Request Header Fields Too Large (RFC 6585)
The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.[19]
440 Login Timeout (Microsoft)
A Microsoft extension. Indicates that your session has expired.[20]
444 No Response (Nginx)
Used in Nginx logs to indicate that the server has returned no information to the client and closed the connection (useful as a deterrent for malware).
449 Retry With (Microsoft)
A Microsoft extension. The request should be retried after performing the appropriate action.[21]
450 Blocked by Windows Parental Controls (Microsoft)
A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.[22]
451 Unavailable For Legal Reasons (Internet draft)
Defined in the internet draft "A New HTTP Status Code for Legally-restricted Resources".[23] Intended to be used when resource access is denied for legal reasons, e.g. censorship or government-mandated blocked access. A reference to the 1953 dystopian novel Fahrenheit 451, where books are outlawed.[24]
451 Redirect (Microsoft)
Used in Exchange ActiveSync if there either is a more efficient server to use or the server cannot access the users' mailbox.[25]
The client is supposed to re-run the HTTP Autodiscovery protocol to find a better suited server.[26]
494 Request Header Too Large (Nginx)
Nginx internal code similar to 431 but it was introduced earlier in version 0.9.4 (on January 21, 2011).[27][original research?]
495 Cert Error (Nginx)
Nginx internal code used when SSL client certificate error occurred to distinguish it from 4XX in a log and an error page redirection.
496 No Cert (Nginx)
Nginx internal code used when client didn't provide certificate to distinguish it from 4XX in a log and an error page redirection.
497 HTTP to HTTPS (Nginx)
Nginx internal code used for the plain HTTP requests that are sent to HTTPS port to distinguish it from 4XX in a log and an error page redirection.
498 Token expired/invalid (Esri)
Returned by ArcGIS for Server. A code of 498 indicates an expired or otherwise invalid token.[28]
499 Client Closed Request (Nginx)
Used in Nginx logs to indicate when the connection has been closed by client while the server is still processing its request, making server unable to send a status code back.[29]
499 Token required (Esri)
Returned by ArcGIS for Server. A code of 499 indicates that a token is required (if no token was submitted).[28]

5xx Server Error[edit]

The server failed to fulfil an apparently valid request.
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has encountered an error or is otherwise incapable of performing the request. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and indicate whether it is a temporary or permanent condition. Likewise, user agents should display any included entity to the user. These response codes are applicable to any request method.
500 Internal Server Error
A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
501 Not Implemented
The server either does not recognize the request method, or it lacks the ability to fulfill the request. Usually this implies future availability (e.g., a new feature of a web-service API).
502 Bad Gateway
The server was acting as a gateway or proxy and received an invalid response from the upstream server.
503 Service Unavailable
The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.
504 Gateway Timeout
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
505 HTTP Version Not Supported
The server does not support the HTTP protocol version used in the request.
506 Variant Also Negotiates (RFC 2295)
Transparent content negotiation for the request results in a circular reference.[30]
507 Insufficient Storage (WebDAV; RFC 4918)
The server is unable to store the representation needed to complete the request.[4]
508 Loop Detected (WebDAV; RFC 5842)
The server detected an infinite loop while processing the request (sent in lieu of 208 Already Reported).
509 Bandwidth Limit Exceeded (Apache bw/limited extension)[31]
This status code is not specified in any RFCs. Its use is unknown.
510 Not Extended (RFC 2774)
Further extensions to the request are required for the server to fulfil it.[32]
511 Network Authentication Required (RFC 6585)
The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).[19]
520 Unknown Error
This status code is not specified in any RFC and is returned by certain services, for instance Microsoft Azure and CloudFlare servers: "The 520 error is essentially a “catch-all” response for when the origin server returns something unexpected or something that is not tolerated/interpreted (protocol violation or empty response)."[33]
598 Network read timeout error (Unknown)
This status code is not specified in any RFCs, but is used by Microsoft HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.[citation needed]
599 Network connect timeout error (Unknown)
This status code is not specified in any RFCs, but is used by Microsoft HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.[citation needed]


 "Top 10" HTTP Status Code. More REST service-specific information is contained in the entry.

Thursday, July 16, 2015

Secure your Web API with SHA-2 certificates

This article will be short but useful and thesis style.
SHA-1 is suxx and here is Google explanation for that https://konklone.com/post/why-google-is-hurrying-the-web-to-kill-sha-1

You can check if your site is using SHA-1 and you need to migrate it to SHA-2 for security reasons

Generate new certificate:


Friday, July 10, 2015

MVC Repository Pattern


Repository pattern is a very useful and powerful pattern when manipulating data. It enhance the maintainability and testability, as the data is accessed and edited from a unique access point which is the Repository. In this application, I used it inside an MVC5 app. So, whenever you want to make changes to the way you manipulate the data, you just change code in the repository, and you do that once.




https://www.youtube.com/watch?v=SExnyXhX3gk

Thursday, July 9, 2015

PostreSQL settings to allow remote connect

Открываем следующий файл на PostgreSQL сервере
C:\Program Files\PostgreSQL\9.4\data\pg_hba.conf

Добавляем строку:

host    all             my_login         your_ip/32            md5

Не удается подключиться к базе данных (no pg_hba.conf entry for host "xxx.xxx.xxx.xxx"...)

$ psql -U my_login -h 10.0.0.101 postgres

psql: FATAL:  no pg_hba.conf entry for host "10.0.0.1", user "my_login", database "postgres", SSL on
FATAL:  no pg_hba.conf entry for host "10.0.0.1", user "my_login", database "postgres", SSL off
Подобная ошибка возникает, если для пользователя my_login не указано, что он может подключаться с ip-адреса 10.0.0.1

Решение

Настройка доступа к базе данных осуществляется через файл pg_hba.conf. Найти его можно командой:
$ find / -name pg_hba.conf 2>/dev/null

/etc/postgresql/9.2/main/pg_hba.conf
Необходимо добавить в файл новую строку, которая разрешит доступ логина my_login к любой базе данных с ip-адреса 10.0.0.1:
host    all             my_login         10.0.0.1/32            md5
После этого необходимо обновить конфигурацию сервера командой:
$ sudo service postgresql reload

* Reloading PostgreSQL 9.2 database server                                                                                                  [ OK ]
Теперь можно попробовать подключиться к базе данных:
$ psql -U my_login -h 10.0.0.101 postgres

Password for user my_login: *****
psql (9.2.1)
Type "help" for help.

postgres=#
или же может появится ошибка:
psql: FATAL:  password authentication failed for user "my_login"
FATAL:  password authentication failed for user "my_login"
это ошибка возникает, если введен неверный пароль для указанного пользователя или пользователь в базе данных не существует. В этом случае поможет рецепт как создавать пользователей

Дополнительная информация

Tuesday, July 7, 2015

Entity Framework 7: Data for Web, Phone, Store, and Desktop

https://channel9.msdn.com/Events/Build/2015/2-693

https://github.com/rowanmiller/UnicornStore

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.