Reputation: 560
I'm developing a little webApp with AngularJS, express, nodejs and Passportjs. I have been creating endpoints on my API on demand but now I have a problem. I have an endpoint which cannot be called by the users when they want. This API call is made when a user make an specific action in the app, so they earn points. The endpoint is something like /api/users/updatePoints and I don't want the users with the developers tools resending the call and earning points they don't deserve. How could I accomplish this? I have been thinking for a day but I can't think of anything reasonable.
Thank you in advance :)
--EDIT-- At last I have just deleted that ENDPOINT and write directly in the database in server-side. Not the solution I wanted but good enough. Thank you!!
Upvotes: 2
Views: 2217
Reputation: 21
It's already too late to answer but I think this could help someone.
To Privatize an endpoint, Allow only your whitelisted Origins by setting the respective response headers and for all other users send a 403 status code (Which implies forbidden, 401 says try again).
Here is an example of middleware that privatizes endpoints.
module.exports = function (allowedOrigins) {
const whitelistedOrigins = Array.isArray(allowedOrigins) ? allowedOrigins : [allowedOrigins];
return function (req, res, next) {
const origin = req.headers.origin;
if (whitelistedOrigins.indexOf(origin) > -1) {
res.setHeader("Access-Control-Allow-Origin", origin);
next();
} else {
res.status(403).json({
msg: "This is a private Endpoint, Please contact the Admin",
});
}
};
};
Here is an example of usage.
const privatizeEndpoint = require("../customMiddlewares/privatizeEndpoint");
router.post("/someEndpoint", privatizeEndpoint(["http://myprivate.domain.com"]), (req, res) => {
console.log("Inside Private Endpoint");
});
However, your endpoint will be still exposed but at least it will be served only to your whitelisted domains.
Notice that even requests without origin will be blocked (curl commands or through POSTMAN).
Upvotes: 2