开发者

Authentication and authorization for RESTfull API (java jersery)

implementing service something similar with tinyurl or bit.ly, I'm would like to expose service as API, I'm using java and jersey as RESTfull service implementation.

I'm looking for simplest way for authentification of users who use API, OAuth is first thing co开发者_JAVA百科ming in mind, but the problem is I don't need this 3 iteration calls with request token query, than access token query with callback url passing. I just need to give user ability to invoke api with no additional security calls to my server.


Thanks to patrickmcgraw comment I used 2-legged oauth authentificaton. Here is some java code.

For client side (using Jersey api):

OAuthParameters params = new OAuthParameters().signatureMethod("HMAC-SHA1").
    consumerKey("consumerKey").version("1.1");

OAuthSecrets secrets = new OAuthSecrets().consumerSecret("secretKey");
OAuthClientFilter filter = new OAuthClientFilter(client().getProviders(), params, secrets);


WebResource webResource = resource();
webResource.addFilter(filter);

String responseMsg = webResource.path("oauth").get(String.class);

On provider side:

@Path("oauth")
public class OAuthService {
    @GET
    @Produces("text/html")
    public String secretService(@Context HttpContext httpContext) {
        OAuthServerRequest request = new OAuthServerRequest(httpContext.getRequest());

        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret("secretKey");

        try {
            if(!OAuthSignature.verify(request, params, secrets)) 
                return "false";
        } catch (OAuthSignatureException ose) {
            return "false";
        }

        return "OK";
    }
}

Here is code for PHP client:

<?php 

require_once 'oauth.php';

$key = 'consumerKey';
$secret = 'secretKey';
$consumer = new OAuthConsumer($key, $secret);

$api_endpoint = 'http://localhost:9998/oauth';
$sig_method = new OAuthSignatureMethod_HMAC_SHA1;

$parameters = null;
$req = OAuthRequest::from_consumer_and_token($consumer, null, "GET", $api_endpoint, $parameters);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req->sign_request($sig_method, $consumer, null);//note: double entry of token

//get data using signed url
$ch = curl_init($req->to_url());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);

echo $res;
curl_close($ch);


if youre using http at the transport layer you can always use basic http authentication

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