Rest API Authorization & Authentication (Web + Mobile)

REST API authentication for web app and mobile app

You should use OAuth2. Here is how:

1) Mobile App

The mobile app store client credentials as you state yourself. It then uses "Resource Owner Password Credentials Grant" (see https://www.rfc-editor.org/rfc/rfc6749#section-4.3) to send those credentials. In turn it gets a (bearer) token it can use in the following requests.

2) Web site

The website uses "Authorization Code Grant" (see https://www.rfc-editor.org/rfc/rfc6749#section-4.1):

  1. Website sees unauthorized request and redirects browser to HTML-enabled autorization endpoint in the REST api.

  2. User authenticates with REST service

  3. REST site redirects user back to website with access token in URL.

  4. Website calls REST site and swaps access token to authorization token.

Here after the website uses the authorization token for accessing the REST service (on behalf of the end-user) - usually by including the token as a "bearer" token in the HTTP Authorization header.

It is not rocket science but it does take some time to understand completely.

3) Restricting API access for certain applications

In OAuth2 each client is issued a client ID and client secret (here "client" is your mobile app or website). The client must send these credentials when authorizing. Your REST service can use this to validate the calling client

REST API Authorization & Authentication (web + mobile)

As allways, the best way to protect a key is not to transmit it.

That said, we typically use a scheme, where every "API key" has two parts: A non-secret ID (e.g. 1234) and a secret key (e.g. byte[64]).

  • If you give out an API key, store it (salted and hashed) in you
    service's database.
  • If you give out user accounts (protected by password), store the
    passwords (salted and hashed) in your service's database

Now when a consumer first accesses your API, to connect, have him

  • Send a "username" parameter ("john.doe" not secret)
  • Send a "APIkeyID" parameter ("1234", not secret)

and give him back

  • the salts from your database (In case one of the parameters is wrong,
    just give back some repeatable salt - eg.
    sha1(username+"notverysecret").
  • The timestamp of the server

The consumer should store the salt for session duration to keep things fast and smooth, and he should calculate and keep the time offset between client and server.

The consumer should now calculate the salted hashes of API key and password. This way the consumer has the exact same hashes for password and API key, as what is stored in your database, but without anything seceret ever going over the wire.

Now when a consumer subseqently accesses your API, to do real work, have him

  • Send a "username" parameter ("john.doe" not secret)
  • Send a "APIkeyID" parameter ("1234", not secret)
  • Send a "RequestSalt" parameter (byte[64], random, not secret)
  • Send a "RequestTimestamp" parameter (calculated from client time and known offset)
  • Send a "RequestToken" parameter (hash(passwordhash+request_salt+request_timestamp+apikeyhash))

The server should not accept timestamps more than say 2 seconds in the past, to make this safe against a replay attack.

The server can now calculate the same hash(passwordhash+request_salt+request_timestamp+apikeyhash) as the client, and be sure, that

  • the client knows the API key,
  • the client knows the correct password

How to secure an API REST for mobile app? (if sniffing requests gives you the key)

Am I wrong?
Is this a stupid question?

No you are not wrong, and it's not a stupid question at all, because it's indeed easy to attack an API server of a mobile app, and you will be surprised to know how many senior developers are not aware how easy it can be done, and I have noticed that more often then not, this is due to their misconception about what vs who is accessing the API server.

The difference between what and who is accessing the API server.

This is discussed in more detail in this article I wrote, where we can read:

The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?

The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.

So if the quoted text is not enough to clarify you, then please go ahead and read the entire section of the article.

Impersonating the Mobile APP

In those request I've found a lot of auth keys that I can use in other calls from a console, simulating the app with no problems.

If by auth keys you mean the ones provide via user sign-in, with his username and password, then they just identify the who in the request.

For other keys, like api-keys, access-tokens, or any other convention used to name them, they have the purpose of providing to the API server a mechanism to only authorize requests from the genuine mobile app, they are indeed trying to allow the API server to identify what is doing the request, and has you already discovered it's easy to extract them with a proxy:

Although you use SSL, it's "usually easy" to hack mobile apps (I'm thinking in Android right now: decompiling the app, changing manifest to allow custom SSL, compiling again and sniffing through a SSL proxy all the requests).

