Updates

Destructuring Assignment to Object Properties in JavaScript

TLDR; I was wondering whether it would be possible to use Destructuring Assignment to assign a value directly to a property of an Object. Somehow I was not able to find any info about this online, not even on the MDN pages. Turns out it is possible, see below.

I’m sure that by now we all know about destructuring assignment in JavaScript. The straight forward destructuring assignment of an Array looks like this:

// suppose we have the array:
const x = [2, 3, 4, 5, 6];

// now we can assign values like this:
const [a] = x;        // a === 2
const [,b] = x;       // b === 3
const [,,c, ...rest]; // c === 4 && rest === [5, 6]

With Objects it’s also possible to use destructuring assignment:

// suppose we have the object
const y = {k: 42, l:96, m: 15, n: 16};

// assignment can be done like this
let {k} = y;                // k === 42
let {l: d} = y;             // d === 96
let {k, l: d, ...rest} = y; // k === 42 && d === 96 && rest === {m: 15, n: 16}

It’s even possible to use destructuring with function parameters:

// destructuring function parameters
function q({a, b}){
    console.log(a, b);
}

q({a: 3, b: 5}); // logs: 3 5

// destructuring with reassignment
function r({a: x, b: y}){
    console.log(x, y);
}

r({a: 33, b: 55}); // logs: 33 55

// with default values
function s({a = 3, b = 5, c = 7} = {}){
    console.log(a, b, c);
}

s();        // logs: 3 5 7
s({b: 42}); // logs: 3 42 7

// with default values, nested objects and reassignment
function t({a: x = 3, b: y = 5, some: {value: z = 'empty'}} = {}){
    console.log(x, y, z);
}

t({a: 6, some: {otherValue: 7}}); // logs: 6 5 "empty"

There are plenty more variants, like swapping values and using defaults. Most of them can be found in articles all over the internet, like for instance on MDN.

// swapping variables
let x = 16;
let y = 22;
[y, x] = [x, y]; // x === 22 && y === 16 

// using defaults
const x = [2, 3, 4];
const [,, a = 6, b = 8] = x; // a === 4 && b === 8

Assigning directly to an Object Property

One thing I don’t usually see anything written about though is assigning to a property of an object using destructuring assignment. I’m talking about something like this:

const x = [2, 3, 4];
const y = {z: 42};

// instead of doing this
y.z = x[1]; // y.z === 3

// we can write:
[,y.z] = x; // y.z === 3 👌 sweet!

Pure CSS star rating

Recently I was reading an article about a simple star rating system using vanilla JS, CSS and HTML. It got me thinking about whether it would be possible to recreate something similar with just CSS… and a tiny bit of HTML on the side.

You can see the result below and on CodePen, I think the code is self explanatory.

 

See the Pen Pure CSS Star Rating by Bjørn (@magikMaker) on CodePen.

 

In case you would like to send the selected rating back to a server, it’s very easy to get the selected star using this tiny JavaScript snippet:

document.querySelector('.rating').addEventListener('click', event => {
    // figure out which star was clicked
    const rating = Array
        .from(event.currentTarget.querySelectorAll('input'))
        .indexOf(event.target) + 1;
 
    // example: get the id 
    // const id = event.currentTarget.getAttribute('id').match(/\d+$/);
 
    // then somehow post the info to the server or save locally or...
    // post(`https://some-server.it/ratings/${id}`, {rating});
 });

Jira ticket number in Git commit

Just like many developers these days, I often find myself working on a project where we use Jira to track our work and progress. When using Jira and Bitbucket to to track source code that lives in Git repositories, it can be very convenient to write the Jira ticket id’s in the Git commit messages. This way both Bitbucket and Jira will pick it up and display everything neatly together.

However, writing the Jira ticket in every commit message can become quite the challenge. I for one always forget to add it. So I wrote an npm package, called magik-commit, to do it for me.

It’s pretty simple. When creating a new Git branch, make sure that the ticket number is part of the branch name. This can be easily accomplished by using the “create branch” button from Jira. This is only available when using Jira in conjunction with Bitbucket though. So, if you’re not using Bitbucket, just create the branch name like this:

feature/JIRA-42-some-new-awesomeness

After installing the module via npm, every commit message you create will be prepended with the Jira ticket id, `JIRA-42` in this case.

This will also work when using other issue trackers, as long as your ticket id’s are in the format recognised by magik-commit. Have a look at the magik-commit on npmjs.org for more information.

Pure CSS Responsive Images (Yes, without JavaScript)

There are numerous ways to implement responsive images in webpages. However, all solutions I came across make use of JavaScript. That made me wonder whether it would be possible to implement responsive images without the use of JavaScript.

I came up with this solution that is pure CSS.

How does it work?

I placed an <img> tag within a <span>. The src attribute will fetch the mobile version of the image from the server. Then I also include a bit of CSS within the <span> element.

What?! Embedded CSS in the HTML document?

Yes, that is perfectly valid in HTML5 as long as you add the scoped attribute. In the CSS I use an @media query to add the high resolution image as a background to the <span> from a certain breakpoint. In the code below I’ve only added one breakpoint, but you can add as many as you like of course.

By using a background image, it will only be fetched from the server when needed. That is, only when the media query is satisfied. The <img> will make sure the <span> will have the proper width and height ratio so the background image on that <span> is displayed properly.

Show me the code

Here is the code to make it all work.

The HTML

First the HTML.


