Wednesday, May 9, 2018

WebApp RESTful API

I have created an authorization server and resource server both in a single API. There is an endpoint that you can call in order to retrieve the resources for the demonstration purposes.
This is written using node.js. In order to run this on your computer you have to have node.js installed on your computer.

app.js

As you can see oauth grant type I have given is client_credentials. This has to be mentioned in the request body when you try to get the access token from authorization server.
Also this app tuns on port 4000. You can give any port number here.
There are two endpoints I have created in this. One to get the access token which is "/oauth/token" and the other one is to get resources which is "/profile".
As resources I have hard coded one value which is name ("Waas") and this comes as a JSON object.

model.js


Here I have created a sample user. (username = admin, password = admin) and all the functions that handle requests from client are written in this file.

Run the app.js file.


To make all get and post requests to the resource server we use RESTclient Mozilla Firefox Add on. You can use other similar products such as Postman for this.

First of all We have to make a POST request to get the access token from the authorization server.
For that we have to send the authorization key in the header.

Authorization : Bearer XXXXXXXXXXXXXXX
And also we have to mention the content type in the header.

I ll demonstrate with RestClient on Mozilla Firefox with creating all the requests manually and of course how to retrieve resources.


Then we have to mention these 3 parameters in the body.
username=test
password=test
grant_type=client_credentials

The URL should be the endpoint that gives us the access token.

http://localhost:4000/oauth/token 


When we send this we get the response which has access token in it. This access token also have an expiration time.

Then we have to make a GET request to retrieve the resources we need.



Now our URL is different because we have to call a different endpoint to get these resources which is "http://localhost:4000/profile".
We do not have to mention anything in the body.
In the request header we should send the access token we got in the previous step.

Authization: Bearer XXXXXXXXXXXXXXX

Make sure that the access token is not expired. Otherwise you will get an error message saying that it has expired.

When you sent this request you get a response that contains the resources we specified in the code.

Find the Source code from here.

No comments:

Post a Comment

Get Unlimited Free Trials Using a "Real" Fake Credit Card Number

When I see the words "free trial," I know I'm probably going to have to whip out my credit card and enter in the number to &qu...