1. The user launches the mobile app and is prompted to enter username/email and a password to identify themselves as an authorized user.
2. The app sends a POST request over TLS to the Authorization Server with the type of flow, client ID and user’s credentials.
$ curl -i \
-X POST \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=password&username=USERNAME &password=PASSWORD&client_id=cd72a…a9a45 ' \
3. If validation is successful, the app will receive a 200 OK response with the access token that expires after a certain amount of time (and optional a refresh token). Here is a sample of the returned JSON structure:
HTTP/1.1 200 OK
4. The app stores the access token on the mobile device somewhere (you know exactly where, because we talked about that in the part 1 of this article).
5. Like an API key, you can now include the access_token in the authorization header of your requests to access to protected resources.
$ curl -X POST -H "Authorization: Bearer cd72a…xp45"
6. Once the access token expires and no longer works, you re-prompt the user for their username/email and password.
An important advantage of using OAuth 2.0 to secure APIs is that it does not require you to store API keys in an unsafe environment. Instead, it will generate access tokens that can be stored in an untrusted environment temporarily. If attackers somehow manage to obtain your temporary access token, they can potentially invoke malicious operations, such as deleting data. However, OAuth provides several improvements over API keys. Additionally, access tokens can be tied to particular scopes, which restrict the types of operations and data the application can access. Also, combined with refresh tokens, access tokens will expire, so the negative effects could have a limited impact.
Ok, you now have an idea about what is OAuth and could see some details about how to implement the Password flow, one of the most used grant types. Let’s continue by expanding on another way to enhance security for your app.
JSON Web Token (JWT) is an open standard (RFC7519) that defines a JSON object as a safe way to represent a set of information between two parties. It looks like a longer randomly-generated string; the size depends on how much data you store within them. This string has generally three parts: a header, a payload, and a signature.
Sample of Decoded JWT
base64UrlEncode(header) + "." +
The header is the part that identifies which algorithm is used to generate the signature. The payload contains the data stored. The signature is calculated by base64 encoding the header and payload. The result is three Base64 strings separated by dots that can be easily passed in HTTP requests.
Sample of Encoded JWT
In our example, we did only put two claims into the payload, the “name” of the user and “role”. You can put as many claims as you want. Also, there are different standard claims for the JWT payload, “exp” for example is used for the expiration time, but they are optional. In short, JWTs are more convenient than traditional access tokens, and have many more benefits, including:
- Holds JSON data
- Can reduce the number of API calls to your service while still not compromising security by allowing users to validate their API credentials locally
- Can be signed so you can be sure the senders are who they say they are
- Also, as the signature is calculated using the header and the payload, you can verify if the token was not tampered with.
The most common scenario for using JWT is for Authentication. So wow your “Catalog of Products” app could take advantage of JWT You could change the server configuration to return a JWT with a set of claims instead a regular access token. So when the user successfully logs in using their credentials, a JSON Web Token will be returned. Then the app will give to it the same treatment, securely storing tokens locally and sending within each request in the authorization header. Additionally to the security advantages previously mentioned, using JWT, your API service also avoids multiple queries to the databases (once the data required to determine the identity and scope of access are in the token).
You should now have a good understanding why is it useful to use JWT as the OAuth access token. But keep in mind that you should restrict the usage to data that you are ok with being publicly exposed. It is normally used to store user ID and permissions.
Proof Key for Code Exchange
In the section describing the OAuth 2.0 grant types, we only went in details on the Password grant flow. The main difference between Password and Authorization Code grants instead of getting the user credentials and sending them to the server to obtain the access token, the client will redirect the users to authenticate themselves on the authorization server. Then the server will return the authorization code representing the authorization delegation performed by the user. On public clients, this code is all the application needs to obtain the access token allowing access to the User’s resources.
Where is the security issue? If attackers creates a native application that registers the same redirect URI used by your app, they can obtain the authorization code, because the server will sent it to any installed app with the same URL scheme. Unfortunately, there is no central entity controlling these scheme registrations, so an application can hijack the message from the browser to the client app. Having obtained the authorization code, the malicious app has all the information required to retrieve an access token and access the User’s resources.
To address this vulnerability, the PKCE specification introduces additional parameters to certain messages of the flow. When the client app is redirected to the authorization server page in the browser, it generates a random secret, stores it and uses its hash value on the new code_challenge authorization request parameter. The server stores away this hash value and associates it with code before returning it back to the app. When the app then exchanges the code for the access token, it will include the code_verifier parameter with the secret on that call. The server computes the hash of the code_verifier value and compares it with the original code_challenge associated with the code. If it is missing or does not match, the authorization server will not return the access token.
This ensures that only the entity that started the flow can end the flow and obtain the access token. Even if a malicious app is able to obtain a code, without the corresponding code_verifier it will be unable to obtain an access token, making the knowledge of the code insufficient to use it.
So, if you plan to use the Authorization Code flow in your app, make sure to use PCKE (if supported by your Authorization server) because it provides an important security enhancement..
Which of the presented security mechanisms should I use in my app?
As you can see, these security options are not mutually exclusive. In fact, it is possible an API could use all of these at the same time. Or, each could be used independently of the others. You can rely on API keys if you expect to build a internal app that do not need to access more than another application data. You can use OAuth with Authorization Code flow if you want users to easily provide authorization to apps without needing to use their credentials in the app. You can use OAuth with Password flow to allow your employees to identify themselves using their Intranet credentials to access protected corporation systems. There are many others scenarios, but no matter which scenario you need to cover, the application developer is responsible to handle some important implementation considerations regarding security. As mentioned in the beginning, this is just an introduction about some of the security mechanisms available to secure the consume of APIs on mobile devices. To summarize, there is a lot to learn. There are entire books on OAuth 2.0 security framework with details of authenticating multiple types of applications in various scenarios. Plus, we did not cover other security concepts like PKI and SSO. Therefore there is a significant time investment.
Ok, so what if you are daunted by all of these tasks you just read about because you know it will take several months to implement. Is there anything simpler? Yes there is.
CA Mobile API Gateway SDK
You can save a lot of time on developing your app using the Mobile SDK for CA Mobile API Gateway to access any protected API. App developers can rely on our Mobile SDK to provide security using OAuth, OpenID Connect, PCKE, JWT, Social Login, SSO, Public key Infrastructure (PKI), MutualSSL, Dynamic Client Registration, and much more. Using a token-based system with individually issued tokens for users, apps and devices provides the most flexibility for API access policies. It is an open source solution designed to help you develop cross-platform mobile applications, desktop applications, or web applications, along with many services to help you rapidly develop mobile and IoT apps.