OAuth 2 Server

Now that you’ve seen how the OAuth 1 process works, you may have decided you want to provide access to your content using OAuth 2. Or perhaps you already knew you wanted to use OAuth 2 and jumped straight to this chapter, that’s just fine. In this chapter, we’re going to look at the finer points of implementing an OAuth 2 server to serve your content. This section includes a bit on authorization, as well as authentication and the different types of grants you may want to support.

In the OAuth 1 Server chapter, you’ll remember we had to break down and reconstruct the signature in order to authenticate the user. The good news for OAuth 2.0 is that the signature goes away completely, getting the information needed to authenticate a user is much easier. We also have a better framework for handling authorization to certain resources, which will come in handy.

SSL/TLS

So before we get into a lot of the technical details, OAuth 2 requires you communicate to the server securely. This means, as a server provider, you are going to need Transport Layer Security (TLS) or Secure Sockets Layer (SSL) to encrypt and protect the requests that are made to the server. This means that as a service provider, you are going to be responsible for obtaining and maintaining the certificates your server needs to ensure the sensitive data in incoming requests is properly encrypted and your web servers are configured to use only HTTPS for OAuth requests.

It is important to note the use of TLS/SSL is not optional according to the OAuth 2 specification, as it acts as a cryptographic alternative to signed requests. Since we’re dealing with fewer tokens, the tokens we are using need to be handled with care and caution. More on the tokens later, the importance of this section is that you understand and can start planning for the requirement of using TLS/SSL for your OAuth 2 driven service.

Tokens and Grants

The main concept in both versions of OAuth is that a user is able to authenticate with a service and obtain an identifier which allows them to communicate with the API in a way that hides or doesn’t use their user name and password. By eliminating the need to send the user name and password in each request, OAuth helps protect the credentials for the service from being hijacked from a request. Instead, OAuth uses identifiers known as tokens which can easily be regenerated and revoked in the event they are compromised. This process is a great deal more convenient than having to reset a user name and password.

In OAuth 1, these tokens are combined into a hashed signature which can be recreated to verify the identity of the user. In OAuth 2, because of the TLS/SSL requirement, the tokens are provided with the requests which makes the formation of the requests much easier to understand. This method also eliminates the need to have an access token and an access secret, favoring the access token. As a result, the implementation of an OAuth 2 server is easier to understand.

If you are using a library, there is likely already a method for generating the access token; if you can use a library method you should. If you are writing your own implementation, you need to determine the length (in characters) of the access token you generate. You also need to make sure each access token which is generated is unique from any active access tokens. Similar to how we created the nonce in OAuth 1 clients, we can create a random string like this:

$bytes = openssl_random_pseudo_bytes(20);
$token = bin2hex($bytes);

The previous code will create a hexadecimal representation of the random bytes and generate a token which is 40 characters long.

Authorization Code Grant

The first grant we are going to take a look at is the Authorization Code Grant. As the name implies, there is an authorization code which is required in order to successfully implement this grant. In order to use this grant in your server, the user will need to authenticate with your service. This usually means the user is redirected to a URL belonging to your application which allows them to authenticate and authorize the calling application. Once this happens, an authorization code needs to be generated and associated with the authenticating user. In addition to creating this authorization code and making the proper association, it’s also important this token not be allowed to be valid for a long period of time. It needs to expire after a set amount of time; this can vary, but ideally a couple of minutes should be plenty of time for the user to take the next step.

Once the user has authenticated and has been redirected back to the redirect URL from the calling application, a second request has to be made. This request serves as the primary way to obtain an access token. The user will make a request for the access token by passing along the client key, client secret, Authorization Code, and the redirect URI. If everything matches and the Authorization Code has not expired, an access token is returned. In order to return one, a token needs to be created and associated with the correct user account. The access token is the primary mechanism for identifying a user. Optionally, you can choose to also return a refresh token, which will allow the user to easily recreate any token which has expired. It’s important to allow the access tokens to expire after an amount of time that seems reasonable for your application and use case.

By requiring an authorization code, you are ensuring a user takes multiple steps to verify themselves to your application. This grant type should be used whenever possible, as the additional request naturally provides a layer of security and ensures requests were not hijacked and modified prior to the tokens being assigned.

Implicit Grant

The Implicit Grant provides an easy way of obtaining the access token by sending the token immediately after the user authenticates with your service. By not requiring the user to send an authorization code back to your server, access tokens can be very easily obtained by users who may not have the ability to generate a second request. This grant can be particularly useful in applications built solely with JavaScript. It’s important to communicate to users the use cases where using the Implicit Grant may be advantageous.

Because there is no authorization code, the second level of verification is obviously removed. This is why having short-lived tokens is a smart strategy to employ and why this grant should only be used when the Authorization Code Grant is impermissible or overly difficult to implement. I strongly urge you to properly communicate via documentation and other necessary means the proper utilization of this grant. I’d even go a step further and indicate use of this grant should not be used as a shortcut to the Authorization Code Grant.

Ensuring you are properly deactivating tokens and taking other security precautions is an important step to ensure user data in your application remains secure and unmolested. There is a greater threat of theft when the user is not required to verify the receipt of non-access token information. While you certainly can’t prevent users from misusing anything in your application, communicating clearly is your responsibility to anyone who may be using your API for their application.

Client Credential Grant

The Client Credential Grant is a grant which allows a user to authenticate to the service by providing the consumer key and secret via Basic authentication. In this grant, there really isn’t a user to identify. As a result, it is important any user-related read/writes are sufficiently protected and the operations the API can perform are kept to a minimum.

