How should I handle authentication in my REST API?

2019-07-29 11:19发布

问题:

I am new to this but I will try my best to explain what I am trying to do.

I have a catalog of products and various private information that my users want to be able to access via their website.

For example:

User-a has an e-commerce site and they want to sell my merchandise. They will be able to access a certain products details via a web service. They will also be able to see the negotiated rate that I've given them along with some other private details.

How should the API handle authenticating the request that comes from User-a's website?

I've been reading all day about different authentication methods but they all seem to revolve around the idea of a third party accessing specific user information. An example is if you let http://randomtwitterapp.com access your twitter profile. In that case, the third party site must manage multiple different users and auth tokens. In our case, my users website is interacting on behalf of the user. I hope this makes sense.

回答1:

Let's call user A "Alice" because calling her User-A is cumbersome.

Treat Alice's web site as if it were Alice herself. The special pricing and such IS specific to the web site in question, so have it log into your site. Issue credentials that the person developing that site would use to authenticate with, and then use those credentials to determine the pricing and products you show.

As for actual authentication mechanisms, it really depends on your needs. If all you need to do is serve different data to different people, you could do something as simple as an API token passed in the query string: http://api.example.com/products?key=9af4d8381781baccb0f915e554f8798d

Or if Alice already has a username and password for your site, you could have her use those in her API requests with Basic Auth.

If Alice is going to need to enter her account information on various sites that she doesn't control, then oAuth comes in very handy. With that, you can essentially give her an API key for every site she needs to access your API from. And you give her the ability to delete those API keys and deny those sites access.