What's behind a REST API - api

I'm working on the frontend part of some REST API (link, json validation and in generale controlling)
I'm trying to figure out how it works in the backhand, there should be a database I guess and each API call correspond to a specific query?
could you suggest me guide on how such implementation are usually build?
I'm only finding formal guide on how to shape url for rest API
thanks
It is a quite generale / cultural question, not technical

There's no standard way, the point of a protocol like HTTP (what REST is based on) is to decouple this kind of details and leave the server implementor to be free of doing it however it wants.
There are a lot of different ways and listing them all is very hard.
For a simple service what you said is true, for more complex scenario behind a REST endpoint there could be a service doing calls to other services and aggregating their responses into the json you see.

You would usually have a single endpoint do a single task but you could also do anything you want with the data provided from the user. You could carry out regex validations, store it inside a database, send it to another API, extract data out of it, and plenty of other things.
Here is an example I wrote in Node.js:
const signup_post = async (req, res) => {
const { email, password, username } = req.body;
try {
const user = await User.create({ email, password, username });
const token = createToken(user._id);
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
res.status(201).json({ user: user._id });
}
catch(err) {
const errors = handleErrors(err);
res.status(400).json({ errors });
}
}
This example code, we are taking the user-provided data, making a new entry in the database with a pre-defined schema, creating a JWT token and attaching it to a cookie, and sending the cookie back to the client. This is one way to handle authentication- and as long as the client has this cookie, they will stay logged in.
We are also handling any errors and validating the user-provided data to make sure it fits our database schema.

Related

How to secure an endpoint

I have an endpoint written in expressjs
router.post("/mkBet", async (req, res) => {
console.log(req.body)
const betToPush = new Bet({
addr: req.body.address,
betAmount: req.body.amount,
outcome: req.body.didWin,
timePlaced: Math.round(+new Date()/1000)
})
try {
const newBet = await betToPush.save()
res.status(201).json(newBet)
} catch(err) {
res.status(400).json({message: err.message})
}})
And I am trying to make it so that it can only be called when an action is performed on the frontend. So users cannot call it with custom arguments to make it so the outcome is always true. What would be the best way to achieve this?
It is not possible to securely tell what client sent the request. In other words, a request from your client and a different one can be identical in general.
Talking about unmodified browsers (as opposed to non-browser tools like Postman), you can tell the origin of the request (~the url loaded in the browser when the request was sent) with some confidence from the Origin and Referer request headers. However, your backend needs authentication and authorization anyway.
With the latter two in place, ie. with proper security implemented on the server-side, it doesn't matter anymore what client sends the requests.

How to handle backend auth with express as reverse proxy api

I am using express the first time in a project as a kind of reverse proxy in between my frontend and backend. The backend authentication is cookie based.
First I was using http-proxy-middleware to make my requests. This works fine and the cookie gets passed no problem.
The problem is that I want to decouple the front and backend as the api isn't very usable right now (for example 3 requests necessary to get data for one view). So instead of making requests directly I want to have my express server handle the heavy lifting in the background.
Currently I am using axios for the requests and pass the cookie through with the request and the new one back with the response. This works fine but feels very hacky and error prone. For example I have to split the returned setcookie string in a very weird way.
app.get('/api/myrequest', (req, res) => {
axios.get('backendserver/url', {
headers: {
Cookie: req.cookies['auth'],
},
responseType: 'json',
})
.then((response) => {
let tempCookie = response.headers['set-cookie'][0];
tempCookie = tempCookie.split(';')[0];
tempCookie = tempCookie.split('=');
res.cookie(tempCookie[0], tempCookie[1]);
res.send(response.data);
})
});
I suppose there is a much better way to handle this. I was looking at things like passportjs but am not sure if it fits this special use case as the auth isn't handled by express itself.
Maybe someone can point me in the right direction?

Auth0: Validating id_token/JWT on UI (javascript) level

