Application Security

Secure API Development Best Practices – OAuth2 and JWT

We can’t imagine our business without digital. When we send a Twitter, log into an account with our social network, make an online purchase, or check real-time traffic via an app, behind-the-scenes APIs (Application Programming Interfaces) are running. 

In our world of connected devices and applications, APIs play a crucial role in facilitating communication between different systems and applications. In addition to being the connector for B2B or B2C businesses, we are talking about enabling the connection for thousands of devices for the internet of things (IoT). 

APIs revolutionize the world of system integration and are major players in our Digital Transformation era. Therefore, the secure development of APIs is of utmost relevance for organizations to provide secure and reliable access to data and services. In this context, there are several security technologies and best practices that can be applied to ensure the protection of API-based communication, in this article we highlight OAuth2 and JSON Web Token (JWT).

We talk about OAuth2 because it is an open standard for authorization that delegates the process to an authorization server, allowing third-party applications to securely access user data. And we include the efficient and compact form of request, or token, JWT used for authentication and authorization in APIs. 

We believe that awareness and incorporation of these security best practices increase the reliability, integrity of information, and availability of API services, decreasing risk and increasing the credibility and image of organizations.

Nova call to action

OAUTH 2

Gone are the days when the access control process was based on presenting a user and password to the application. Today both authentication and authorization have their complex steps to establish the user’s identity and access profile respectively. 

While some APIs are authenticated with username and password, usually in the form of basic authentication in the header, this is not our recommendation. As a best practice for working with device authorization and server-to-server support, OAuth 2.0 is our recommendation, allowing for a great user experience and enforcing secure development in your API.

But what is OAuth? We stick with the definition present in the OWASP Cheat Sheets Series recommendation list on Authentication, under “Use of authentication protocols that require no password”:

“Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service.”

I would like to take this opportunity to inform you that we have discussed the difference between OAuth2 and SAML in a previous article.

OAuth 2.0 Advantages

As positive points when choosing to use Oauth 2 as an authorization protocol, we can cite the simplicity of use and the comprehensiveness of the technology. It can be used for web, desktop, and mobile applications. Besides these, it is worth mentioning the advantages of: 

  • The user does not need to create another profile to access the application;
  • Few passwords to remember;
  • Time savings, since no authentication needs to be developed;
  • Lower risk of identity theft since authentication occurs at the provider; 
  • Tokens are transmitted in encrypted form and not stored in the application;
  • Fewer data to store on servers.

Threats to OAuth 2.0

It is possible for attackers to threaten Oauth flows with CSRF, XSS, and

Open Redirect. The following threats can be listed:

  • Threats on the endpoint;
  • Redirect Hijack;
  • Man-In-The-Middle (MITM) Attack.

Examples of vulnerabilities:

  • Authorization Code Injection Attack;
  • OAuth Phishing via Unchecked Redirect URI;
  • OAuth Client Secret Disclosure.

More information about the weaknesses can be found in RFC-6819 Threat Modeling and Security Considerations for OAuth 2.0

Security Best Practices for OAuth 2.0

Because of these possible attack scenarios, it is important to pass on the best practices of secure API development when using OAuth 2.0:

  • Always validate the “redirect_uri” parameter on the server side to allow only approved URLs and thus avoid open redirect attacks;
  • Always try to make the exchange with code, instead of getting the token directly (avoid “response_type=token”);
  • Use the “state” parameter with a random hash to prevent CSRF attacks in the OAuth authentication process;
  • Define and validate the scope for each application;
  • Always use secure communication, such as HTTPS, when transmitting OAuth2 tokens and authorization codes.

JSON Web Token (JWT)

The JWT standard defines how to transmit and store JSON objects between applications securely, simply, and in a compact form. It is an open standard documented in RFC-7519. Widely used in the validation of services in Web Services, for the advantages that we will see below, already highlighting the possibility of local validation.

Knowing the structure of JWT we see that it is a JSON structure composed of a Header, Payload, and Signature. 

But what is OAuth? We stick with the definition present in the OWASP Cheat Sheets Series recommendation list on Authentication, under “Use of authentication protocols that require no password”:

“Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server and provides how the authorization flows most occur, so that a client, such as a mobile application, can tell the server what user is using the service.”

I would like to take this opportunity to inform you that we have discussed the difference between OAuth2 and SAML in a previous article.

OAuth 2.0 Advantages

As positive points when choosing to use Oauth 2 as an authorization protocol, we can cite the simplicity of use and the comprehensiveness of the technology. It can be used for web, desktop, and mobile applications. Besides these, it is worth mentioning the advantages of: 

  • The user does not need to create another profile to access the application;
  • Few passwords to remember;
  • Time savings, since no authentication needs to be developed;
  • Lower risk of identity theft since authentication occurs at the provider; 
  • Tokens are transmitted in encrypted form and not stored in the application;
  • Fewer data to store on servers.

Threats to OAuth 2.0

It is possible for attackers to threaten Oauth flows with CSRF, XSS, and

Open Redirect. The following threats can be listed:

  • Threats on the endpoint;
  • Redirect Hijack;
  • Man-In-The-Middle (MITM) Attack.

