Sneha S
Sneha S

Reputation: 288

Java Method to receive the request and generate Oauth Signature

I want to write a java method which will receive request containing Authorization header and will generate an Oauth Signature using HMAC-SHA1 and send it as a response. I would like to know how i can implement this?

I hope that the method should obtain the signature base string from request and generate signature using algorithm. Correct me if i am wrong or if there are any other approaches to obtain similar output.

Upvotes: 2

Views: 4575

Answers (1)

Ripu Daman Bhadoria
Ripu Daman Bhadoria

Reputation: 2572

This question is not correct in some ways as "Authorization header" will have signature inside it. If you want to verify the oauth request then you will verify the consumer key first then generate the signature using all other fields and the secret which will be stored at your end and verify it against the signature which came in the "Authorization header".

However, if you want to sign the request then there are many open source libraries to do that. I am using Jersey's "oauth signature" library to sign the request.

public static String getOAuthHeader(final String url, final String method,
        final String realm, final String consumerSecret,
        final String consumerKey, final String callback,
        final String verifier, final String token,
        final String tokenSecret, final String host) {

    String oauthHeader = null;
    OAuthSecrets secrets = new OAuthSecrets()
            .consumerSecret(consumerSecret);
    OAuthParameters authParams = new OAuthParameters()
            .consumerKey(consumerKey).signatureMethod(HMAC_SHA1.NAME)
            .version(AuthenticationConstants.OAUTH_VERSION_10A)
            .realm(realm).nonce().timestamp();

    if (callback != null) {
        authParams = authParams.callback(callback);
    }

    if (verifier != null) {
        authParams = authParams.verifier(verifier);
    }

    if (token != null) {
        authParams = authParams.token(token);
    }

    if (tokenSecret != null) {
        secrets = secrets.tokenSecret(tokenSecret);
    }

    final OAuthRequestData request = new OAuthRequestData();
    request.setRequestMethod(method);
    request.setRequestURL(url);
    request.addHeaderValue(AuthenticationConstants.HOST_HEADER, host);

    try {

        OAuthSignature.sign(request, authParams, secrets);

        final List<String> header = request
                .getHeaderValues(OAuthParameters.AUTHORIZATION_HEADER);
        oauthHeader = header.get(0);
    } catch (final OAuthSignatureException oae) {
        //handle this exception
    }

    return oauthHeader;
}

Upvotes: 3

Related Questions