OAuth2: Implicit Flow using oauth2orize, express 4 and mongoJS

In this blog post I will describe how to implement the implicit flow with Node.JS using oauth2orize. Again, if you don’t know about this flow at all check out this blog, which gives a nice introduction and an example using groovy.
Many things in the implicit flow are similar to the authorization grant flow. The main difference is that there isn’t a request code issued first, but the access token is directly delivered instead. This makes it a good fit for single page JavaScript applications, since there isn’t a redirect back to the server required in order to get the access token. However, since it is less secure there shouldn’t be a refresh token issued.
So, just as with the authorization grant flow we need to register a client and a user. You can take a look at my authorization grant flow post, which shows how I implemented that.
As it turns out the authorization process itself, is very similar to the authorization grant flow. Only the grant function is different and there is no need for the token functions, since we directly send the access token. Another small difference is that when redirecting to the authorization endpoint the response_type must be token and not code. The new grant function looks as follows:

server.grant(oauth2orize.grant.token(function (client, user, ares, done) {
    var token = utils.uid(256)
    var tokenHash = crypto.createHash('sha1').update(token).digest('hex')
    var expirationDate = new Date(new Date().getTime() + (3600 * 1000))

    db.collection('accessTokens').save({token: tokenHash, expirationDate: expirationDate, userId: user.username, clientId: client.clienId}, function(err) {
        if (err) return done(err)
        return done(null, token, {expires_in: expirationDate.toISOString()})

The grant function creates, stores and sends back an access token. The access token is then found in the fragment part of the URL along with the expiration date (which is why it is necessary to transform it into a string).
The full example of the implicit flow can be found at: https://github.com/reneweb/oauth2orize_implicit_example


One thought on “OAuth2: Implicit Flow using oauth2orize, express 4 and mongoJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s