OAuth 2 and JWT - How to design a secure API?

OAuth 2 and JWT - How to design a secure API?

Translated by Moakap, the original  OAuth 2 VS JSON Web Tokens: How to secure an API

This article will detail two common approaches to securing APIs: OAuth2 and JSON Web Token (JWT)

Suppose:

  • you have implemented or are implementing an API;
  • You are considering choosing an appropriate method to secure your API;

JWT and OAuth2 comparison?

Want to compare JWT and OAuth2? The first thing to understand is that these two are not comparable at all, they are two completely different things.

  • JWT is an authentication protocol. 
    JWT provides a method for issuing an access token (Access Token) and verifying the issued signed access token. The token itself contains a series of claims, according to which the application can restrict the user's access to the resource.

  • OAuth2 is an authorization framework 
    On the other hand, OAuth2 is an authorization framework that provides a detailed set of authorization mechanisms (guidance). Users or applications can authorize third-party applications to access specific resources through public or private settings.

Since JWT and OAuth2 are not comparable, why put these two together? In practice, many people do compare JWT and OAuth2. Putting these two together in the title is indeed misleading. In many cases, when discussing the implementation of OAuth2, JSON Web Token is used as an authentication mechanism. That's why they often appear together.

Let's first find out what JWT and OAuth2 are doing~

JSON Web Token (JWT)

JWT is defined in the standard as follows:

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS). 
- RFC7519 https://tools.ietf.org/html/rfc7519

JWT is a security standard. The basic idea is that the user provides the user name and password to the authentication server, and the server verifies the legitimacy of the information submitted by the user; if the verification is successful, a Token (token) will be generated and returned, and the user can use this token to access protected resources on the server.

An example of a token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
  • 1

A token consists of three parts:

header.claims.signature

All parts are base64 URL-safe encoded for safe use in urls.

Header header part

The header simply declares the type (JWT) and the algorithm used to generate the signature.

{
  "alg" : "AES256",
  "typ" : "JWT" }
  • 1
  • 2
  • 3
  • 4

Claims

The claims part is the core of the whole token and represents the user details to be sent. In some cases, we are likely to implement authentication on one server and then access resources on another server; or, through a separate interface to generate a token, the token is stored in the application client (such as a browser) for use. 
An example of a simple claim:

{
  "sub": "1234567890",
  "name": "John Doe", "admin": true }
  • 1
  • 2
  • 3
  • 4
  • 5

Signature

The purpose of the signature is to ensure that the above two parts of information are not tampered with. If you try to use Bas64 to modify the decoded token, the signature information will be invalid. Generally, a private key is used to obfuscate Header and Claims through a specific algorithm to generate signature information, so only the original token can match the signature information.

There is an important implementation detail here. Only applications (such as server-side applications) that have obtained the private key can fully authenticate the legitimacy of the token containing the claim information. So, never put private key information on the client (such as browser).

What is OAuth2?

In contrast, OAuth2 is not a standard protocol, but a secure authorization framework. It describes in detail how to implement mutual authentication between different roles, users, service front-end applications (such as API), and clients (such as websites or mobile apps) in the system.

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf. 
- RFC6749 https://tools.ietf.org/html/rfc6749

Here is a brief description of the basic concepts involved.

Roles

An application or user can be any of the following roles:

  • resource owner
  • resource server
  • client application
  • Authentication server

Client TypesClient Types

The client here mainly refers to the user of the API. Types it can be:

  • private
  • public

Client Profile client description

The OAuth2 framework also specifies a centralized client description to represent the type of application:

  • web application
  • user agent
  • Acoustic application

Authorization GrantsAuthentication and authorization

Authentication authorization represents a set of permissions authorized by the resource owner to the client application, which can be in the following forms:

  • Authorization code
  • Implicit Grant
  • Resource owner password certificate
  • client certificate

Endpoints terminal

The OAuth2 framework requires the following terminals:

  • Authentication terminal
  • Token terminal
  • redirect terminal

As you should see from the above, OAuth2 defines a fairly complex set of specifications.

Protect user passwords with HTTPS

