简体   繁体   中英

How to secure my REST-API?

I have an api build with node.js & express.js . For now I have a unsecured api where anyone can GET,POST,PUT,DELETE records.

I am facing following problem. My rest api should not authenticate users but applications. Eg my mobile application should have a valid token to access the api. Same for web application.

Another user case: my api will be used by another application that only uses one single rest call. So somewhere in the code I don't know in an application I don't know (for most part) a rest call on my api will be triggered. How can I secure such access, since no cookies or sessions are involved?

My first thought was, create a user and a password. Each api call (via https) must contain the credentials. Password may be hashed. However I read this

Usernames and passwords, session tokens and API keys should not appear in the URL, as this can be captured in web server logs and makes them intrinsically valuable.

from https://www.owasp.org/index.php/REST_Security_Cheat_Sheet

Any suggestions on this? I read about oauth but this involves redirections and I cannot imagine how this would work with a mobile app eg on android.

You can use RSA encryption for this, have a look at ursa module for node.
A simplified process of using this is... Arrange you client applications to encrypt a secret password with a public key and on the server side decrypt it with a private one, check if the secret is what you expect and act accordingly...

There are plenty of articles about using rsa in applications, I am sure you will be able to pick up a more definite explanation of how to work it if you just google.

EDIT
I have just bumped into this post which has a more detailed write-up on this question.

There is a question of how applications get to know a username/password in the first place, but if you are OK with the general idea (which is safe, as long as you consider the environment in which the application runs to be safe), then you don't need to worry about username/passwords in URLs: simply use https instead of https.

https is encrypted so that only the 2 endpoints (the client and your API) can read even the URL. Any router/proxy/server in between sees only encrypted data and has no means of accessing your username/passwords.

Instead of a username/password, btw, just use an "Access Token", which is a long (read: hard to guess) string, and assign one access token per application. In your end, you keep the list of valid tokens in a DB, and authenticate against that. You can even attach expiry dates to those strings, if you wish so.

Adding access token as part of an https:// url is common practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM