Dec 18, 2015

OAuth 2.0

OAuth 2.0 let client application access user's protected resources without resource owner sharing their credentials with the client application. Instead of using resource owner's credential, client application obtains access token which has specific scope and lifetime and use that to access protected resource.

O-Auth is about delegated authorization, meaning you want to authorize a client (which is a piece of software) to access your resources on your behalf. Its the combination of resource owner and client that make up the resultant access token.

OAuth takes multiple client architecture into account and also each client can have varying level of trust.

The “authorization” of the client by the Resource Owner is really consent. This consent may be enough for the user, but not enough for the API. The API is the one that’s actually authorizing the request. It probably takes into account the rights granted to the client by the Resource Owner, but that consent, in and of its self, is not authorization. So oAuth is for delegated access not for authorization, not for authentication and also not for federation. Refer this for more on authentication.

In movie "Ferris Bueller's Day Off" Ferris and his friend take day off and steal his dad's Ferrari and went to the mall and handed over car key to the guy for valet parking. Rather than parking the car this guy made a little road trip, which obviously was not the intention. This he could do because he had the master key, had that been valet parking key (may be that option was not there back than), he could not have taken Ferrari for the ride. So now take this analogy for oAuth, Ferris is the resource owner, Ferrari is the resource, valet parking guy is client and valet parking key is the token.

In a typical entreprize application you have a trusted client, which mean client, resource server and authorization server are build by the same company/party, so it may be ok (though here also you have to be careful) to have trust level between client and the resource server. But the moment you move your client outside the trust zone, you start thinking to do you manage access control between resource server and client.



OAuth Flows

  • Authorization Code Flow
    • Designed for server rendered application, client store secret securely on server. 
    • Resource owner get authorization
    • Client (server side) get access token. This is never visible to the browser.
    • Client access resource
  • Implicit Flow
    • Resource owner get authorization and access token
    • Client Access resource
  • Resource owner password credential flow
    • Trusted client, resource owner credential is exposed to the client
    • client gets token using resource owner credential
    • Access resource
  • Client credential flow
    • client get access token using client credential. no resource owner
    • access resource
Authorization Code
The authorization code used in auth code flow, provides an important security benefits. This is issued after resource owner is authenticated and access token is directly transmitted to the client without passing it to the resource owner's user-agent. This must expire shortly after it is issued (usually 10 min), and it should not be used more than once.

Access Token
Client access protected resource by sending access token to the resource server. Resource server validates access token and its scope covers protected resource. It depend on resource server how it validates the access token. Usually its done in following two ways
  • By value: In this case access token can be JWT, which may have user information, issuer information. This way access token is self-contained, so resource server can verify the access token and use the associated content without having to go back to the Authorization Server. That is a great property but makes revocation harder. 
  • By reference: In this case access token doesn't contain user info, so in this case resource server will talk to the authorization server in order to get user information against access token.
Refresh Token
A token that may be used to obtain a new access token. Refresh tokens are valid until user revokes access. The idea of refresh tokens is that if an access token is compromised, because it is short-lived, the attacker has a limited window to abuse it. Refresh tokens, if compromised, are useless because the attacker requires the client id and secret in addition to the refresh token in order to gain an access token.

Profiles of Token
  • Bearer Token
  • HoK Token
Concerns 
Eran Hammer lead editor left the committee. He raised lot of concerns some of which are
  • The framework (its no longer specification) has lot of variations, If you go through the specification it has lot of "may be implemented" phrase. So basically you use this framework to come up with your own protocol which satisfies your requirement.
  • If bearer token is stolen anyone can use that to gain access to the resource. There may be scenarios where ssl is not established end to end.
  • Security Theater, Client application can spoof authorization server login screen.
  • Attack surface, User may manipulate redirect url, scope and response type as those comes in query string. So authorization server may need to do proper validation around those input value. There were few hack around this with facebook.
https://www.tbray.org/ongoing/When/201x/2013/01/23/OAuth

Dec 13, 2015

OAuth 2.0 Authorization Code Grant

OAuth let client application access user's protected resources without resource owner sharing their credentials with the client application. Instead of using resource owner's credential, client application obtains access token which has specific scope and lifetime and use that to access protected resource. Following steps are involved in auth code grant type.

Step1

The client initiates the flow by directing the resource owner's user-agent to the authorization endpoint.  The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI
  • client_id  (required)- authorization server issue the registered client
  • response_type (required) - for this case it will be code
  • redirect_uri (optional) - to which the authorization server will send the user-agent back once access is granted or denied, this should be same as what is registered by the client
  • scope (optional)- scope of access request
  • state (optional)- An opaque value used by the client to maintain state between the request callback.
Following is an example of such uri 

https://accounts.google.com/o/oauth2/auth?
scope=https://www.googleapis.com/auth/userinfo.profile&
response_type=code&
redirect_uri=http://localhost:3000/auth/google/callback&
client_id=clientid from google developer
You can use passport-google-oauth npm package and use following code in order to achieve this.

 
 passport.use(new googleStrategy({
            clientID: "1071015616274-as07l0j0iuhpnll3o5auakjbssc3brl7.apps.googleusercontent.com",
            clientSecret: 'O7HoSqMNZD7gkitrSzAUWLpv',
            callbackURL: "http://localhost:3000/auth/google/callback"
        }, function (req, accessToken, refreshToken, profile, done) {
            done(null, profile);
        }));

 app.get('/auth/google',
            passport.authenticate('google', {
                scope: ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
            }));

if you are using passport-google-oauth, refer following where this redirect happens
node_modules\passport-google-oauth\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js

Step 2

Authorization server authenticate resource owner and resource owner authorizes client application to access its resource. User never share its credential with the client application.

Step 3

If the resource owner grant access, the authorization service redirects the user back to your site with an auth code

http://localhost:3000/auth/google/callback?code=xxxxx

Step 4

Client application make a request to authorization server's token endpoint by sending auth code (received in the previous step)

Request looks something like this
POST https://accounts.google.com/o/oauth2/token
grant_type=authorization_code&
redirect_uri=http://localhost:3000/auth/google/callback& (same as what was sent in authorization request)
client_id=xxx& (secret issued to client during registration process)
client_secret=xxx& (secret issued to client during registration process, this is never visible to user agent)
code=xxx (code which was received in earlier step)
Response may look like

{
"access_token" : "xxx",
"token_type" : "Bearer",
"expires_in" : 3431,
"id_token" : "xxxx"
}

If you are using passport-google-oauth npm package, this call happens in the module OAuth2 (node_modules\passport-google-oauth\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js). It then pass

Client application use access token from here on to access user's protected resource


Dec 4, 2015

NodeJS quick guide for beginner

NodeJS is a platform which encourages good software practices out of the box like async and IOC. NodeJS is async by nature. This can be achieved in Asp.Net MVC but that's not default behavior. NodeJS (and express) support middleware similar to pipeline/filters in asp. For someone coming from .Net background here is a quick way to correlate node with .Net.

IIS - Node.exe
C# - JavaScript
ASP.NET MVC Razor-Express Vash
ASP.NET Web API - Express
SignalR - WebSockets

There are number of IDE available for node development, one of which is open source plugin for visual studio. This may be more comfortable for someone coming from .Net background. Refer following for more details on this
       https://github.com/Microsoft/nodejstools

NodeJS is executed under google v8 engine. V8 compiles JavaScript source code directly into machine code when it is first executed.

Module
A module encapsulates related code into a single unit of code. In Node.js, files and modules are in one-to-one correspondence. As an example, following code loads the module controller.js
 
 var controller = require("./controller");

In the above code require("./controller") returns an object which represent (modular) code encapsulated in controller.js (or controller\index.js). Each file (module) has access to module.exports object. You can assign properties to this object which require will return. So the content of controller.js could be
 
 module.exports.myFirstName = "rahul";
 module.exports.myLastName = "raj";
 module.exports.myName = {lastName : "rahul"}

You can access this like.
 
 var controller = require("./controller");
 console.log(controller.myFirstName);

In this case code in controller.js is executed only once when you do require("./controller.js"). The other way is to assign export object as a function
 
 module.exports = function () {
  return "my first name is rahul";
 };

This can be referenced and executed as following. In this example every time you execute controller(), that function will be called.
 
 var controller = require("./controller");
 console.log(controller());

You can also assign constructor method to the export object
 
 module.exports = function () {
  this.myFirstName = "rahul";
  this.myLastName = "raj";
 };

In this case you can use it like this in app.js
 
 var controller = require("./controller");
 var control = new controller();
 console.log(control.myFirstName);

One of my favourite way is to use self executing anonymous function
 
 (function (controller){
  controller.init = function () {
   return "my first name is rahul";
  };
 })(module.exports);

This way we are passing in module.exports as controller. So now inside the anonymous function you can use controller to add any property bag. You may also want to have index.js in every folder and have all your module referenced in index.js, so anyone outside that folder (set of module) just reference index.js.

Express
Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
 
 var express = require("express");
 var app = express();

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
 
 app.get("/create", function (req, res, next)

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)): For static file to be accessible from browser you need to set static resource folder. This is build-in middleware
 
 app.use(express.static(__dirname + "/public"));  //__dirname is the rooth directory name of the application

The other common middlewares are following. These are third-party middleware
 
 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json()); // parse application/json
 app.use(expressValidator());
 app.use(session({...}));
 app.use(flash());

Refer following for more details on using express middleware
http://expressjs.com/en/guide/using-middleware.html

For using template engines with Express you need to set following
 
 app.set("view engine", "vash");

Grunt
Its a javascript task runner. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes.

npm install grunt-cli -g

It looks for gruntfile.js file in the root folder where nodejs is running. this will not be used during run time, its purely development asset. Few of the grunt plugin which i recently used are
grunt-nodemon
grunt-mocha-test
grunt-contrib-watch
grunt-jsbeautifier

Bower 
Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

Npm
It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

Mocha, Chai, Sinon
Mocha sets up and describes test suites and Chai provides convenient helpers to perform all kinds of assertions against your JavaScript code. Sinon is a great JavaScript library for stubbing and mocking such external dependencies and to keep control on side effects against them. run test in all the files which are in test folder by adding chai.should(), all javascript object get property should