简体   繁体   English

如何为移动应用程序保护REST API?

[英]How to secure a REST API for mobile applications?

I am trying to add a REST interface to Django for a mobile client. 我正在尝试为Django添加一个REST接口,用于移动客户端。 The mobile client will use JSON over HTTPS. 移动客户端将通过HTTPS使用JSON。 I have not been able to find the "best" way to accomplish this for mobile devices. 我无法找到为移动设备实现这一目标的“最佳”方式。 From searching around, it seems that #2 is more favorable to #1: 从搜索周围来看,#2似乎更有利于#1:

  1. Use HTTP authentication and establish a cookie based session. 使用HTTP身份验证并建立基于cookie的会话。 All transactions will occur over HTTP and JSON messages will only contain commands or data. 所有事务都将通过HTTP发生,JSON消息将仅包含命令或数据。
  2. Pass the username and password (encrypted) within each JSON msg for all transactions and do not rely on cookie-based sessions. 在所有事务的每个JSON消息中传递用户名和密码(加密),不依赖于基于cookie的会话。

I would recommend sending the username / password first with a login call. 我建议首先通过登录电话发送用户名/密码。 The JSON will pass back an authToken or accessToken which the mobile device will send back for all subsequent calls. JSON将传回一个authToken或accessToken,移动设备将为后续所有呼叫发送回来。 You will then check to make sure the authToken is valid. 然后,您将检查以确保authToken有效。 This is the approach many API's take. 这是许多API采用的方法。 In their database they will bind the API key to the users account that they logged in with. 在他们的数据库中,他们将API密钥绑定到他们登录的用户帐户。

OAuth is overkill unless you want to make these services available to other developers (which they would access on behalf of your end users). 除非您希望将这些服务提供给其他开发人员(他们将代表您的最终用户访问),否则OAuth可能会过度。 Better to go with option 2, but I would recommend using Digest Authentication as opposed to Password Authentication. 最好使用选项2,但我建议使用摘要式身份验证而不是密码身份验证。 Combine that with SSL and you are definitely good to go. 将它与SSL结合起来,你绝对不错。

Number 2 is preferable, and rather than roll your own, I would recommend using OAuth authentication if possible. 2号是首选,而不是自己滚动,我建议尽可能使用OAuth身份验证。 Both client and server libraries are readily available for use on most platforms now. 客户端和服务器库现在都可以在大多数平台上使用。 Check http://oauth.net for details. 查看http://oauth.net了解详情。

So long as you're using actual encryption and not base64 or some homegrown obfuscation algorithm, #2 is fine and dandy. 只要您使用的是实际加密而不是base64或某些自行开发的混淆算法,#2就可以了。 You might also want to consider the route many companies take, which is binding an API key to a username. 您可能还想考虑许多公司采用的路由,即将API密钥绑定到用户名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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