In addition to keeping these permissions to a limited number of well defined operations, it’s very important this grant be used when there is a high level of trust between the client and the server. This grant can be used on internal systems because the trust level is extremely high. When providing this grant type to the world at large, it’s important to understand everything this application is capable of modifying and/or running. If, when providing this API, you find there are areas of the application which are unclear or jobs which may have unintended consequences ensure you obtain the knowledge of these jobs and requests prior to making this grant type available.

Resource Owner Credential Grant

The Resource Owner Credential Grant allows a user to provide their username and password combination, again via Basic auth, in exchange for an access token. This request will be associated with a user, so it is permissible for protected resources to be obtained, created, edited, or deleted. Because a username and password combination is set, it remains very important this is used only between systems with a high level of trust.

A compromised user account can be a very detrimental situation, both for the compromised user and the maintainer of the application. Passwords often need to be reset in multiple locations and credentials generally grant a larger number of acceptable operations. This token, along with the Client Credential Token should timeout after a reasonable amount of time for your application. Understanding the proper use cases and the technology behind this grant is very important if you are considering using or implementing it. While OAuth 2.0 takes steps to ensure there are multiple ways for users to retrieve access tokens, it is important to ensure the users can be sufficiently protected while they consume your service.

Refresh Token Grant

The Refresh Token Grant makes the process of obtaining new tokens much easier by providing a refresh token when the access token is obtained. Refresh tokens are not required. They are an optional part of the specification. If a refresh token is provided, it is very important it be properly protected and stored securely, by both clients and your application. If one is compromised it can allow an unauthorized user to generate new access tokens on behalf of another user.

As we’ve discussed, OAuth 2 access tokens tend to be shorter lived than their OAuth 1 counterparts. By encouraging short-life tokens, security improves but usability can suffer if considerations for expired tokens are not made carefully. When an access token expires, a user can send their refresh token to an endpoint which will exchange it for a new access token. In the event a refresh token is not part of the authorization flow, the user will have to authenticate with the third-party service again in order to obtain a new access token.

Access Control

When implementing any sort of server housing protected resources, authentication and authorization are vital to ensure the information is protected in the proper way. This could be, but is not necessarily limited to, ensuring users can only create, update, or delete data they have access to and ensuring users can only see data they’re supposed to see. It also is vital in ensuring non-administrative users do not have access to administrative tools on the application itself. It’s a problem everyone who’s ever written an application has to face, and let’s be frank, it’s generally not a whole lot of fun.

OAuth 2.0 doesn’t solve these problems directly. It’s really important to understand every application is different and will have different requirements for protected resources. What this ultimately means is as an application creator, you are still responsible for maintaining the proper permissions and requirements when it comes to creating or dealing with these protected resources. While OAuth 2 doesn’t directly handle this for you, there is a concept that was introduced in OAuth 2.0 that provides a jumping off point for implementing this idea. This concept is referred to as Scopes.

Scopes

Scopes provide a way for an application to identify the types of resources they’ll be interacting with and the type of the access they will need to use those resources. These really only come into play with protected resources, as public resources can be handled by the API itself. Take for instance a service like Twitter, while the public time line could be accessible by anyone, they would certainly want to restrict the ability for someone to create a tweet under a certain account. The same goes for GitHub’s gists and a number of other applications.

In OAuth 1.0, if you wanted to restrict the ability to create tweets from the API, you would have to set the entire application to read-only. It would also restrict the ability to create direct messages, which may or may not be what you need to do. If you want to allow the creation of direct messages, you would also have to allow the creation of tweets. This process really limits the amount of control a user has when creating a client application and potentially opens up to their application to being used in a way it wasn’t intended.

Scopes allow application developers to drill down into specific resource types and set the access requirements for those types individually. Where Twitter, which uses OAuth 1.0, only allows you to set an application to read-all or write-all, GitHub can allow you to toggle read and write access to specific resources. This type of access can be requested at the time the access tokens are requested, and allows an access token to be set and properly associated with these scopes to ensure the permissions are not lost.

Scope Implementation

As I mentioned before, the work of actually enforcing these scopes still falls on the creator of the service. In an overly simplified view, the client is going to make requests to the server. It’s the server’s job to know whether the request is allowed, authorized, and should be fulfilled. If the client makes a request to a resource not in the list of allowable scopes, the request should be denied, with the appropriate response and status codes. It’d be improper–and frankly confusing–if the limitations and control scopes provide were to be ignored or not implemented consistently.

If you are writing a service using OAuth 2.0, an important part of planning your service will be to to know and define:

  • the different types of resources available to your users,
  • whether or not those resources are regarded as public or protected.

Applications are as unique and diverse as the people that write them, so it is impossible to suggest a one-size-fits-all approach. Access Control can be very difficult and mistakes in this area tend to be very costly and damaging to the reputation and credibility of an application. Scopes can be a very handy way to define the protected resources in your API or application and to ensure all the use cases for interacting with them are covered correctly and responsibly.

Conclusion

We’ve been able to look at some key components of an OAuth 2.0 server in depth, how the server works, and some of the differences between OAuth 1 and OAuth 2. Understanding the technology and process involved allows application and service creators to make informed decisions about the protocols and technologies they may want to use in their applications. As we’ve seen throughout the book, there are definitely differences between the OAuth versions from both the client and server side. By breaking down the walls of confusion, and understanding the process in simpler terms, we’re able to provide solutions to common problems in a concise, separated manner.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.253.170