Before further discussing the implementation of OAuth2 and JWT, it is necessary to say that both schemes require SSL security protection, that is, encrypting the data to be transmitted.

Secure transmission of user-provided private information is essential in any secure system. Otherwise, anyone can hack into the private wifi and steal the user's username and password when the user logs in.

Some Important Implementation Considerations

Before making your choice, consider the points mentioned below.

time investment

OAuth2 is a security framework that describes authorization issues between multiple applications in various scenarios. There is a huge amount of material to learn, and it takes a lot of time to fully understand. Even for some experienced developers, it will take about a month to deeply understand OAuth2. This is a big time investment.

On the contrary, JWT is a relatively lightweight concept. It might take a day to study the standard specification in depth, and you can easily start implementing it.

risk of error

OAuth2 is not a strictly standard protocol like JWT, so it is more error-prone during implementation. Although there are many existing libraries, each has a different maturity level, and it is also easy to introduce various bugs. It is also easy to find some security holes in commonly used libraries.

Of course, if there is a fairly mature and strong development team to continuously implement and maintain OAuth2, these risks can be completely avoided.

Benefits of Social Login

In many cases, it is convenient to use the user's existing account on a large social networking site for authentication.

If you expect your users to be able to use accounts like Facebook or Gmail directly, it's much more convenient to use an existing library.

in conclusion

Before drawing conclusions, let's list the main usage scenarios of JWT and OAuth2.

JWT usage scenarios

Stateless Distributed API

The main advantage of JWT is that it uses a stateless, scalable way to handle user sessions in an application. The server can easily obtain the user's session information through the embedded declaration information without accessing the user or session database. In a distributed service-oriented framework, this is very useful.

However, if the system needs to use a blacklist to implement a long-term effective token refresh mechanism, this stateless advantage is not obvious.

Advantage

  • rapid development
  • no cookie required
  • Widespread use of JSON on mobile
  • Does not depend on social login
  • Relatively simple conceptual understanding

limit

  • Token has a length limit
  • Token cannot be revoked
  • Requires the token to have an expiration time limit (exp)

OAuth2 usage scenarios

In the author's opinion, there are two scenarios where it is necessary to use OAuth2:

Outsourced Authentication Server

As discussed above, if you don't mind that API usage depends on an external third-party authentication provider, you can simply leave the authentication to the authentication service provider. 
That is, it is common to go to the authentication service provider (such as facebook) to register your application, and then set the user information that needs to be accessed, such as email address, name, etc. When users visit the registration page of the site, they see a portal to connect to the third-party provider. After the user clicks, they are redirected to the corresponding authentication service provider website. After obtaining the authorization of the user, they can access the required information and then redirect back.

Advantage

  • rapid development
  • Small amount of code to implement
  • Maintenance work is reduced

Large Enterprise Solutions

If the API is designed to be used by different apps, and each app uses it in different ways, using OAuth2 is a good choice.

Considering the workload, separate teams may be required to develop sophisticated and flexible security policies for various applications. Of course it takes a lot of work! This point, the author of OAuth2 also pointed out:

To be clear, OAuth 2.0 at the hand of a developer with deep understanding of web security will likely result is a secure implementation. However, at the hands of most developers – as has been the experience from the past two years – 2.0 is likely to produce insecure implementations.


hueniverse - OAuth 2.0 and the Road to Hell

Advantage

  • flexible implementation
  • Can be used concurrently with JWT
  • Scalable for different applications

further

  • http://jwt.io  - JWT official website, you can also check the status of libraries implemented in different languages.
  • http://oauth.net/2/  OAuth2 official website, you can also check the status of libraries implemented in different languages.
  • OAuth 2 tutorials - Useful overview of how OAuth 2 works
  • Oauth2 Spec issues Eran Hammer’s (推进OAuth标准的作者) views on what went wrong with the OAuth 2 spec process. Whatever your own opinion, good to get some framing by someone who understand’s key aspects of what make a security standard successful.
  • Thoery and implemnetation: with Laravel and Angular Really informative guide to JWT in theory and in practice for Laravel and Angular.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325331116&siteId=291194637