Oauth 2.0 Basic Understanding

Oauth 2.0 Basic Understanding

In the modern world of social media, each of us uses dozens of applications and websites every day. OAuth 2.0 identity provider is designed to simplify the authorization process and, as a result, make the lives of users easier and safer. The question arises — in which way?

What is Oauth 2.0?

Here we’ll try to have explained what is OAuth 2.0 protocol in simple words for every user. Let’s take a common situation: you open a website, choose which data provider and which particular account to use, give permission to use the data (if it’s necessary) and work further on behalf of the owner of this account. You do not recall the password, do not waste time on a boring registration — it all happens in a few clicks.

...Obviously, you need to have an account of this provider for the purpose.

The term «provider» presupposes a service which owns user data and provides third-party services (clients) with secure access to this data with the user’s consent. An application that wants to get user data is a client.

For example, let’s take the login/registration form on Aliexpress. In this case, the form contains a choice of several providers — Google, Facebook, Vkontakte, and Twitter.

You press «login via Facebook» or «login via Google», and you are redirected to the account selection page, then you select your account and that’s all — you are already logged in.

The OAuth 2.0 specification defines a delegation protocol that provides clients with secure access to the user resources on a service provider. Such an approach prevents the user from the necessity to enter his password out of the service provider: the whole process is curtailed to clicking the «I agree to provide access to ...» button. The idea is that having one secure account, the user can use it for identity verification on other services, without disclosing his password.

Unlike OpenID, OAuth 2.0 can also be used for authorization. That is, it allows us to provide the rights for the actions that the service client will be able to take on behalf of the account holder. After the authorization, the account owner may not participate in the process of taking actions at all. The ticket selling service, for instance, creates an event in the user calendar on his own, or a game posts a report on the next cup won on Facebook.

General OAuth 2.0 outline:

  1. The client requests authorization from the resource owner.
  2. The client receives an authorization grant.
  3. The client requests an access token through identity verification with the help of the authorization server and authorization grant provision.
  4. The authorization server verifies the client by checking the authorization grant and, if it’s valid, issues an access token and refresh token.
  5. The client requests a secure resource from the provider and authenticates by presenting the access token.
  6. The provider checks the access token and, if valid, serves the request.

Thus we can see that the final goal is to get access and refresh tokens. Then the client interacts with the data provider until the access token expires. Further on to access the provider data again, the client needs to use the refresh token and to send a request for a new pair of access/refresh tokens generating.

Why Do We Need A Refresh Token At All?

Let’s imagine a situation when someone has got your access token and gained access to secure data. That is why tokens have an expiration date. For an access token, it is usually small — from a few seconds to several days, for a refresh token — its longer. So, the attacker will have access to the data until the access token expires. Suppose that someone has also taken possession of the refresh token and used it earlier than you, obtaining a new access token in such a way. In this case, you cannot receive data from the provider, but to solve this problem, it will be enough to log out and log in again — and that’s all! All old tokens will become invalid or deleted (implementation dependent). After this procedure, you receive new access/refresh tokens and you can safely continue working, and the bad guy, with old tokens, is left in the lurch.

What Are OAuth 2.0 Advantages And Disadvantages?

The following advantages of Oauth 2.0 protocol should be mentioned specifically:

    • The access to the resources is realized via HTTP / HTTPS with the token indicated in the headers. This allows OAuth usage in almost any solutions: in mobile and desktop applications, on various sites, and even in browser plug-ins.
    • Capability to authorize a user.
    • Popularity — most companies use OAuth in their APIs.
    • Simplicity of implementation and a large amount of manuals and reference materials.
    • Availability of the ready-made solutions that can be changed to fit your needs.

The disadvantages:

    • There is no common format, as a result, each service requires its own implementation.
    • In the process of user verification, sometimes you have to make additional requests to get minimal user information. It can be solved with the help of jwt token, but not all services support it.
    • When a token is stolen, an attacker gains access to the secure data for a while. To minimize this risk a token with signature can be used.

OAuth 2.0 approach realization in php can be found in several popular bundles on GitHub:

Some Words About JWT

JSON Web Token is an open standard for tokens creation in json format. Such a token consists of three parts separated by periods: a header, a set of fields (payload) and a signature. The first two blocks are presented in json format and encoded additionally. There is one obligatory key for the header — alg, indicating the signature algorithm. The payload fieldset contains undefined pairs key/value. There are also optional reserved keys (read).

A signature can be generated using both symmetric encryption algorithms and asymmetric ones. More than that, there is a separate standard that describes the format of an encrypted JWT token.

Example

We have some SECRET_KEY, only the server and the application are aware of it — the client (receives it during the installation).

      $SECRET_KEY = "stFalcon";
        $header = '{"typ":"JWT","alg":"HS256"}';
        $payload = '{"sub":"1234567890","name":"alex","admin":true}';
        $unsignedToken = \sprintf("%s.%s", base64_encode($header), base64_encode($payload));
        $signature = hash_hmac('sha256', $unsignedToken, $SECRET_KEY);</p></ol>
     
     
        $tokenEncoded =  \sprintf("%s.%s.%s", base64_encode($header), base64_encode($payload), base64_encode($signature));

    As a result, we have a ready-made token:

    eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6ImFsZXgiLCJhZG1pbiI6dHJ1ZX0=.MTI5MGZmYTkwMGM2YmE0ODIzNGQ2ZGI4OGYxZTM2NGY5Y2VhYzExN2NiZGNjODA0YmNhN2NhNmM1ZWUzMDQ3NA==

    Now let’s check the token for validity:

       $tokenDecodedArr = explode('.', $tokenEncoded);  
     
        $externalHeader = $tokenDecodedArr[0];
        $externalPayload = $tokenDecodedArr[1];
        $externalSignature = $tokenDecodedArr[2];
     
        if ( base64_decode($externalSignature) === hash_hmac('sha256' , \sprintf("%s.%s", $externalHeader, $externalPayload), $SECRET_KEY) ) {
          echo 'matched';
        } else {
          echo 'don’t mathe';
        }

    Thus, we can check whether the signatures match each other, if they do, the JWT is valid, i.e. it came from a trusted source. If the signatures do not match, then something has gone wrong — perhaps this is a sign of a potential attack.

    As a result, using jwt we get an additional level of protection against our data theft and the ability to transfer a certain amount of information without additional requests.

    Conclusion

    Summarizing what is OAuth 2.0 authentication  —is a simple solution based on HTTP, which makes it possible to use it on almost any platform. The majority of big sites support it and it has good documentation. So if you have decided to use this protocol in your project, this is a good choice.