Update March 2019
I just went over this question again; the Auth0's github code has been updated in December 2018. They are now storing 'access_token','id_token' and 'expire_at' into the object/session, instead of localstorage and using now an 'isLoggedIn' flag to mark if authenticated or not. Check the pull request and these 2 lines in the specific commit: line1 and line2.
If you do not need to re-validate 'id_token' - like I was doing in the original question - that might be an alternative. Otherwise check original question.
Original Question
We are using auth0 for one of our clients. One stack that we are using it for is:
React/Redux UI
NodeJS backend
So we are using a cross origin authentication using implicit grant for that, using JWT with an RS256 algorithm. We also refresh tokens in background using silent authentication.
I was able to validate 'access_token' on the API (nodejs) side using node-jwks-rsa for express
On the UI level, after going through the source code of the auth0-js library I noticed that the "parseHash" method used in their provided react samples, actually validates tokens before we store them in localstorage, ie on successful authentication. Mainly this line in the source code.
Then I used their sample code that allows us to check if a user is authenticated, method isAuthenticated().
Problem with the isAuthenticated() method
From a security perspective, if later on (post authentication) a user of the application decided to manually modify the 'expire_at' label in the storage, they could get away as indeed authenticated. While of course there is additional security checking in our app, I wanted to update this function to validate 'id_token'. So far, I couldn't find any example in auth0's online docs for how to do that.
After digging in their source code I found a method validateToken that is being used. So I decided to leverage it in one of our functions:
import IdTokenVerifier from 'idtoken-verifier'
.... Some code in here ....
reValidateToken() {
return new Promise((resolve, reject) => {
// Both of these are stored in localstorage on successful authentication, using the parseHash method
let id_token = localStorage.getItem('id_token');
let transactionNonce = localStorage.getItem('app_nonce');
this.webAuth.validateToken(id_token, transactionNonce, function(
validationError,
payload
) {
if (!validationError) {
resolve('no validation errors for id_token');
}
if (validationError.error !== 'invalid_token') {
reject(validationError.error);
}
// if it's an invalid_token error, decode the token
var decodedToken = new IdTokenVerifier().decode(id_token);
// if the alg is not HS256, return the raw error
if (decodedToken.header.alg !== 'HS256') {
reject(validationError);
}
});
});
}`
Now, for it to succeed; we store the nonce in localstorage after successful authentication, does this approach create back doors for potential security holes? if it does; what is best practice to validate RS256 JWT id_token(s) on a UI level?

socket.io unity authentication

I have this use case:
- I'm working on a game with a webapp for user management and chat, which is on MERN, and a unity game, with socket.io as the real time messaging layer for the multiplayer game.
- User may register to webapp by either providing a pair of email/password, or getting authenticated on FB/Gamil/etc. as usual, in which case the user's email is obtained and saved to MongoDB and this is done by passport.
- There is no session in express side, and socket.io is on a redis. There is no cookie but JWT is used.
My problem is that I don't know what's the best practices in this. I read this
article
and this
one
which both have content and code close to what I want to do, but in the first one:
app.use(express.cookieParser());
while I don't want to use cookie at all, and the other one also has in code:
cookie: {
secure: process.env.ENVIRONMENT !== 'development' && process.env.ENVIRONMENT !== 'test',maxAge: 2419200000}...
Also, I found this on
github
which suggests for the client side (unity):
var socket = io.connect('http://localhost:9000');
socket.on('connect', function (socket) {
socket.on('authenticated', function () {
//do other things
})
.emit('authenticate', {token: jwt}); //send the jwt
});
meaning that:
1. socket is created
2. authentication is requested
but I think that the approach I found in the other article is better, where the socket is not created at all if the JWT for auth is not provided at the first ever connection request sent to "io", so if I'd do it I'd issue:
var socket = io.connect('http://localhost:9000', {query: {"JWT":"myjwt"}});
and in my server side where I have:
io.on("connection", function(socket){...});
I'd like to first get the JWT:
var jwt = socket.handshake.query["JWT"];
and then if auth will be unsuccessful, simply return socket.disconnect('reason') and do not open any connection at all (here maybe I just didn't understand, say, that the approach the Author took in the github source is using a middle ware technique and it is maybe also done before anything else).
I still could not find out what is the best practice that Gurus use, please help me get clear.

CakePHP Authentication on REST API

So I'm creating a REST API for a web app I'm developing, and I know the basic ways for authentication are either sending the credentials on each request or sending a token.
Since I have never used token before, I think I may send the credentials for each request. The point is I can't find any examples on how to handle this in the controller. Would it be something like this?
public function api_index() {
if(!$this->Auth->login()) return;
$this->set(array(
'models' => $this->Model->find('all'),
'_serialize' => array('models')
));
}
I don't really think this is the way AuthComponent::login() works, can I get some directions here please?
Alright, first a clarification about how AuthComponent::login works. In Cake 2.x that method does not do any authentication, but rather creates the Auth.User array in your session. You need to implement the actual authentication yourself (the User model is a natural place to do this). A basic authentication method might look like this:
App::uses('AuthComponent', 'Controller/Component');
public function authenticate($data) {
$user = $this->find('first', array(
'conditions' => array('User.login' => $data['login']),
));
if($user['User']['password'] !== AuthComponent::password($data['password']) {
return false;
}
unset($user['User']['password']); // don't forget this part
return $user;
// the reason I return the user is so I can pass it to Authcomponent::login if desired
}
Now you can use this from any controller as long as the User model is loaded. You may be aware that you can load it by calling Controller::loadModel('User').
If you want to authenticate every request, then you should then put in the beforeFilter method of AppController:
public function beforeFilter() {
$this->loadModel('User');
if(!$this->User->authenticate($this->request->data)) {
throw new UnauthorizedException(__('You don\'t belong here.'));
}
}
All of the above assumes that you pass POST values for login and password every time. I think token authentication is definitely the better way to go, but for getting up and running this should work. Some downsides include sending password in cleartext (unless you require ssl) every request and the probably high cpu usage of the hashing algorithm each time. Nevertheless, I hope this gives you a better idea of how to do authentication with cakephp.
Let me know if something needs clarifying.
Update:
Since posting this, I found out that you can actually use AuthComponent::login with no parameters, but I am not a fan of doing so. From the CakePHP documentation:
In 2.x $this->Auth->login($this->request->data) will log the user in with
whatever data is posted, whereas in 1.3 $this->Auth->login($this->data)
would try to identify the user first and only log in when successful.
AuthComponent::login() creates a session variable that stores the user data, so say you had data that was something like.
$data = array('User' => array('id' => 1, 'username' => 'johndoe'));
Then you would use
$this->Auth->login($data);
And access the data with
$this->Auth->user('User');
To get the user id
$this->Auth->user('User.id');
In your AppControllers beforefilter put $this->Auth->deny(); that will deny all actions to someone who is not logged in. Then in each controllers before filter you want to $this->Auth->allow(array('view')); 'view' being the name of an action you want to be public.
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Cakephp 2.X, After lots of research about this on internet I did not find any satisfactory answer So I found a way myself to do this. May be this answer will help some folks in future. This answer is only applicable for REST API's in cake php.
Add following line in your logic action of REST API before checking for the $this->Auth->login().
$this->request->data['User'] = $this->request->data ;
if($this->Auth->login()){
echo "Hurray You are logged In from REST API.";
}
else
{
throw new UnauthorizedException(__('You don\'t belong here.'));
}
Desciption : As #threeve said in one of the answers that $this->Auth->login() does not do any authentication itself. but rather creates the Auth.User array in your session. For Authentication we require our $this->request->data to be inside User array since User is the model which will check the Credentials in Database. Therefore we have to pass the data to Auth as it is required when not using REST API's. Rest of the things will be handled by Cake and Auth itself.
Any enhancements or suggestions on this answer are most welcome.