Library for OAuth Provider (Java)

Viewed 54643

I'm looking for a Java library that helps me building an OAuth Provider. I must be able to receive OAuth signed requests and determine whether they are valid or not (checking the signature, timestamp and nonce values).

Do you know if there's something out there that makes this task easier?

6 Answers

Scribe is an OAuth library for Java, written by the asker himself. ;-)

Note: I post this here as an answer so that other googlers have a choice of alternatives. For another library-based alternative, see my other answer "Jersey OAuth signature library".

Some code to illustrate usage:

OAuthService service = new ServiceBuilder()
                                  .provider(TwitterApi.class)
                                  .apiKey("your_api_key")
                                  .apiSecret("your_api_secret")
                                  .build();
...
Token requestToken = service.getRequestToken();
String your_token = requestToken.getToken();
...
Verifier verifier = new Verifier("your_previously_retrieved_verifier");
 Token accessToken = service.getAccessToken(requestToken, verifier);

Creating the request:

OAuthRequest request = OAuthRequest(Verb.GET, "http://api.twitter.com/1/direct_messages.json");
service.signRequest(accessToken, request);
Response response = request.send();

You can use the Jersey OAuth Signature Library.

Simple OAuth authentication for a servlet or filter may be set up using a Container Filter, which filters the request before the request is matched and dispatched to a root resource class. The Container Filter is registered using initialization parameters which point to a user defined class, such as the following:

public class OAuthAuthenticationFilter implements ContainerRequestFilter {
    @Override
    public ContainerRequest filter(ContainerRequest containerRequest) {
        // Read the OAuth parameters from the request
        OAuthServerRequest request = new OAuthServerRequest(containerRequest);
        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);

        // Set the secret(s), against which we will verify the request
        OAuthSecrets secrets = new OAuthSecrets();
        // ... secret setting code ...

        // Check that the timestamp has not expired
        String timestampStr = params.getTimestamp();
        // ... timestamp checking code ...

        // Verify the signature
        try {
            if(!OAuthSignature.verify(request, params, secrets)) {
                throw new WebApplicationException(401);
            }
        } catch (OAuthSignatureException e) {
            throw new WebApplicationException(e, 401);
        }

        // Return the request
        return containerRequest;
    }
}
Related