By Nathan


2008-08-11 05:44:42 8 Comments

When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ?

When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints.

While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged.

Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework.

18 comments

@Andrejs 2017-11-08 20:29:14

There is a great checklist found on Github:

Authentication

  • Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.

  • Use Max Retry and jail features in Login.

  • Use encryption on all sensitive data.

JWT (JSON Web Token)

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.

  • Don't extract the algorithm from the payload. Force the algorithm in the backend (HS256 or RS256).

  • Make token expiration (TTL, RTTL) as short as possible.

  • Don't store sensitive data in the JWT payload, it can be decoded easily.

OAuth

  • Always validate redirect_uri server-side to allow only whitelisted URLs.

  • Always try to exchange for code and not tokens (don't allow response_type=token).

  • Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.

  • Define the default scope, and validate scope parameters for each application.

Access

  • Limit requests (Throttling) to avoid DDoS / brute-force attacks.

  • Use HTTPS on server side to avoid MITM (Man In The Middle Attack)

  • Use HSTS header with SSL to avoid SSL Strip attack.

Input

  • Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.

  • Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc) and respond with 406 Not Acceptable response if not matched.

  • Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc).

  • Validate User input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc).

  • Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.

  • Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, Concurrent Rate Limit) and deploy APIs resources dynamically.

Processing

  • Check if all the endpoints are protected behind authentication to avoid broken authentication process.

  • User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.

  • Don't auto-increment IDs. Use UUID instead.

  • If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).

  • If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.

  • Use a CDN for file uploads.

  • If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.

  • Do not forget to turn the DEBUG mode OFF.

Output

  • Send X-Content-Type-Options: nosniff header.

  • Send X-Frame-Options: deny header.

  • Send Content-Security-Policy: default-src 'none' header.

  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.

  • Force content-type for your response, if you return application/json then your response content-type is application/json.

  • Don't return sensitive data like credentials, Passwords, security tokens.

  • Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).

@johndodo 2017-12-24 19:43:52

Nice list, though a bit opinionated - and it starts with a nonsense imho: "Don't use Basic Auth Use standard authentication (e.g. JWT, OAuth)." You can't get more standard-y than Basic Auth, and it has its place, especially for APIs where the clients are not browsers (for browsers JWT is usually more suitable). OAuth on the other hand is using a whole other set of compromises for authentication and is not really comparable to Basic Auth and JWT.

@Andrejs 2017-12-28 16:38:21

You're right, BasicAuth with HTTPS is common, but it is hotly debated - security.stackexchange.com/questions/988/… . I will remove this point anyway.

@Matt Bannert 2017-08-11 21:51:08

It's been a while but the question is still relevant, though the answer might have changed a bit.

An API Gateway would be a flexible and highly configurable solution. I tested and used KONG quite a bit and really liked what I saw. KONG provides an admin REST API of its own which you can use to manage users.

Express-gateway.io is more recent and is also an API Gateway.

@Rob Ottaway 2009-01-09 21:25:56

I've used OAuth a few times, and also used some other methods (BASIC/DIGEST). I wholeheartedly suggest OAuth. The following link is the best tutorial I've seen on using OAuth:

http://hueniverse.com/oauth/guide/

@skomisa 2019-01-22 20:29:43

Although this is a very old answer relating to OAuth 1.0, it's worth noting that the author of the link you cite had this to say about OAuth 2.0: "I reached the conclusion that OAuth 2.0 is a bad protocol...When compared with OAuth 1.0, the 2.0 specification is more complex, less interoperable, less useful, more incomplete, and most importantly, less secure.". To be clear, the comment I am quoting was made several years after you posted your answer.

@java_geek 2014-10-06 06:05:08

