We going to develop a little API application in Sinatra. What are the authentication options available to secure the API calls?
相关问题
- java client program to send digest authentication
- Google places autocomplete suggestion without coun
- Karate API Testing - Access variable value across
- PHP persistent login - Do i reissue a cookie after
- How to verify laravel passport api token in node /
相关文章
- 我用scrapy写了一个蛮简单的爬虫怎么封装成一个api啊
- 后端给前端的API接口是怎么用代码写的
- Convert C# Object to Json Object
- Android camera2 API get focus distance in AF mode
- Getting all listing images from an Etsy shop
- How do I access Sinatra params using a symbol?
- Is there an API to get statictics on Google Play d
- User.Identity.IsAuthenticated vs WebSecurity.IsAut
Sinatra has no built-in authentication support. There are some gems available, but most are designed for user authentication (i.e. for a website). For an API, they seem like overkill. It’s easy enough to make your own. Simply check the request params in each of your routes to see if they contain a valid API key, and if not, return a 401 error.
Nothing after the call to
error
will happen if yourvalid_key?
method returns false —error
callshalt
internally, which stops the request from continuing.Of course, it’s not ideal to repeat the check at the beginning of each route. Instead, you can create a small extension that adds conditions to your routes:
If you just want authentication on all your routes, use a
before
handler:http://www.secondforge.com/blog/2014/11/05/simple-api-authentication-in-sinatra/ has a slightly more detailed answer that uses user tokens.
This is one step more complicated than an API key, but is necessary if your API needs authentication to log in a user to do things such as editing a name/email/password, or accessing per-user information. (i.e. "private" API actions). You can also revoke/expire user tokens to let people log out, etc.
(It's worth to note that it's more common to read credentials from an HTTP header instead of the JSON body, but the author mentions that.)