Secure node.js restful API

2019-05-26 07:02发布

问题:

I'd like to secure a restful Api, and I'm trying to keep it as simple as possible, as well as being stateless.

What is the optimal way to store, generate, and authenticate api keys? I was thinking about generating keys with node-uuid, storing them in redis, and then authenticating them with passport-apikeys.

Would this work? Or is there another optimal solution that I'm missing.

I have been reading up on this a good amount, but a lot of resources are missing the actually implementation, like this post

回答1:

Your solution sounds OK to me, but not that secure enough I'm afraid. I'd like to suggest you sign the request with the key, so that you can protect your API from tampering. So you need to generate a key pair, let's say access id and access key, to the user who is going to use your API. The HTTP request will have two sections, one is the access id, the other is a signature that calculate the whole request content by the access key. But access key should never by passed through HTTP. So in server side you can check the signature of the HTTP request by the access key stored in Redis.

You can use Node.js Crypto module for this. http://nodejs.org/api/crypto.html#crypto_class_hmac

Hope this helps a bit.