The Techies' pub

Angular 2 – Building the OAuth2 server using nodeJS

Hope you are all well. This is a response to many of our friends asking me to do a post on Oauth2 authorization method in our nodeJS backend. I am sorry since this took a really long time, but here we go.

First of all this post is heavily inspired by the blog post from Scott K Smith. His is the most read post on Oauth 2 and NodeJs which he wrote a couple of years back.

We have added two more strategies here. But as I said before let’s continue and finish the flow.

Open up routes.js and add new routes. Now routes.js should look like this.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

varexpress=require('express');

varactions=require('../methods/actions');

varauth=require('../methods/auth');

varclients=require('../methods/client');

varoauth2=require('../methods/oauth2');

varrouter=express.Router();

router.post('/authenticate',actions.authenticate);

router.post('/adduser',actions.addNew);

router.get('/getinfo',actions.getinfo);

router.post('/addbook',auth.isBearerAuthenticated,actions.addBook);

router.get('/getbooks',auth.isBearerAuthenticated,actions.getBooks);

router.route('/clients')

.post(auth.isAuthenticated,clients.postClients)

.get(auth.isAuthenticated,clients.getClients);

router.route('/oauth2/authorize')

.get(oauth2.authorization)

.post(oauth2.decision);

router.route('/oauth2/token')

.post(auth.isClientAuthenticated,oauth2.token);

module.exports=router;

Now for oauth2orize module we need sessions., so we will install express-session using the below command.

1

npm install express-session

Now open up server.js and add the below code so as to include sessions in our app.

1

2

3

4

5

6

7

8

app.use(session({

secret:'Super Secret Session Key',

saveUninitialized:true,

resave:true

}));

app.set('view engine','ejs');

app.use(routes);

app.use(passport.initialize());

Note that we have also set the view engine to ejs.

Okay. That’s it. Now, remember our steps. Let us say you have added a client and now you want to access the REST Apis. So you send a get request to /oauth/authorize along with the client_ID & redirect_uri (This will usually be added along while you register the client).

So that route invokes oauth2.authorization. Look up oauth2.authroization in your oauth2.js file. You could see that it simply references the Client in the client db using the client_id and then returns a client and tries to call the redirect URL.

Okay; usually apps would ask you permission before allowing the registered client to access Apis right?

For eg., this is what twitter would show when you make REST calls.

]

we need to create a similar interface for our apps too right ?

Once again we will be using code from Scottksmith’s blog.

We will be using ejs template engine for our view. Create a folder called views and create a new file inside it called dialog.ejs and then add the below code in it.

If you notice we simply generate a code and then saves it. It also returns the value of the code to the calling app.

Okay. So far so good. Let’s remember the next steps of our app. This code could be exchanged for an access token right.

This is where the ‘/oauth2/token’ endpoint comes in. Send a post request to this endpoint along with your Client ID and secret in the header(base64 encoded) and also send the code which you received from the previous step.

Our basic strategy in passport will check if the client is found using the client_Id. Then the oauth.token function will call the server.exchange function whose code looks like below.

If you notice you will see that it checks up the code which we saved previously and then generates a new token. This token is saved and then returned.

Note that the token is encoded first into a json web token using our secret.

This is essential since we will be making use of this token to do all our authorized requests. If you look at the JwtBearerStrategy in auth.js

1

2

3

4

5

6

7

8

9

10

11

12

13

passport.use(newJwtBearerStrategy(

config.secret,

function(token,done){

// console.log(token);

Token.findById(token._id,function(err,user){

if(err){returndone(err);}

if(!user){returndone(null,false);}

// console.log(user);

returndone(null,user,token);

});

}

));

You can see from the above code that we are first decoding the token using our secret again and then searching for this token using the id and then if it’s present then the token is considered to be valid and the user is authorized to use the resource.

Important things to notice:

We will never be using our username password anywhere after logging in.

Multiple request,responses take place and thats where the serialization and deserialization in oauth2.js file are used.

If you feel confused kindly watch my video screen-cast. I believe I have explained it a bit more clearly there. Or read this article once again. You could ask me anytime if you are stuck (use the comments section).

Alternatively you could grab a copy of this repo and try it out using Postman.

In the next part we will be building an Angular 2 app to consume these REST Apis. Since we will actually be using the code we wrote here, your doubts would get cleared and you would get a better understanding of the flow.

If you found this helpful kindly share it with someone else and help them too.