Documentation

You are viewing the documentation for the 2.3.x release series. The latest stable release series is 3.0.x.

§OAuth

OAuth is a simple way to publish and interact with protected data. It’s also a safer and more secure way for people to give you access. For example, it can be used to access your users’ data on Twitter.

There are 2 very different versions of OAuth: OAuth 1.0 and OAuth 2.0. Version 2 is simple enough to be implemented easily without library or helpers, so Play only provides support for OAuth 1.0.

§Usage

To use OAuth, first add javaWs to your build.sbt file:

libraryDependencies ++= Seq(
  javaWs
)

§Required Information

OAuth requires you to register your application to the service provider. Make sure to check the callback URL that you provide, because the service provider may reject your calls if they don’t match. When working locally, you can use /etc/hosts to fake a domain on your local machine.

The service provider will give you:

§Authentication Flow

Most of the flow will be done by the Play library.

  1. Get a request token from the server (in a server-to-server call)
  2. Redirect the user to the service provider, where he will grant your application rights to use his data
  3. The service provider will redirect the user back, giving you a /verifier/
  4. With that verifier, exchange the /request token/ for an /access token/ (server-to-server call)

Now the /access token/ can be passed to any call to access protected data.

§Example

conf/routes:

GET     /twitter/homeTimeline controllers.Twitter.homeTimeline()
GET     /twitter/auth         controllers.Twitter.auth()

controller:

import play.libs.F.Function;
import play.libs.F.Option;
import play.libs.F.Promise;
import play.libs.oauth.OAuth;
import play.libs.oauth.OAuth.ConsumerKey;
import play.libs.oauth.OAuth.OAuthCalculator;
import play.libs.oauth.OAuth.RequestToken;
import play.libs.oauth.OAuth.ServiceInfo;
import play.libs.ws.WS;
import play.libs.ws.WSResponse;
import play.mvc.Controller;
import play.mvc.Result;

import com.google.common.base.Strings;

public class Twitter extends Controller {
  static final ConsumerKey KEY = new ConsumerKey("...", "...");

  private static final ServiceInfo SERVICE_INFO = new ServiceInfo("https://api.twitter.com/oauth/request_token",
                                                                  "https://api.twitter.com/oauth/access_token",
                                                                  "https://api.twitter.com/oauth/authorize", 
                                                                  KEY);
  
  private static final OAuth TWITTER = new OAuth(SERVICE_INFO);
  
  public static Promise<Result> homeTimeline() {
    Option<RequestToken> sessionTokenPair = Twitter.getSessionTokenPair();
    if (sessionTokenPair.isDefined()) {
      return WS.url("https://api.twitter.com/1.1/statuses/home_timeline.json")
          .sign(new OAuthCalculator(Twitter.KEY, sessionTokenPair.get()))
          .get()
          .map(new Function<WSResponse, Result>(){
            @Override
            public Result apply(WSResponse result) throws Throwable {
              return ok(result.asJson());
            }
       });
    }
    return Promise.pure(redirect(routes.Twitter.auth()));
  }
  
  public static Result auth() {
    String verifier = request().getQueryString("oauth_verifier");
    if (Strings.isNullOrEmpty(verifier)) {
      String url = routes.Twitter.auth().absoluteURL(request());
      RequestToken requestToken = TWITTER.retrieveRequestToken(url);
      saveSessionTokenPair(requestToken);
      return redirect(TWITTER.redirectUrl(requestToken.token));
    } else {
      RequestToken requestToken = getSessionTokenPair().get();
      RequestToken accessToken = TWITTER.retrieveAccessToken(requestToken, verifier);
      saveSessionTokenPair(accessToken);
      return redirect(routes.Twitter.homeTimeline());
    }
  }

  private static void saveSessionTokenPair(RequestToken requestToken) {
    session("token", requestToken.token);
    session("secret", requestToken.secret);
  }

  private static Option<RequestToken> getSessionTokenPair() {
    if (session().containsKey("token")) {
      return Option.Some(new RequestToken(session("token"), session("secret")));
    }
    return Option.None();
  }
  
}

Next: Integrating with Akka


Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines, please feel free to contribute a pull request. Have questions or advice to share? Go to our community forums to start a conversation with the community.