<span class="magik-responsive-image" id="image-01">
<img src="http://dummyimage.com/200x150/cdcdcd/000/?text=lo-res">
<style scoped>
@media screen and (min-width: 701px){#image-01{background-image:url(http://dummyimage.com/1600x1200/dcdcdc/000/?text=hi-res);}}
</style>
</span>

The CSS

We also need a little bit of extra CSS to hide the lo-res image when the hi-res image should be displayed. The trick is to add background-size: 100%;, this will stretch the background while maintaining the aspect ratio.


.magik-responsive-image {
background-repeat: no-repeat;
background-size: 100%;
display: block;
position: relative;
}

.magik-responsive-image img {
max-width: 100%;
width: 100%;
}

@media screen and (min-width: 701px) {

.magik-responsive-image img{
opacity: 0;
}
}

The pros

  • No JavaScript
  • Simple to implement
  • Also works for videos (I’ll post about that in a future post)

The cons

  • On desktop there are two requests made to the server.
  • The scoped attribute of the <style> tag is not yet supported in any of the major browsers. Because of this, we need to add an id, but this usually is not a problem to add in the back-end code.

 

 The Demo

have a look at this fiddle

 

Chrome stopped displaying apps in new tab after update

Yesterday chrome was updated to version 29. Usually I don’t even notice an update, but this time it was really apparent. When opening a new tab, now there is a search bar displayed with the most visited websites. I have no idea why anybody would come up with such a stupid idea. In fact, I got so irritated by it, that I decided to restore the old functionality of displaying apps in the new tab.

Here’s my Chrome extension that fixes the problem.

440x280

OAuth documention mirror

This is a mirror of the original found here: oauth.net/core/1.0a. I put it here for my own convenience because the oauth.net website is e-x-t-r-e-m-e-l-y-s-l-o-w…

Keep in mind that this specification has been obsoleted by RFC 5849.
The OAuth 1.0 Protocol. Implementers should use RFC 5849 instead of this specification.

June 24, 2009

OAuth Core 1.0 Revision A

License

This specification was derived from the OAuth Core 1.0 specification which was made available under the OAuth Non-Assertion Covenant and Author’s Contribution License For OAuth Specification 1.0 available at http://oauth.net/license/core/1.0. The changes between OAuth Core 1.0 and OAuth Core 1.0 Revision A have not yet been covered by a license. All changes were made by employees of Google and Yahoo! and both companies are in the process of granting the same agreement available for OAuth Core 1.0.

Changes from OAuth Core 1.0

OAuth Core 1.0 Revision A was created to address a session fixation attack identified in the OAuth Core 1.0 specification as detailed in http://oauth.net/advisories/2009-1. A full inventory of changes is available in the specification repository.

Abstract

The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers. More generally, OAuth creates a freely-implementable and generic methodology for API authentication.

An example use case is allowing printing service printer.example.com (the Consumer), to access private photos stored on photos.example.net (the Service Provider) without requiring Users to provide their photos.example.net credentials to printer.example.com.

OAuth does not require a specific user interface or interaction pattern, nor does it specify how Service Providers authenticate Users, making the protocol ideally suited for cases where authentication credentials are unavailable to the Consumer, such as with OpenID.

OAuth aims to unify the experience and implementation of delegated web service authentication into a single, community-driven protocol. OAuth builds on existing protocols and best practices that have been independently implemented by various websites. An open standard, supported by large and small providers alike, promotes a consistent and trusted experience for both application developers and the users of those applications.


Table of Contents

 


1.
Authors

  • Mark Atwood ()
  • Dirk Balfanz ()
  • Darren Bounds ()
  • Richard M. Conlan ()
  • Blaine Cook ()
  • Leah Culver ()
  • Breno de Medeiros ()
  • Brian Eaton ()
  • Kellan Elliott-McCrea ()
  • Larry Halff ()
  • Eran Hammer-Lahav (), Editor
  • Ben Laurie ()
  • Chris Messina ()
  • John Panzer ()
  • Sam Quigley ()
  • David Recordon ()
  • Eran Sandler ()
  • Jonathan Sergent ()
  • Todd Sieling ()
  • Brian Slesinsky ()
  • Andy Smith ()

 


2.
Notation and Conventions

The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”,
“SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this
document are to be interpreted as described in [RFC2119] (Bradner, B., “Key words for use in RFCs to Indicate Requirement Levels,” .).
Domain name examples use [RFC2606] (Eastlake, D. and A. Panitz, “Reserved Top Level DNS Names,” .).

 


3.
Definitions

Service Provider:
A web application that allows access via OAuth.
User:
An individual who has an account with the Service Provider.
Consumer:
A website or application that uses OAuth to access the Service
Provider on behalf of the User.
Protected Resource(s):
Data controlled by the Service Provider, which the Consumer can
access through authentication.
Consumer Developer:
An individual or organization that implements a Consumer.
Consumer Key:
A value used by the Consumer to identify itself to the Service
Provider.
Consumer Secret:
A secret used by the Consumer to establish ownership of the
Consumer Key.
Request Token:
A value used by the Consumer to obtain authorization from the User,
and exchanged for an Access Token.
Access Token:
A value used by the Consumer to gain access to the Protected
Resources on behalf of the User, instead of using the User’s
Service Provider credentials.
Token Secret:
A secret used by the Consumer to establish ownership of a given
Token.
OAuth Protocol Parameters:
Parameters with names beginning with oauth_.

 


4.
Documentation and Registration

OAuth includes a Consumer Key and matching Consumer Secret that
together authenticate the Consumer (as opposed to the User) to the
Service Provider. Consumer-specific identification allows the Service
Provider to vary access levels to Consumers (such as un-throttled access
to resources).

Service Providers SHOULD NOT rely on the Consumer Secret as a method to
verify the Consumer identity, unless the Consumer Secret is known to be
inaccessible to anyone other than the Consumer and the Service
Provider. The Consumer Secret MAY be an empty string (for example when
no Consumer verification is needed, or when verification is achieved
through other means such as RSA).


4.1.
Request URLs

OAuth defines three request URLs:

Request Token URL:
The URL used to obtain an unauthorized Request Token, described
in Section 6.1 (Obtaining an Unauthorized Request Token).
User Authorization URL:
The URL used to obtain User authorization for Consumer access,
described in Section 6.2 (Obtaining User Authorization).
Access Token URL:
The URL used to exchange the User-authorized Request Token for
an Access Token, described in Section 6.3 (Obtaining an Access Token).

The three URLs MUST include scheme, authority, and path, and MAY
include query and fragment as defined by [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .)
section 3. The request URL query MUST NOT contain any OAuth Protocol
Parameters. For example:

http://sp.example.com/authorize

 


4.2.
Service Providers

The Service Provider’s responsibility is to enable Consumer Developers
to establish a Consumer Key and Consumer Secret. The process and
requirements for provisioning these are entirely up to the Service
Providers.

The Service Provider’s documentation includes:

  1. The URLs (Request URLs) the Consumer will
    use when making OAuth requests, and the HTTP methods (i.e. GET,
    POST, etc.) used in the Request Token URL and Access Token URL.
  2. Signature methods supported by the Service Provider.
  3. Any additional request parameters that the Service Provider
    requires in order to obtain a Token. Service Provider specific
    parameters MUST NOT begin with oauth_.

 


4.3.
Consumers

The Consumer Developer MUST establish a Consumer Key and a Consumer
Secret with the Service Provider. The Consumer Developer MAY also be
required to provide additional information to the Service Provider
upon registration.

 


5.
Parameters

OAuth Protocol Parameter names and values are case sensitive. Each
OAuth Protocol Parameters MUST NOT appear more than once per request,
and are REQUIRED unless otherwise noted.


5.1.
Parameter Encoding

All parameter names and values are escaped using the
[RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) percent-encoding (%xx) mechanism.
Characters not in the unreserved character set
([RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) section 2.3) MUST be encoded. Characters
in the unreserved character set MUST NOT be encoded. Hexadecimal
characters in encodings MUST be upper case. Text names and values
MUST be encoded as UTF-8 octets before percent-encoding them per
[RFC3629] (Yergeau, F., “UTF-8, a transformation format of Unicode and ISO 10646,” .).

unreserved = ALPHA, DIGIT, '-', '.', '_', '~'

 


5.2.
Consumer Request Parameters

OAuth Protocol Parameters are sent from the Consumer to the Service
Provider in one of three methods, in order of decreasing preference:

  1. In the HTTP Authorization header as defined in
    OAuth HTTP Authorization Scheme (OAuth HTTP Authorization Scheme).
  2. As the HTTP POST request body with a
    content-type
    of
    application/x-www-form-urlencoded.
  3. Added to the URLs in the query part (as defined by
    [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) section 3).

In addition to these defined methods, future extensions may describe
alternate methods for sending the OAuth Protocol Parameters.
The methods for sending other request parameters are left
undefined, but SHOULD NOT use the
OAuth HTTP Authorization Scheme (OAuth HTTP Authorization Scheme) header.


5.3.
Service Provider Response Parameters

Response parameters are sent by the Service
Provider to return Tokens and other information to the Consumer in
the HTTP response body. The parameter names and values are first
encoded as per Parameter Encoding (Parameter Encoding), and concatenated with the ‘&’ character (ASCII code 38)
as defined in [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) Section 2.1. For example:

oauth_token=ab3cd9j4ks73hf7g&oauth_token_secret=xyz4992k83j47x0b

 


5.4.
OAuth HTTP Authorization Scheme

This section defines an [RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .) extension to
support OAuth. It uses the standard HTTP Authorization and
WWW-Authenticate headers to pass OAuth Protocol Parameters.

It is RECOMMENDED that Service Providers accept the HTTP
Authorization header. Consumers SHOULD be able to send OAuth
Protocol Parameters in the OAuth Authorization header.

The extension auth-scheme (as defined by
[RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .)) is OAuth and is case-insensitive.


5.4.1.
Authorization Header

The OAuth Protocol Parameters are sent in the Authorization
header the following way:

  1. Parameter names and values are encoded per
    Parameter Encoding (Parameter Encoding).
  2. For each parameter, the name is immediately followed by an ‘=’
    character (ASCII code 61), a ‘”‘ character (ASCII code 34), the
    parameter value (MAY be empty), and another ‘”‘ character
    (ASCII code 34).
  3. Parameters are separated by a comma character (ASCII code 44)
    and OPTIONAL linear whitespace per [RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .).
  4. The OPTIONAL realm parameter is added and interpreted per
    [RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .), section 1.2.

For example:

                Authorization: OAuth realm="http://sp.example.com/",
                oauth_consumer_key="0685bd9184jfhq22",
                oauth_token="ad180jjd733klru7",
                oauth_signature_method="HMAC-SHA1",
                oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
                oauth_timestamp="137131200",
                oauth_nonce="4572616e48616d6d65724c61686176",
                oauth_version="1.0"

 


5.4.2.
WWW-Authenticate Header

Service Providers MAY indicate their support for the extension by
returning the OAuth HTTP WWW-Authenticate
header upon Consumer requests for Protected Resources. As per
[RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .) such a response MAY include additional
HTTP WWW-Authenticate headers:

For example:

                WWW-Authenticate: OAuth realm="http://sp.example.com/"

The realm parameter defines a protection realm per
[RFC2617] (Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” .), section 1.2.

 


6.
Authenticating with OAuth

OAuth authentication is the process in which Users grant access to
their Protected Resources without sharing their credentials with the
Consumer. OAuth uses Tokens generated by the Service Provider instead
of the User’s credentials in Protected Resources requests. The process
uses two Token types:

Request Token:
Used by the Consumer to ask the User to authorize access to the
Protected Resources. The User-authorized Request Token is exchanged
for an Access Token, MUST only be used once, and MUST NOT be used
for any other purpose. It is RECOMMENDED that Request Tokens have
a limited lifetime.
Access Token:
Used by the Consumer to access the Protected Resources on behalf of
the User. Access Tokens MAY limit access to certain Protected
Resources, and MAY have a limited lifetime. Service Providers
SHOULD allow Users to revoke Access Tokens. Only the Access Token
SHALL be used to access the Protect Resources.

OAuth Authentication is done in three steps:

  1. The Consumer obtains an unauthorized Request Token.
  2. The User authorizes the Request Token.
  3. The Consumer exchanges the Request Token for an Access Token.


6.1.
Obtaining an Unauthorized Request Token

The Consumer obtains an unauthorized Request Token by asking the
Service Provider to issue a Token. The Request Token’s sole purpose
is to receive User approval and can only be used to obtain an Access
Token. The Request Token process goes as follows:


6.1.1.Consumer Obtains a Request Token

To obtain a Request Token, the Consumer sends an HTTP request to
the Service Provider’s Request Token URL. The Service Provider
documentation specifies the HTTP method for this request, and HTTP POST
is RECOMMENDED. The request MUST be signed and contains the following parameters:

oauth_consumer_key:
The Consumer Key.
oauth_signature_method:
The signature method the Consumer used to sign the request.
oauth_signature:
The signature as defined in
Signing Requests (Signing Requests).
oauth_timestamp:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_nonce:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_version:
OPTIONAL. If present, value MUST be
1.0
. Service Providers
MUST assume the protocol version to be 1.0 if this parameter
is not present. Service Providers’ response to non-1.0 value
is left undefined.
oauth_callback:
An absolute URL to which the Service Provider will redirect the User back when the
Obtaining User Authorization (Obtaining User Authorization) step is completed. If the
Consumer is unable to receive callbacks or a callback URL has been established via other
means, the parameter value MUST be set to oob (case sensitive),
to indicate an out-of-band configuration.
Additional parameters:
Any additional parameters, as defined by the Service Provider.


6.1.2.
Service Provider Issues an Unauthorized Request Token

The Service Provider verifies the signature and Consumer Key. If
successful, it generates a Request Token and Token Secret and
returns them to the Consumer in the HTTP response body as defined
in Service Provider Response Parameters (Service Provider Response Parameters).
The Service Provider MUST ensure the Request
Token cannot be exchanged for an Access Token until the User
successfully grants access in Obtaining
User Authorization (Obtaining User Authorization)
.

The response contains the following parameters:

oauth_token:
The Request Token.
oauth_token_secret:
The Token Secret.
oauth_callback_confirmed:
MUST be present and set to true. The Consumer
MAY use this to confirm that the Service Provider received the callback value.
Additional parameters:
Any additional parameters, as defined by the Service Provider.

If the request fails verification or is rejected for other reasons,
the Service Provider SHOULD respond with the appropriate response
code as defined in HTTP Response Codes (HTTP Response Codes).
The Service Provider MAY include some further details about why the
request was rejected in the HTTP response body as defined in
Service Provider Response Parameters (Service Provider Response Parameters).


6.2.
Obtaining User Authorization

The Consumer cannot use the Request Token until it has been
authorized by the User. Obtaining User authorization includes
the following steps:


6.2.1.
Consumer Directs the User to the Service Provider

In order for the Consumer to be able to exchange the Request Token
for an Access Token, the Consumer MUST obtain approval from the
User by directing the User to the Service Provider. The Consumer
constructs an HTTP GET request to the Service Provider’s
User Authorization URL with the following parameter:

oauth_token:
OPTIONAL. The Request Token obtained in the previous step. The
Service Provider MAY declare this parameter as REQUIRED, or
accept requests to the User Authorization URL without it, in
which case it will prompt the User to enter it manually.
Additional parameters:
Any additional parameters, as defined by the Service Provider.

Once the request URL has been constructed the Consumer redirects
the User to the URL via the User’s web browser. If the Consumer is
incapable of automatic HTTP redirection, the Consumer SHALL notify
the User how to manually go to the constructed request URL.

Note: If a Service Provider knows a Consumer to be running on a
mobile device or set-top box, the Service Provider SHOULD ensure
that the User Authorization URL and Request Token are suitable
for manual entry.

 


6.2.2.
Service Provider Authenticates the User and Obtains Consent

The Service Provider verifies the User’s identity and asks for
consent as detailed. OAuth does not specify how the Service Provider
authenticates the User. However, it does define a set of REQUIRED
steps:

  • The Service Provider MUST first verify the User’s identity
    before asking for consent. It MAY prompt the User to sign
    in if the User has not already done so.
  • The Service Provider presents to the User information about the
    Consumer requesting access (as registered by the Consumer
    Developer). The information includes the duration of the
    access and the Protected Resources provided. The information
    MAY include other details specific to the Service Provider.
  • The User MUST grant or deny permission for the Service Provider
    to give the Consumer access to the Protected Resources on
    behalf of the User. If the User denies the Consumer access, the
    Service Provider MUST NOT allow access to the Protected
    Resources.

When displaying any identifying information about the Consumer to
the User based on the Consumer Key, the Service Provider MUST
inform the User if it is unable to assure the Consumer’s true
identity. The method in which the Service Provider informs the User
and the quality of the identity assurance is beyond the scope of
this specification.


6.2.3.
Service Provider Directs the User Back to the Consumer

After the User authenticates with the Service Provider and grants
permission for Consumer access, the Consumer MUST be notified that
the Request Token has been authorized and ready to be exchanged for
an Access Token. If the User denies access, the Consumer MAY be
notified that the Request Token has been revoked.

To make sure that the User granting access is the same User returning
back to the Consumer to complete the process, the Service Provider MUST
generate a verification code: an unguessable value passed to the Consumer via the
User and REQUIRED to complete the process.

If the Consumer provided a callback URL (using the oauth_callback
parameter in Section 6.1.1 (Consumer Obtains a Request Token) or by other means), the Service Provider uses
it to constructs an HTTP request, and directs the User’s web browser to that URL with the following
parameters added:

oauth_token:
The Request Token the User authorized or denied.
oauth_verifier:
The verification code.

The callback URL MAY include Consumer provided query parameters.
The Service Provider MUST retain them unmodified and append the
OAuth parameters to the existing query.

If the Consumer did not provide a callback URL, the Service Provider SHOULD display the value of the
verification code, and instruct the User to manually inform the Consumer that authorization is completed. If the Service Provider
knows a Consumer to be running on a mobile device or set-top box, the Service Provider
SHOULD ensure that the verifier value is suitable for manual entry.


6.3.
Obtaining an Access Token

The Consumer exchanges the Request Token for an Access Token capable
of accessing the Protected Resources. Obtaining an Access Token
includes the following steps:

 


6.3.1.
Consumer Requests an Access Token

The Request Token and Token Secret MUST be exchanged for an Access
Token and Token Secret.

To request an Access Token, the Consumer makes an HTTP request to
the Service Provider’s Access Token URL. The Service Provider
documentation specifies the HTTP method for this request, and HTTP POST
is RECOMMENDED. The request MUST be signed per
Signing Requests (Signing Requests),
and contains the following parameters:

oauth_consumer_key:
The Consumer Key.
oauth_token:
The Request Token obtained previously.
oauth_signature_method:
The signature method the Consumer used to sign the request.
oauth_signature:
The signature as defined in Signing Requests (Signing Requests).
oauth_timestamp:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_nonce:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_version:
OPTIONAL. If present, value MUST be
1.0
. Service Providers
MUST assume the protocol version to be 1.0 if this parameter
is not present. Service Providers’ response to non-1.0 value
is left undefined.
oauth_verifier:
The verification code received from the Service Provider in the
Service Provider Directs the User Back to the Consumer (Service Provider Directs the User Back to the Consumer) step.

No additional Service Provider specific parameters are allowed when
requesting an Access Token to ensure all Token related information
is present prior to seeking User approval.


6.3.2.
Service Provider Grants an Access Token

The Service Provider MUST ensure that:

  • The request signature has been successfully verified.
  • The Request Token has never been exchanged for an Access Token.
  • The Request Token matches the Consumer Key.
  • The verification code received from the Consumer has been successfully verified.

If successful, the Service Provider generates an Access Token and
Token Secret and returns them in the HTTP response body as defined
in Service Provider Response Parameters (Service Provider Response Parameters).
The Access Token and Token Secret are stored by the Consumer and
used when signing Protected Resources requests. The response
contains the following parameters:

oauth_token:
The Access Token.
oauth_token_secret:
The Token Secret.
Additional parameters:
Any additional parameters, as defined by the Service Provider.

If the request fails verification or is rejected for other reasons,
the Service Provider SHOULD respond with the appropriate response
code as defined in HTTP Response Codes (HTTP Response Codes).
The Service Provider MAY include some further details about why the
request was rejected in the HTTP response body as defined in
Service Provider Response Parameters (Service Provider Response Parameters).

 


7.
Accessing Protected Resources

After successfully receiving the Access Token and Token Secret, the
Consumer is able to access the Protected Resources on behalf of the
User. The request MUST be signed per
Signing Requests (Signing Requests), and
contains the following parameters:

oauth_consumer_key:
The Consumer Key.
oauth_token:
The Access Token.
oauth_signature_method:
The signature method the Consumer used to sign the request.
oauth_signature:
The signature as defined in
Signing Requests (Signing Requests).
oauth_timestamp:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_nonce:
As defined in Nonce and Timestamp (Nonce and Timestamp).
oauth_version:
OPTIONAL. If present, value MUST be 1.0. Service Providers
MUST assume the protocol version to be 1.0 if this parameter
is not present. Service Providers’ response to non-1.0 value
is left undefined.
Additional parameters:
Any additional parameters, as defined by the Service Provider.


8.
Nonce and Timestamp

Unless otherwise specified by the Service Provider, the timestamp is
expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
The timestamp value MUST be a positive integer and MUST be equal or
greater than the timestamp used in previous requests.

The Consumer SHALL then generate a Nonce value that is unique for all
requests with that timestamp. A nonce is a random string, uniquely
generated for each request. The nonce allows the Service Provider to
verify that a request has never been made before and helps prevent
replay attacks when requests are made over a non-secure channel
(such as HTTP).


9.
Signing Requests

All Token requests and Protected Resources requests MUST be
signed by the Consumer and verified by the Service Provider.
The purpose of signing requests is to prevent unauthorized parties
from using the Consumer Key and Tokens when making Token requests or
Protected Resources requests. The signature process encodes
the Consumer Secret and Token Secret into a verifiable value which is
included with the request.

OAuth does not mandate a particular signature method, as each
implementation can have its own unique requirements. The protocol
defines three signature methods: HMAC-SHA1,
RSA-SHA1, and
PLAINTEXT, but Service Providers
are free to implement and document their own methods.
Recommending any particular method is beyond the scope of this specification.

The Consumer declares a signature method in the oauth_signature_method
parameter, generates a signature, and stores it in the oauth_signature
parameter. The Service Provider verifies the signature as specified in
each method. When verifying a Consumer signature, the Service Provider
SHOULD check the request nonce to ensure it has not been used in a
previous Consumer request.

The signature process MUST NOT change the request parameter names or
values, with the exception of the oauth_signature parameter.

 


9.1.
Signature Base String

The Signature Base String is a consistent reproducible concatenation
of the request elements into a single string. The string is used as an
input in hashing or signing algorithms. The HMAC-SHA1 signature
method provides both a standard and an example of using the Signature
Base String with a signing algorithm to generate signatures. All
the request parameters MUST be encoded as described in
Parameter Encoding (Parameter Encoding) prior to
constructing the Signature Base String.


9.1.1.
Normalize Request Parameters

The request parameters are collected, sorted and concatenated into
a normalized string:

The oauth_signature parameter MUST be
excluded.

The parameters are normalized into a single string as follows:

  1. Parameters are sorted by name, using lexicographical byte value
    ordering. If two or more parameters share the same name, they
    are sorted by their value. For example:
                    a=1, c=hi%20there, f=25, f=50, f=a, z=p, z=t
  • Parameters are concatenated in their sorted order into a single
    string. For each parameter, the name is separated from the
    corresponding value by an ‘=’ character (ASCII code 61), even
    if the value is empty. Each name-value pair is separated by an
    ‘&’ character (ASCII code 38). For example:

 

                    a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t


9.1.2.
Construct Request URL

The Signature Base String includes the request absolute URL, tying
the signature to a specific endpoint. The URL used in the Signature
Base String MUST include the scheme, authority, and path, and MUST
exclude the query and fragment as defined by [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .)
section 3.

If the absolute request URL is not available to the Service Provider
(it is always available to the Consumer), it can be constructed by
combining the scheme being used, the HTTP Host
header, and the relative HTTP request URL. If the
Host header is not available, the Service
Provider SHOULD use the host name communicated to the Consumer in the
documentation or other means.

The Service Provider SHOULD document the form of URL used in the
Signature Base String to avoid ambiguity due to URL normalization.
Unless specified, URL scheme and authority MUST be lowercase and
include the port number; http default
port 80 and https default port 443 MUST
be excluded.

For example, the request:

                HTTP://Example.com:80/resource?id=123

Is included in the Signature Base String as:

                http://example.com/resource

 


9.1.3.
Concatenate Request Elements

The following items MUST be concatenated in order into a single
string. Each item is encoded (Parameter Encoding)
and separated by an ‘&’ character (ASCII code 38), even if empty.

  1. The HTTP request method used to send the request. Value MUST be
    uppercase, for example: HEAD,
    GET
    , POST, etc.
  2. The request URL from Section 9.1.2 (Construct Request URL).
  3. The normalized request parameters string from Section 9.1.1 (Normalize Request Parameters).

See Signature Base String example in Appendix A.5.1 (Generating Signature Base String).

 


9.2.
HMAC-SHA1

The HMAC-SHA1 signature method uses the HMAC-SHA1 signature
algorithm as defined in [RFC2104] (Krawczyk, H., Bellare, M., and R. Canetti, “HMAC: Keyed-Hashing for Message Authentication,” .) where the Signature
Base String is the text and the
key is the concatenated values
(each first encoded per Parameter Encoding (Parameter Encoding))
of the Consumer Secret and Token Secret, separated by an ‘&’
character (ASCII code 38) even if empty.

 


9.2.1.
Generating Signature

oauth_signature is set
to the calculated digest octet string, first base64-encoded per
[RFC2045] (Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies,” .) section 6.8, then URL-encoded per
Parameter Encoding (Parameter Encoding).

 


9.2.2.
Verifying Signature

The Service Provider verifies the request by generating a new request
signature octet string, and comparing it to the signature provided by the Consumer,
first URL-decoded per Parameter Encoding (Parameter Encoding),
then base64-decoded per [RFC2045] (Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies,” .) section 6.8.
The signature is generated using the request parameters as provided
by the Consumer, and the Consumer Secret and Token Secret as stored
by the Service Provider.

 


9.3.
RSA-SHA1

The RSA-SHA1 signature method uses the
RSASSA-PKCS1-v1_5 signature algorithm as defined in
[RFC3447] (Jonsson, J. and B. Kaliski, “Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography; Specifications Version 2.1,” .) section 8.2 (more simply known as PKCS#1),
using SHA-1 as the hash function for EMSA-PKCS1-v1_5. It is assumed
that the Consumer has provided its RSA public key in a verified way
to the Service Provider, in a manner which is beyond the scope of
this specification.

 


9.3.1.
Generating Signature

The Signature Base String is signed using the Consumer’s RSA private
key per [RFC3447] (Jonsson, J. and B. Kaliski, “Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography; Specifications Version 2.1,” .) section 8.2.1, where K is the
Consumer’s RSA private key, M the Signature Base String, and S is
the result signature octet string:

                S = RSASSA-PKCS1-V1_5-SIGN (K, M)

oauth_signature is set to S, first base64-encoded per
[RFC2045] (Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies,” .) section 6.8, then URL-encoded per
Parameter Encoding (Parameter Encoding).

 


9.3.2.
Verifying Signature

The Service Provider verifies the signature per [RFC3447] (Jonsson, J. and B. Kaliski, “Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography; Specifications Version 2.1,” .)
section 8.2.2, where
(n, e)
is the Consumer’s RSA public key, M
is the Signature Base String, and S is the octet string
representation of the oauth_signature value:

                RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S)

 


9.4.
PLAINTEXT

The
PLAINTEXT
method does not provide any security protection and
SHOULD only be used over a secure channel such as HTTPS. It does not
use the Signature Base String.

 


9.4.1.
Generating Signature

oauth_signature is set to the concatenated encoded values of the
Consumer Secret and Token Secret, separated by a ‘&’ character (ASCII
code 38), even if either secret is empty. The result MUST be encoded again.

These examples show the value of oauth_signature
for Consumer Secret djr9rjt0jd78jf88 and
3 different Token Secrets:

jjd999tj88uiths3:
oauth_signature=djr9rjt0jd78jf88%26jjd999tj88uiths3
jjd99$tj88uiths3:
oauth_signature=djr9rjt0jd78jf88%26jjd99%2524tj88uiths3
Empty:
oauth_signature=djr9rjt0jd78jf88%26

 


9.4.2.
Verifying Signature

The Service Provider verifies the request by breaking the signature
value into the Consumer Secret and Token Secret, and ensures they
match the secrets stored locally.


10.
HTTP Response Codes

This section applies only to the Request Token and Access Token
requests. In general, the Service Provider SHOULD use the
response codes defined in [RFC2616] (Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, “Hypertext Transfer Protocol — HTTP/1.1,” .) Section 10. When
the Service Provider rejects a Consumer request, it SHOULD respond with
HTTP 400 Bad Request or HTTP 401 Unauthorized.

  • HTTP 400 Bad Request
    • Unsupported parameter
    • Unsupported signature method
    • Missing required parameter
    • Duplicated OAuth Protocol Parameter
  • HTTP 401 Unauthorized
    • Invalid Consumer Key
    • Invalid / expired Token
    • Invalid signature
    • Invalid / used nonce

 


11.
Security Considerations

 


11.1.
Credentials and Token Exchange

The OAuth specification does not describe any mechanism for protecting
Tokens and secrets from eavesdroppers when they are transmitted from
the Service Provider to the Consumer in Section 6.1.2 (Service Provider Issues an Unauthorized Request Token)
and Section 6.3.2 (Service Provider Grants an Access Token). Service Providers should ensure
that these transmissions are protected using transport-layer mechanisms
such as TLS or SSL.

 


11.2.
PLAINTEXT Signature Method

When used with PLAINTEXT signatures, the
OAuth protocol makes no attempts to protect User credentials from
eavesdroppers or man-in-the-middle attacks.
The PLAINTEXT signature algorithm is only
intended to be used in conjunction with a transport-layer security
mechanism such as TLS or SSL which does provide such protection.
If transport-layer protection is unavailable, the
PLAINTEXT signature method should not be
used.

 


11.3.
Confidentiality of Requests

While OAuth provides a mechanism for verifying the integrity of
requests, it provides no guarantee of request confidentiality.
Unless further precautions are taken, eavesdroppers will have full
access to request content. Service Providers should carefully
consider the kinds of data likely to be sent as part of such requests,
and should employ transport-layer security mechanisms to protect
sensitive resources.

 


11.4.
Spoofing by Counterfeit Servers

OAuth makes no attempt to verify the authenticity of the Service
Provider. A hostile party could take advantage of this by intercepting
the Consumer’s requests and returning misleading or otherwise incorrect
responses. Service providers should consider such attacks when
developing services based on OAuth, and should require transport-layer
security for any requests where the authenticity of the Service
Provider or of request responses is an issue.

 


11.5.
Proxying and Caching of Authenticated Content

The HTTP Authorization scheme (OAuth HTTP Authorization Scheme) is
optional. However, [RFC2616] (Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, “Hypertext Transfer Protocol — HTTP/1.1,” .) relies on the
Authorization and
WWW-Authenticate headers to distinguish
authenticated content so that it can be protected. Proxies and
caches, in particular, may fail to adequately protect requests not
using these headers.

For example, private authenticated content may be stored in (and thus
retrievable from) publicly-accessible caches. Service Providers not
using the HTTP Authorization scheme (OAuth HTTP Authorization Scheme)
should take care to use other mechanisms, such as the
Cache-Control header, to ensure that
authenticated content is protected.

 


11.6.
Plaintext Storage of Credentials

The Consumer Secret and Token Secret function the same way passwords
do in traditional authentication systems. In order to compute the
signatures used in the non-PLAINTEXT
methods, the Service Provider must have access to these secrets in
plaintext form. This is in contrast, for example, to modern operating
systems, which store only a one-way hash of user credentials.

If an attacker were to gain access to these secrets – or worse, to
the Service Provider’s database of all such secrets – he or she would
be able to perform any action on behalf of any User. Accordingly, it
is critical that Service Providers protect these secrets from
unauthorized access.

 


11.7.
Secrecy of the Consumer Secret

In many applications, the Consumer application will be under the
control of potentially untrusted parties. For example, if the
Consumer is a freely available desktop application, an attacker may
be able to download a copy for analysis. In such cases, attackers
will be able to recover the Consumer Secret used to authenticate the
Consumer to the Service Provider.

Accordingly, Service Providers should not use the Consumer Secret
alone to verify the identity of the Consumer. Where possible, other
factors such as IP address should be used as well.

 


11.8.
Phishing Attacks

Wide deployment of OAuth and similar protocols may cause
Users to become inured to the practice of being redirected to
websites where they are asked to enter their passwords. If Users are
not careful to verify the authenticity of these websites before
entering their credentials, it will be possible for attackers to
exploit this practice to steal Users’ passwords.

Service Providers should attempt to educate Users about the risks
phishing attacks pose, and should provide mechanisms that make it
easy for Users to confirm the authenticity of their sites.

 


11.9.
Scoping of Access Requests

By itself, OAuth does not provide any method for scoping the access
rights granted to a Consumer. A Consumer either has access to
Protected Resources or it doesn’t. Many applications will, however,
require greater granularity of access rights. For example, Service
Providers may wish to make it possible to grant access to some
Protected Resources but not others, or to grant only limited access
(such as read-only access) to those Protected Resources.

When implementing OAuth, Service Providers should consider the types
of access Users may wish to grant Consumers, and should provide
mechanisms to do so. Service Providers should also take care to
ensure that Users understand the access they are granting, as well as
any risks that may be involved.

 


11.10.
Entropy of Secrets

Unless a transport-layer security protocol is used, eavesdroppers will
have full access to OAuth requests and signatures, and will thus be
able to mount offline brute-force attacks to recover the Consumer’s
credentials used. Service Providers should be careful to assign Token
Secrets and Consumer Secrets which are long enough – and random enough
– to resist such attacks for at least the length of time that the
secrets are valid.

For example, if Token Secrets are valid for two weeks, Service
Providers should ensure that it is not possible to mount a brute force
attack that recovers the Token Secret in less than two weeks. Of
course, Service Providers are urged to err on the side of caution,
and use the longest secrets reasonable.

It is equally important that the pseudo-random number generator (PRNG)
used to generate these secrets be of sufficiently high quality. Many
PRNG implementations generate number sequences that may appear to be
random, but which nevertheless exhibit patterns or other weaknesses
which make cryptanalysis or brute force attacks easier. Implementors
should be careful to use cryptographically secure PRNGs to avoid these
problems.

 


11.11.
Denial of Service / Resource Exhaustion Attacks

The OAuth protocol has a number of features which may make resource
exhaustion attacks against Service Providers possible. For example,
if a Service Provider includes a nontrivial amount of entropy in Token
Secrets as recommended above, then an attacker may be able to exhaust
the Service Provider’s entropy pool very quickly by repeatedly
obtaining Request Tokens from the Service Provider.

Similarly, OAuth requires Service Providers to track used nonces. If
an attacker is able to use many nonces quickly, the resources required
to track them may exhaust available capacity. And again, OAuth can
require Service Providers to perform potentially expensive computations
in order to verify the signature on incoming requests. An attacker may
exploit this to perform a denial of service attack by sending a large
number of invalid requests to the Service Provider.

Resource Exhaustion attacks are by no means specific to OAuth. However,
OAuth implementors should be careful to consider the additional
avenues of attack that OAuth exposes, and design their implementations
accordingly. For example, entropy starvation typically results in
either a complete denial of service while the system waits for new
entropy or else in weak (easily guessable) secrets. When implementing
OAuth, Service Providers should consider which of these presents a
more serious risk for their application and design accordingly.

 


11.12.
Cryptographic Attacks

SHA-1, the hash algorithm used in HMAC-SHA1
signatures, has been shown (De Canniere, C. and C. Rechberger, “Finding SHA-1 Characteristics: General Results and Applications,” .) [SHA1] to have a number
of cryptographic weaknesses that significantly reduce its resistance to
collision attacks. Practically speaking, these weaknesses are difficult
to exploit, and by themselves do not pose a significant risk to users
of OAuth. They may, however, make more efficient attacks possible, and
NIST has announced (National Institute of Standards and Technolog, NIST., “NIST Brief Comments on Recent Cryptanalytic Attacks on Secure Hashing Functions and the Continued Security Provided by SHA-1,” .) [NIST] that it will phase out
use of SHA-1 by 2010. Service Providers should take this into account
when considering whether SHA-1 provides an adequate level of security
for their applications.

 


11.13.
Signature Base String Compatibility

The Signature Base String has been designed to support the signature
methods defined in this specification. When designing additional
signature methods, the Signature Base String should be evaluated to
ensure compatibility with the algorithms used.

The Signature Base String cannot guarantee the order in which parameters
are sent. If parameter ordering is important and affects the result of a
request, the Signature Base String will not protect against request
manipulation.

 


11.14.
Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is a web-based attack whereby HTTP requests
are transmitted from a user that the website trusts or has authenticated.
CSRF attacks on OAuth approvals can allow an attacker to obtain authorization to
OAuth Protected Resources without the consent of the User. Service Providers
SHOULD strongly consider best practices in CSRF prevention at all OAuth endpoints.

CSRF attacks on OAuth callback URLs hosted by Consumers are also possible.
Consumers should prevent CSRF attacks on OAuth callback URLs by verifying that
the User at the Consumer site intended to complete the OAuth negotiation with the
Service Provider.

 


11.15.
User Interface Redress

Service Providers should protect the authorization process against UI Redress attacks
(also known as “clickjacking”). As of the time of this writing, no complete defenses
against UI redress are available. Service Providers can mitigate the risk of UI
redress attacks through the following techniques:

  • Javascript frame busting.
  • Javascript frame busting, and requiring that browsers have javascript enabled on the authorization page.
  • Browser-specific anti-framing techniques.
  • Requiring password reentry before issuing OAuth tokens.

 


11.16.
Automatic Processing of Repeat Authorizations

Service Providers may wish to automatically process authorization requests
(Section 6.2 (Obtaining User Authorization)) from Consumers which have been previously
authorized by the user. When the User is redirected to the Service Provider
to grant access, the Service Provider detects that the User has already granted
access to that particular Consumer. Instead of prompting the User for approval,
the Service Provider automatically redirects the User back to the Provider.

If the Consumer Secret is compromised, automatic processing creates additional
security risks. An attacker can use the stolen Consumer Key and Secret to redirect
the User to the Service Provider with an authorization request. The Service Provider
will then grant access to the User’s data without the User’s explicit approval, or
even awareness of an attack. If no automatic approval is implemented, an attacker
must use social engineering to convince the User to approve access.

Service Providers can mitigate the risks associated with automatic processing by
limiting the scope of Access Tokens obtained through automated approvals. Access
Tokens obtained through explicit User consent can remain unaffected. Consumers can
mitigate the risks associated with automatic processing by protecting their Consumer
Secret.

 


Appendix A.
Appendix A – Protocol Example

In this example, the Service Provider photos.example.net is a photo
sharing website, and the Consumer printer.example.com is a photo
printing website. Jane, the User, would like printer.example.com to
print the private photo
vacation.jpg
stored at photos.example.net.

When Jane signs-into photos.example.net using her username and
password, she can access the photo by going to the URL
http://photos.example.net/photo?file=vacation.jpg. Other Users
cannot access that photo, and Jane does not want to share her
username and password with printer.example.com.

The requests in this example use the URL query method when sending
parameters. This is done to simplify the example and should not be
taken as an endorsement of one method over the others.

 


Appendix A.1. Documentation and Registration

The Service Provider documentation explains how to register for a Consumer Key and Consumer Secret, and declares the following URLs:

Request Token URL:
https://photos.example.net/request_token, using HTTP POST
User Authorization URL:
http://photos.example.net/authorize, using HTTP GET
Access Token URL:
https://photos.example.net/access_token, using HTTP POST
Photo (Protected Resource) URL:
http://photos.example.net/photo with required parameterfile and optional parameter size
Request Token URL:
https://photos.example.net/request_token, using HTTP POST
User Authorization URL:
http://photos.example.net/authorize, using HTTP GET
Access Token URL:
https://photos.example.net/access_token, using HTTP POST
Photo (Protected Resource) URL:
http://photos.example.net/photo with required parameterfile and optional parameter size

The Service Provider declares support for the HMAC-SHA1 signature method for all requests, and PLAINTEXT only for secure (HTTPS) requests.

The Consumer printer.example.com already established a Consumer Key and Consumer Secret with photos.example.net and advertizes its printing services for photos stored on photos.example.net. The Consumer registration is:

Consumer Key:

dpf43f3p2l4k3l03
Consumer Secret:
kd94hf93k423kf44

 


Appendix A.2. Obtaining a Request Token

After Jane informs printer.example.com that she would like to print her vacation photo stored at photos.example.net, the printer website tries to access the photo and receives HTTP 401 Unauthorized indicating it is private. The Service Provider includes the following header with the response:

              WWW-Authenticate: OAuth realm="http://photos.example.net/"

The Consumer sends the following HTTP POST request to the Service
Provider:

              https://photos.example.net/request_token?oauth_consumer_key=dpf43f3p2l4k3l03&oauth_signature_method=PLAINTEXT&oauth_signature=kd94hf93k423kf44%26&oauth_timestamp=1191242090&oauth_nonce=hsu94j3884jdopsl&oauth_version=1.0&oauth_callback=http%3A%2F%2Fprinter.example.com%2Frequest_token_ready

The Service Provider checks the signature and replies with an
unauthorized Request Token in the body of the HTTP response:

              oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&oauth_callback_confirmed=true

 


Appendix A.3.
Requesting User Authorization

The Consumer redirects Jane’s browser to the Service Provider
User Authorization URL to obtain Jane’s approval for accessing
her private photos.

              http://photos.example.net/authorize?oauth_token=hh5s93j4hdidpola

The Service Provider asks Jane to sign-in using her username and
password and, if successful, asks her if she approves granting
printer.example.com access to her private photos. If Jane approves
the request, the Service Provider generates a verification code and
redirects her back to the Consumer’s callback URL:

              http://printer.example.com/request_token_ready?oauth_token=hh5s93j4hdidpola&oauth_verifier=hfdp7dh39dks9884

 


Appendix A.4.
Obtaining an Access Token

Now that the Consumer knows Jane approved the Request Token, it
asks the Service Provider to exchange it for an Access Token:

              https://photos.example.net/access_token?oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=hh5s93j4hdidpola&oauth_signature_method=PLAINTEXT&oauth_signature=kd94hf93k423kf44%26hdhd0244k9j7ao03&oauth_timestamp=1191242092&oauth_nonce=dji430splmx33448&oauth_version=1.0&oauth_verifier=hfdp7dh39dks9884

The Service Provider checks the signature and the verification code and replies with an
Access Token in the body of the HTTP response:

              oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00

 


Appendix A.5.
Accessing Protected Resources

The Consumer is now ready to request the private photo. Since the
photo URL is not secure (HTTP), it must use HMAC-SHA1.


Appendix A.5.1.
Generating Signature Base String

To generate the signature, it first needs to generate the Signature
Base String. The request contains the following parameters
(oauth_signature excluded) which are ordered and concatenated into
a normalized string:

oauth_consumer_key:
dpf43f3p2l4k3l03
oauth_token:
nnch734d00sl2jdk
oauth_signature_method:
HMAC-SHA1
oauth_timestamp:
1191242096
oauth_nonce:
kllo9940pd9333jh
oauth_version:
1.0
file:
vacation.jpg
size:
original

The following inputs are used to generate the Signature Base String:

  1. GET
  2. http://photos.example.net/photos
  3. file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original

The Signature Base String is:

                GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal

 


Appendix A.5.2.
Calculating Signature Value

HMAC-SHA1 produces the following digest value as a base64-encoded
string (using the Signature Base String as text and

kd94hf93k423kf44&pfkkdhi9sl3r4s00
as key):

                tR3+Ty81lMeYAr/Fid0kMTYa/WM=

 


Appendix A.5.3.
Requesting Protected Resource

All together, the Consumer request for the photo is:

                http://photos.example.net/photos?file=vacation.jpg&size=original

                Authorization: OAuth realm="http://photos.example.net/",
                oauth_consumer_key="dpf43f3p2l4k3l03",
                oauth_token="nnch734d00sl2jdk",
                oauth_signature_method="HMAC-SHA1",
                oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D",
                oauth_timestamp="1191242096",
                oauth_nonce="kllo9940pd9333jh",
                oauth_version="1.0"

And if using query parameters:

                http://photos.example.net/photos?file=vacation.jpg&size=original&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature_method=HMAC-SHA1&oauth_signature=tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_version=1.0

photos.example.net checks the signature and responds with the
requested photo.

 


12. References

[NIST] National Institute of Standards and Technolog, NIST., “NIST Brief Comments on Recent Cryptanalytic Attacks on Secure Hashing Functions and the Continued Security Provided by SHA-1.”
[RFC2045] Freed, N. and N. Borenstein, “Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies,” RFC 2045.
[RFC2104] Krawczyk, H., Bellare, M., and R. Canetti, “HMAC: Keyed-Hashing for Message Authentication,” RFC 2104.
[RFC2119] Bradner, B., “Key words for use in RFCs to Indicate Requirement Levels,” RFC 2119.
[RFC2606] Eastlake, D. and A. Panitz, “Reserved Top Level DNS Names,” RFC 2606.
[RFC2616] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, “Hypertext Transfer Protocol — HTTP/1.1,” RFC 2616.
[RFC2617] Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” RFC 2617.
[RFC3447] Jonsson, J. and B. Kaliski, “Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography; Specifications Version 2.1,” RFC 3447.
[RFC3629] Yergeau, F., “UTF-8, a transformation format of Unicode and ISO 10646,” RFC 3629.
[RFC3986] Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” RFC 3986.
[SHA1] De Canniere, C. and C. Rechberger, “Finding SHA-1 Characteristics: General Results and Applications.”

 


Author’s Address

OAuth Core Workgroup
Email: spec@oauth.net

Google Gadget – Bash.org Quotes

I wrote my first Google Gadget this weekend. The gadget displays random quotes from IRC conversations, some are really funny, although I guess you have to be a geek to really enjoy it 😉

Now if only Google would include it in their directory, that would be nice. You can add the gadget to your iGoogle homepage by clicking this link. Add to Google

update: At last, Google added the gadget to their directory… Here it is: