Tuesday 11 April 2017

How to not let anyone POST/PUT/DELETE on my API ?

Currently I have a API that when I go to the URL of "localhost:3000/api/todos" I can get a list of all the todos from my MySQL Database. If I go to /api/todos/1 I will get a single todo...if I POST to /api/todos I can create a new todo and PUT to /api/todos/1 I can update the todo with id of 1 and yeah so on, very simple.Now, say I want to build on this... I want to create a site where.You make an account and can login.View your todos, edit todos and so on.For the front end/client side. I want to use ReactJS to retrieve the todos of the logged in user via the API URLs I created. ReactJS will also POST and PUT to my api url /api/todos and so on.However, anyone can go into, say, PostMan or any REST client and POST, PUT into the API URLS that I have setup.How do I fix this ? A middleware that checks if the user has a session ? What if I want to make this API available for anyone ? How will I make sure the user is logged in ? Is this where headers come in ? What if I only want ReactJS to post/put to my own api, how do I prevent people from using my api urls that I setup.How do I add that to my express app ? Middlewares ? I want to make this secure as possible. Here is a rough example of what my current POST 'api/todos/' looks likeapp.post('/api/todos/, (req, res) => { Todos.create({ title: req.body.title, desc: req.body.desc }).then( (todo) =>{ res.status(201).json(todo) }). catch(// blah blah); }) TL;DR: With the code above, anyone with a REST client can create a new todo...I do not want that. I only want MY CLIENT/ReactJS to be allowed to POST , DELETE, PUT. If I want to make this API available, how do I check so that not anyone can PUT and POST and DELETE a todo with a API client.

Submitted April 11, 2017 at 04:48PM by HappyZombies

No comments:

Post a Comment