Wednesday, May 23, 2018

RESTful API

Resource Server API

You can use either existing authorization server or your own server.Here, I created an authorization server and resource server both in a single server.This is written using node,js. In order to run this on your computer, you should have node.js installed on your computer.

app.js 


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". 

model.js








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

Run




Run this resource server using node,js

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.
Content-Type :  application/x-www-form-urlencoded


Then we have to mention these 3 parameters in the body.
username=thusiya
password=thusiya
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".

Authization: Bearer XXXXXXXXXXXXXXX

When you sent this request you get a response that contains the resources we specified in the code.
{"name":"thusiya","id":"set"} 


You can download source code from my GitHub.

https://github.com/thusith94/RESTful_API









No comments:

Post a Comment