So, in the end of the day all an attacker needs it's to use a proxy to learn how the API server works, and what is needed to simulate an API call as if it was done from the mobile app itself.

Hardening and Shielding the Mobile App

So, now I've hacked some API's in mobile apps, my question is: is there any way to secure an API in a mobile app?

You can use Mobile Hardening and Shielding solutions, that will try to prevent the mobile app to work in compromised/rooted devices, with modified/tampered apps and/or when some instrumentation framework is being used during runtime, but all of them have the draw-back of performing all that decisions in the mobile app, therefore subject to be manipulated or totally bypassed by the alreay dito instrumentation frameworks, and a good example of one it's Frida:

Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.

While is better to use an in app solution, than not using anything, it's still not the ideal solution, because the control of deciding what to do is in the client side, not in the server side, thus the attacker can resort to use Frida to introspect the code at runtime and learn how to impersonate the mobile app.

Securing the API Server

The Basic API Security Defenses

Now that you understand the difference between who vs what is accessing your API server and you know that an attacker can learn how to impersonate your genuine mobile app you may want to go an read my article about the basic techniques to secure an API:

In this article we will explore the most common techniques used to protect an API, including how important it is to use HTTPS to protect the communication channel between mobile app and API, how API keys are used to identify the mobile app on each API request, how user agents, captchas and IP addresses are used for bot mitigation, and finally how user authentication is important for the mobile security and api security. We will discuss each of these techniques and discuss how they impact the business risk profile, i.e. how easy they are get around.

This is only a very basic technique that the majority of APIs may already employ, but they can be reinforced with some more advanced techniques.

More Advanced API Security Defenses

You can start to read this series of articles on Mobile API Security Techniques to understand how API keys, HMAC, OAUTH and certificate pinning can be used to enhance the security and at same time learn how they can be abused/defeated.

Afterwards, and depending on your budget and resources you may employ an array of different approaches and techniques to defend your API server, and I will start to enumerate some of the most usual ones.

You can start with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.

Google reCAPTCHA V3:

reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.

WAF - Web Application Firewall:

A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.

UBA - User Behavior Analytics:

User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.

All this solutions work based on a negative identification model, by other words, they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.

So, you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.

Regarding APIs serving mobile apps a positive identification model can be used by implementing a Mobile App Attestation solution that attests the integrity of your mobile app and device its running on before any request is made to the API server.

A Possible Better Solution

The current implementations of a mobile app and API server may look like this:

API direct access from a Mobile App

This approach is what leaves the API keys vulnerable to be extracted by attackers via proxy interception(red line), just like you already noticed by using a proxy to intercept them.

A better approach would be something like this:

No API Key in a mobile app

Wait, but I don't see any API key in the mobile app anymore:

Am I missing something ?

Yes, a Mobile App Attestation solution.

To be in a position where you don't need to ship any secrets with your mobile app, then you need to resort to the Mobile App Attestation concept, and from this article section I will quote the relevant parts to explain it's role:

The role of a Mobile App Attestation service is to authenticate what is sending the requests, thus only responding to requests coming from genuine mobile app instances and rejecting all other requests from unauthorized sources.

In order to know what is sending the requests to the API server, a Mobile App Attestation service, at run-time, will identify with high confidence that your mobile app is present, has not been tampered/repackaged, is not running in a rooted device, has not been hooked into by an instrumentation framework(Frida, xPosed, Cydia, etc.), and is not the object of a Man in the Middle Attack (MitM). This is achieved by running an SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device it is running on.

On a successful attestation of the mobile app integrity, a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud know. In the case that attestation fails the JWT token is signed with an incorrect secret. Since the secret used by the Mobile App Attestation service is not known by the mobile app, it is not possible to reverse engineer it at run-time even when the app has been tampered with, is running in a rooted device or communicating over a connection that is the target of a MitM attack.

The mobile app must send the JWT token in the header of every API request. This allows the API server to only serve requests when it can verify that the JWT token was signed with the shared secret and that it has not expired. All other requests will be refused. In other words a valid JWT token tells the API server that what is making the request is the genuine mobile app uploaded to the Google or Apple store, while an invalid or missing JWT token means that what is making the request is not authorized to do so, because it may be a bot, a repackaged app or an attacker making a MitM attack.

A great benefit of using a Mobile App Attestation service is its proactive and positive authentication model, which does not create false positives, and thus does not block legitimate users while it keeps the bad guys at bay.

The Mobile App Attestation releases your mobile app from having an embedded secret in its code, instead now it only needs to pass to the reverse proxy or backend the JWT token it receives from the mobile app attestation service. Now the reverse proxy or backend can verify the JWT token, and on successful validation they can accept requests with a very high confidence that they are originated from what they expect, a true and genuine instance of the mobile app, with the added benefit of not exposing the API keys to access your API server or any Third Party services.

GOING THE EXTRA MILE

I cannot finish without recommending you the excellent work done by the OWASP foundation.

For Mobile Apps

OWASP - Mobile Security Testing Guide:

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.

For APIS

OWASP API Security Top 10

The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

securing REST-API accessed by mobile application with no login

You cannot avoid that people reverse engineer and obtain your API key (or hard coded user/password combo). You can make it harder, for instance by enforcing HTTPS with Certificate Pinning during the communication with your server or applying IP based API rate limiting, such that people cannot easily spy on the communication or dump whatever your API returns en masse, but you cannot make it impossible. Expect people to always have the same privileges that your App (on their device) has. In your case, that means that an attacker could also generate unlimited UIDs, since they are generated by a client request. That makes using the UID for any kind of serious authentication pretty useless.

I mean, after all, an attacker also could write code to automatically use your app to extract the information you are trying to protect, even if he would not be able to disassemble your application. What you are requesting is not possible.

Authorization Code Flow, sending the code from a mobile app to a REST API

Hmm - some assumptions below, but I would aim to use standard flows. Some solutions are not possible in a good way though.

BUSINESS SOLUTION

Are you trying to build an app that combines the user's Spotify data with your own data for the user?

ARCHITECTURE TO AIM FOR

Your own UIs and APIs should use tokens issued by you and not Spotify. Only use Spotify tokens when you need to access Spotify resources. This leads to simple and reliable code.

STANDARD OPTION 1

This is based on you being in control of data from multiple sources:

  • You should have your own login and token issuing system. UI first logs into your app, which enables it to call your API with a token.

  • When you want to access Spotify you need to redirect the user again. The user can then consent to you using Spotify resources in your app, after which your web / mobile UIs get a Spotify token and can call Spotify APIs.

STANDARD OPTION 2

This is based on allowing the user to sign in with a familiar credential, which works via a federated login:

  • User needs to login
  • Your app redirects to your Authorization Server
  • There is a second redirect to Spotify
  • User logs in at Spotify
  • Spotify posts a token to your Authorization Server
  • Your Authorization Server posts its own token to your mobile app

Meanwhile your Web API has its own connection to Spotify that uses the Client Credentials Flow.

DOUBLE HOPPING CODES / TOKENS

This is not insecure, but it will add a lot of complexity and is not standard. You would need to maintain some kind of API session with 2 types of token per user and access token expiry would be a horrible area.

MOBILE FLOW

For mobile apps you should use Authorization Code Flow (PKCE) - my blog posts have some stuff on messages and user experience.



Related Topics



Leave a reply



Submit