Examples of vulnerabilities:

  • Authorization Code Injection Attack;
  • OAuth Phishing via Unchecked Redirect URI;
  • OAuth Client Secret Disclosure.

More information about the weaknesses can be found in RFC-6819 Threat Modeling and Security Considerations for OAuth 2.0

Security Best Practices for OAuth 2.0

Because of these possible attack scenarios, it is important to pass on the best practices of secure API development when using OAuth 2.0:

  • Always validate the “redirect_uri” parameter on the server side to allow only approved URLs and thus avoid open redirect attacks;
  • Always try to make the exchange with code, instead of getting the token directly (avoid “response_type=token”);
  • Use the “state” parameter with a random hash to prevent CSRF attacks in the OAuth authentication process;
  • Define and validate the scope for each application;
  • Always use secure communication, such as HTTPS, when transmitting OAuth2 tokens and authorization codes.

JSON Web Token (JWT)

The JWT standard defines how to transmit and store JSON objects between applications securely, simply, and in a compact form. It is an open standard documented in RFC-7519. Widely used in the validation of services in Web Services, for the advantages that we will see below, already highlighting the possibility of local validation.

Knowing the structure of JWT we see that it is a JSON structure composed of a Header, Payload, and Signature. 

Being digitally signed, JWT naturally guarantees the integrity issue. But it is worth remembering that if the data transmitted in the payload is sensitive, this will require implementing encryption in the payload to make it confidential.

More details about secure JSON Web token (JWT) implementation can be found in our blog.

JWT Advantages

That the JSON Web Token (JWT) is a compact and secure way to transmit requests, we already know. Now as advertised, let’s look at other advantages of secure API development of this signed encoding mechanism:

  • Because it is stateless, there is no need for session storage on the server;
  • Because it is compact, it can be transmitted in the HTTP header or as a query parameter;
  • Cross-domain compatibility. That is, it can be used in building decentralized cross-domain systems.

Threats to JWT

  • Store sensitive information in the payload;
  • Expiration time not configured;
  • Expiration time too high;
  • Use of weak algorithm for signature;
  • Lack of use of the other reserved claims of JWT;
  • Bug in some libraries;
  • The algorithm “None”;
  • Algorithm Change;
  • Entering an invalid signature;
  • Brute force on weak keys.

Examples of vulnerabilities:

  • JWT algorithm “None” allowed;
  • JWT signature not verified;
  • JWT validity not checked.

Security Best Practices for JWT

  • Restrict accepted algorithms;
  • Verify all tokens before processing payload data to prevent tampering and unauthorized access;
  • Store JWTs tokens securely, such as in secure HTTP-only cookies, avoiding access control failures;
  • Always sanitize data that the user can manipulate;
  • Implement rate-limiting to prevent brute-force and denial-of-service attacks.
  • Restrict URLs from any JWKS / X509 certificates;
  • Use the most robust signing process for which you can spare CPU time;
  • Use asymmetric keys if tokens are used on more than one server;
  • Use strong and unique keys to sign JWTs and protect against brute force attacks;
  • Have a short expiration time, which decreases attackers’ time and prevents reuse;
  • Always try to use the latest version of the JWT library you choose, and perform a search for possible CVEs to verify that the version you use has no publicly known vulnerabilities;
  • Use secure protocols like HTTPS to avoid eavesdropping and man-in-the-middle attacks.

JWT is a widely used and convenient way to authenticate and authorize users in RESTful APIs. To ensure JWT security, it is important to follow best practices, such as using strong secret keys, verifying signatures, and storing tokens securely. By taking the necessary security precautions, you can reduce the risk of security incidents and protect your APIs and the sensitive data that they handle.

Conclusion

Taking care of secure API development brings with it a series of precautions that include the use of security protocols and best practices. OAuth2 should be properly implemented to reduce security risks. And the JSON Web Token (JWT) can be used for authentication and authorization, but it must be protected with strong secret keys, verified signatures, and stored securely.

Nova call to action
About author

Articles

Professional in the technology area for over 16 years. A technologist from ETE, a bachelor's degree in Systems Analysis and Information Technology from Fatec, and a postgraduate (MBA) in Management and Governance of Information Technology by FIAP. Throughout his career, he has developed several systems, in different market technologies, both web and mobile, and participated in all cycles of the reformulation project of the 'Customer Mobile App' of Liberty Seguros SA, winner in the category Insurance Application of the "eFinance 2017 Award", one of the primary technology awards for the finance area. He acts as a squad leader in the Consulting team taking the AppSec culture to customers.
Related posts
Application SecurityCode Fighters

How to integrate Semgrep on CI/CD's and send findings to Conviso Platform

Nowadays a very common practice is to integrate security scans during the continuous integration and…
Read more
Application Security

Negative Impacts Generated by Lack of Logs and Security Monitoring

Logs are records of activities also generated by systems, applications, and network devices. They…
Read more
Application Security

Dockers and Containers

Containers are incredibly popular solutions in the software development industry. They provide an…
Read more

Deixe um comentário