For Web Application Security, you should take a look at OWASP (https://www.owasp.org/index.php/Main_Page) which provides cheatsheets for various security attacks. You can incorporate as many measures as possible to secure your Application. With respect to API security (authorization, authentication, identity management), there are multiple ways as already mentioned (Basic,Digest and OAuth). There are loop holes in OAuth1.0, so you can use OAuth1.0a (OAuth2.0 is not widely adopted due to concerns with the specification)

@Archimedes Trajano 2014-07-17 15:08:57

As @Nathan ended up with which is a simple HTTP Header, and some had said OAuth2 and client side SSL certificates. The gist of it is this... your REST API shouldn't have to handle security as that should really be outside the scope of the API.

Instead a security layer should be put on top of it, whether it is an HTTP Header behind a web proxy (a common approach like SiteMinder, Zermatt or even Apache HTTPd), or as complicated as OAuth 2.

The key thing is the requests should work without any end-user interaction. All that is needed is to ensure that the connection to the REST API is authenticated. In Java EE we have the notion of a userPrincipal that can be obtained on an HttpServletRequest. It is also managed in the deployment descriptor that a URL pattern can be secure so the REST API code does not need to check anymore.

In the WCF world, I would use ServiceSecurityContext.Current to get the current security context. You need to configure you application to require authentication.

There is one exception to the statement I had above and that's the use of a nonce to prevent replays (which can be attacks or someone just submitting the same data twice). That part can only be handled in the application layer.

@Manish Jain 2014-03-01 01:04:58

I want to add(in line with stinkeymatt), simplest solution would be to add SSL certificates to your site. In other words, make sure your url is HTTPS://. That will cover your transport security (bang for the buck). With RESTful url's, idea is to keep it simple (unlike WS* security/SAML), you can use oAuth2/openID connect or even Basic Auth (in simple cases). But you will still need SSL/HTTPS. Please check ASP.NET Web API 2 security here: http://www.asp.net/web-api/overview/security (Articles and Videos)

@WelsonJR 2014-02-24 18:41:39

OWASP(Open Web Application Security Project) has some cheat sheets covering about all aspects of Web Application development. This Project is a very valuable and reliable source of information. Regarding REST services you can check this: https://www.owasp.org/index.php/REST_Security_Cheat_Sheet

@kravietz 2013-11-21 14:19:04

The fact that the SOAP world is pretty well covered with security standards doesn't mean that it's secure by default. In the first place, the standards are very complex. Complexity is not a very good friend of security and implementation vulnerabilities such as XML signature wrapping attacks are endemic here.

As for the .NET environment I won't help much, but “Building web services with Java” (a brick with ~10 authors) did help me a lot in understanding the WS-* security architecture and, especially, its quirks.

@David Brossard 2013-09-24 22:22:33

Everyone in these answers has overlooked true access control / authorization.

If for instance your REST APIs / web services are about POSTing / GETing medical records, you may want to define access control policie about who can access the data and under which circumstances. For instance:

  • doctors can GET the medical record of a patient they have a care relationship with
  • no one can POST medical data outside practice hours (e.g. 9 to 5)
  • end-users can GET medical records they own or medical records of patients for whom they are the guardian
  • nurses can UPDATE the medical record of a patient that belongs to the same unit as the nurse.

In order to define and implement those fine-grained authorizations, you will need to use an attribute-based access control language called XACML, the eXtensible Access Control Markup Language.

The other standards here are for the following:

  • OAuth: id. federation and delegation of authorization e.g. letting a service act on my behalf on another service (Facebook can post to my Twitter)
  • SAML: identity federation / web SSO. SAML is very much about who the user is.
  • WS-Security / WS-* standards: these focus on the communication between SOAP services. They are specific to the application-level messaging format (SOAP) and they deal with aspects of messaging e.g. reliability, security, confidentiality, integrity, atomicity, eventing... None cover access control and all are specific to SOAP.

XACML is technology-agnostic. It can be applied to java apps, .NET, Python, Ruby... web services, REST APIs, and more.

The following are interesting resources:

@Stan 2013-12-31 15:23:02

I don't understand why can't you just implement token system that will get the user and his permissions which will essentially be the same thing?

@David Brossard 2014-01-02 07:44:37

You can take a token-based approach. That works well too but you still need the logic that defines which permissions users get, in other words, which permissions to insert inside the token. That's what XACML can help you achieve. It also avoids token bloat.

@Roland 2016-07-11 13:43:21

As a side comment, what does "9 to 5" contribute to security? As if attackers are only active at night? Not to speak of the severe usage implications, as if doctors only work "9 to 5".

@David Brossard 2016-07-11 14:44:55

That's a common requirement in healthcare scenarios. Check out HL7 for instance. There are break-the-glass scenarios too in case a doctor does need access outside hours. As for hackers, once they're in all bets are off

@Simply G. 2018-05-09 10:15:13

@DavidBrossard If you have not yet, I would have a look at block chain solutions for handling permissions.

@David Brossard 2018-05-09 12:00:18

Some of my colleagues are investigating that indeed. Thanks @SimplyG.

@Abhijit Gaikwad 2013-03-14 00:59:38

I would recommend OAuth 2/3. You can find more information at http://oauth.net/2/

@Butifarra 2013-03-20 22:57:37

Care to elaborate why would you recommend version 2 when it remains largely incomplete? IMHO, version 1.0a remains a solid solution for most apps.

@Robert Morschel 2012-10-12 08:22:50

REST itself offers no security standards, but things like OAuth and SAML are rapidly becoming the standards in this space. However, authentication and authorization are only a small part of what you need to consider. Many of the known vulnerabilities relating to web applications apply very much to REST apis. You have to consider input validation, session cracking, inappropriate error messages, internal employee vulnerabilities and so on. It is a big subject.

@Parisa Kachoui 2012-05-15 10:36:28

I searched a lot about restful ws security and we also ended up with using token via cookie from client to server to authenticate the requests . I used spring security for authorization of requests in service because I had to authenticate and authorized each request based on specified security policies that has already been in DB.

@Mark Renouf 2008-08-11 06:07:03

There are no standards for REST other than HTTP. There are established REST services out there. I suggest you take a peek at them and get a feel for how they work.

For example, we borrowed a lot of ideas from Amazon's S3 REST service when developing our own. But we opted not to use the more advanced security model based on request signatures. The simpler approach is HTTP Basic auth over SSL. You have to decide what works best in your situation.

Also, I highly recommend the book RESTful Web Services from O'reilly. It explains the core concepts and does provide some best practices. You can generally take the model they provide and map it to your own application.

@EdgarVerona 2009-01-09 21:34:22

RESTful Web Services is definitely a great book. A must read in this area. It was downright inspiring.

@user4903 2012-04-15 00:37:02

How is it that @aehlke has received so many upvotes for that comment considering (1) there is no such thing as a REST specification and (2) the Fielding Dissertation on the Architectural Styles and the Design of Network-based Software Architectures explicitly mentions REST and HTTP in 6.3: REST Applied to HTTP.

@nategood 2013-05-16 19:21:07

HTTP is not a requirement for REST.

@icc97 2018-06-05 15:08:01

The RESTful Web Services book is available for free from their website: crummy.com/writing/RESTful-Web-Services

@Bhargav Jhaveri 2018-07-14 00:43:04

I was planning to read the book and then I realized it is mainly targetted for XML format. Should I use this book considering the popularity of JSON? Or it is not dependent on the Data Interchange Format. Need guidance.

@yolob 21 2019-05-31 09:46:48

rest functionality is not coupled with the format of the data

@stinkymatt 2009-09-25 19:39:38

I'm kind of surprised SSL with client certificates hasn't been mentioned yet. Granted, this approach is only really useful if you can count on the community of users being identified by certificates. But a number of governments/companies do issue them to their users. The user doesn't have to worry about creating yet another username/password combination, and the identity is established on each and every connection so communication with the server can be entirely stateless, no user sessions required. (Not to imply that any/all of the other solutions mentioned require sessions)

@Casey 2012-09-05 13:55:35

We actually do use this for some integrations as well as encrypted vpn tunnels to support older systems that we don't control that can not communicate over https.

@Jeremy Logan 2012-10-15 18:11:41

Client certs can make trouble when you need load balancing... it can be done, but it's less straight-forward.

@stinkymatt 2012-10-15 19:25:10

@fiXedd - The opposite has been my experience with client certs because they are truly stateless. Client cert authenticated connections can be load balanced with a dumb load balancer with no regard to connection stickyness because they require absolutely zero shared state between the client and server.

@Jeremy Logan 2012-10-19 16:12:26

Oh, you can do it.... you can just have the load balancer forward the TCP traffic, but you can't, for instance, have the load balancer be the termination point for the SSL.

@Joyce 2015-03-18 17:17:59

Is it still secure if the client certificates and its root authority are self-signed? The root authority will be imported into the client's trusted root certificate authorities.

@degnome 2008-09-18 20:53:16

One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.

@Nathan 2008-10-13 23:07:23

Thanks for the link (1 RainDrop) - very interesting discussion of security as it relates to SOAP v REST

@John Spurlock 2008-09-18 02:55:07

You may also want to take a look at OAuth, an emerging open protocol for token-based authorization specifically targeting http apis.

It is very similar to the approach taken by flickr and remember the milk "rest" apis (not necessarily good examples of restful apis, but good examples of the token-based approach).

@redben 2010-11-11 00:04:49

But it seems that 2-legged oAuth, which i think is what is need here, isn't covered (lack of info) as much as the 3-legged one.

@David Brossard 2013-09-24 22:15:48

OAuth is about delegation of authorization i.e. I the owner of the information / account let service A interact with my data on service B (e.g. I let Twitter write on my facebook). It's not authorization in the broader sense which is about controlling what users can do on resources (data, information, services...). This is where XACML steps in. XACML lets you define authorization policies about who can do what.

@Nathan 2008-09-17 20:30:10

Thanks for the excellent advice. We ended up using a custom HTTP header to pass an identity token from the client to the service, in preparation for integrating our RESTful API with the the upcoming Zermatt Identity framework from Microsoft. I have described the problem here and our solution here. I also took tweakt's advice and bought RESTful Web Services - a very good book if you're building a RESTful API of any kind.

@Gili 2008-10-03 18:10:14

This approach sounds fishy to me. What prevents an attacker from using the identity token to masquerade the client? HTTPS doesn't protect the URL or headers the last time I checked...

@Nathan 2008-10-29 23:23:50

Hmmm...not sure you're right about that. I believe that except for the few headers required to understand what kind of encryption is required, all other headers are encrypted.

@Mark Renouf 2009-02-04 13:31:41

That is wrong. HTTPS protects EVERYTHING. It goes: TCP handshake... TLS handshake... <ENCRYPTED> GET /foo 200 OK... teardown </ENCRYPTED>.

@TarasB 2011-01-25 11:22:11

I also used custom headers to pass a token.

@Bruce Alderson 2011-11-10 19:51:55

Note that you can also pass a token as a cookie (instead of a custom header). This behaves well in browsers as it uses an HTTP header with standard behaviours in most toolkits and applications. On the service side, the cookie does not have to relate to a session, you can use it to communicate any token you wish.

@Win Myo Htet 2012-03-13 22:57:24

Nathan, your problem and solution links on the githubs are gone. Do you have planned to post them back somewhere? Thx.

@Nathan 2012-03-14 18:40:51

I'm sorry I don't - I don't work with .NET anymore and let my .NET blog hosting lapse, so alas they are gone forever. Sorry.

@cjc343 2012-10-23 20:03:53

The Wayback Machine is a beautiful thing: problem description and solution

@Greg Hewgill 2008-08-11 08:45:13

As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying.

The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time.

Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed.

@Norman H 2013-01-01 22:19:39

SSL is an important part of security, but not all applications require that level of encryption. If someone steals in-transit what you are going to post publicly on Twitter, is that such a significant drawback? For the majority of API's SSL encryption is going to be preferred. The infrastructure requirements of SSL are somewhat higher than with plaintext and no intermediate (read here edge based) caching servers can participate in the caching of repeatedly accessed content. Beware, your scalability may suffer if you absolutely require the encryption offered.

@Greg Hewgill 2013-01-02 00:51:14

@NormanH: Your argument is specious, because if somebody can see the entire transaction that I use to post to Twitter, then they could therefore impersonate me and post their own messages under my name.

@Norman H 2013-01-02 18:11:37

@GregHewgill yes, I did consider that, however authentication tokens could be encrypted even though the entire channel is not SSL encrypted.

@Norman H 2013-01-02 18:45:00

Quoting from wikipedia on Digest authentication, "Digest access authentication is one of the agreed-upon methods a web server can use to negotiate credentials with a user's web browser. It applies a hash function to a password before sending it over the network, which is safer than basic access authentication, which sends plaintext." which would be one standard way of accomplishing what I alluded to above. (See en.wikipedia.org/wiki/Digest_access_authentication for the details)

@Kevin Day 2014-02-12 03:38:57

@WillSargent The BuzzFeed article is phenomenal - great resource. One gotcha that I hadn't considered is to not put authentication tokens of any sort into the URL or parameters - these could get captured in the server's access logs.

@toniedzwiedz 2014-05-29 05:23:59

"sending plaintext passwords over the net is almost universally a bad thing" - Can you elaborate on the "almost"? When is it not a bad idea?

@Greg Hewgill 2014-05-29 07:46:18

@Tom: Perhaps in situations such as within a private network it might be okay. Also, various systems send plaintext passwords over email all the time (still not a good idea, but it happens).

@toniedzwiedz 2014-05-29 08:53:11

@GregHewgill even in a private network, I wouldn't want my users to be able to intercept each others' passwords. The only situation I can think of, in which it's OK to send a password over a network is when the user is alone in the network. The fact that such things happen elsewhere is hardly a reason to allow it.

@guettli 2014-07-09 10:42:01

If you use ssl, you don't need to care about replay attacks. See: security.stackexchange.com/questions/20105/…

@nflash 2015-06-29 15:40:00

@guettli that is not 100% correct. SSL establishes a secure connection but does not prevent to replay messages inside that connection. It prevents to replay a dump collected with a sniffer, but if someone can decrypt the original message (not that hard) then it is possible to rebuild the messages (or create new) and resend the messages, unless some king of message level security is used. SSL by itself is not very secure.

@guettli 2015-06-30 19:34:02

@nflash please provide details. Your quote "SSL by itself is not very secure" is very vague. How can you decrypt the original message? I don't get why you say this is not that hard.

@nflash 2015-07-05 14:23:11

@guettli just by using SSL doesn't mean your app is secure. I see lots of (mobile) developers ignoring Certificate Validation... even if they validate the certificate in an environment controlled by others there are ways to go around this and allow a man in the middle (I have seen and done this in a controlled environment with out of the box tools and without much knowledge about the subject). That’s why I say that SSL by itself is not very secure, but is one of the security layers that you should use

@guettli 2015-07-07 07:00:45

@nflash I am still missing an explanation of "SSL establishes a secure connection but does not prevent to replay messages inside that connection." and "but if someone can decrypt the original message (not that hard)"

@nflash 2015-08-21 11:10:51

@guettli a comment does not allow enough chareters for giving a more detail answer. look for Man in the middle or SSL proxy and you will see how to capture and decrypt messages inside a secure channel (easy with some control over the enviorment). If the messages itself are not authenticated or secured in someway you will be able to reconstruct the message and replay it or even change it and send it. Certitificate validation plays a key role in SSL and if you overcome this then the secure channel is no longer secure.

@guettli 2015-08-21 11:25:35

@nflash I know that it is possible. But it is hard. Running mitmproxy.org is very easy. But first you need run the proxy between the client and the server. Next you need a valid cert for the requested domain. I wouldn't call this "not that hard". It is possible, but not easy.

@nflash 2015-08-24 09:36:53

@guettli as I said: "I see lots of (mobile) developers ignoring Certificate Validation... even if they validate the certificate in an environment controlled by others there are ways to go around this and allow a man in the middle". If you controll the enviorment you can easly install certificates as trusted. In the cases where certificate validation is ignored you don't even have to do this.

@Roman Plášil 2016-04-23 02:30:19

@NormanH: yes, seeing somebody's tweets before they are published is no big deal but with no cryptographic protection, the attacker can also modify them. And that IS a big deal.

Related Questions

Sponsored Content

11 Answered Questions

[SOLVED] Best practice for partial updates in a RESTful service

  • 2010-03-14 18:57:18
  • magiconair
  • 93782 View
  • 204 Score
  • 11 Answer
  • Tags:   rest

11 Answered Questions

[SOLVED] Best practice to return errors in ASP.NET Web API

6 Answered Questions

[SOLVED] REST / SOAP endpoints for a WCF service

  • 2008-10-09 10:11:30
  • Wessam Zeidan
  • 262395 View
  • 421 Score
  • 6 Answer
  • Tags:   wcf rest soap

26 Answered Questions

6 Answered Questions

[SOLVED] Security of REST authentication schemes

Sponsored Content