Simple OAuth Client and Server Examples

Wednesday, January 14, 2009

Simple OAuth Client and Server Examples

The OAuth Google code ( http://code.google.com/p/oauth/) is woefully undocumented, so I put together below a zeroeth order approximation to how things actually work. To use this, you need both the Open Social Java implementation (for the client) and the OAuth Java implementation. Check them both out from the Google Code SVNs as described in earlier posts.

In the examples below, we will use OAuth's two-legged authentication. This is the server-to-server authentication used by OpenSocial gadgets. It is appropriate when no human intervention is needed (or is possible) in the authentication process. Also, we are going to just look at shared secret key-style authentication, using the HMAC-SH1 algorithm and symmetric key encryption. The OAuth code will also support public/private asymmetric keys.

Finally, note that the steps for generating the OAuth consumer key and consumer secret are out of scope. We will just use the key and secret from the earlier OpenSocial gadget experiments. Generally, shared secrets will need to be communicated through a separate registration process. Presumably, the server would use the consumer key sent by the client to look up the secret key on the server side from a database, but check the OAuth specification for details.

Server Code
We'll implement a dummy server as a JSP. You can put this in an Apache Tomcat server under a webapp called OAuthTest. You will also need to put several jars in webapp/OAuthTest/WEB-INF/lib:

ls apache-tomcat-5.5.27/webapps/OAuthTest/WEB-INF/lib/
commons-codec-1.3.jar jetty-6.1.11.jar
commons-httpclient-3.1.jar jetty-util-6.1.11.jar
commons-logging-1.1.jar junit.jar
httpclient-4.0-beta1.jar oauth-core-20090108.jar
httpcore-4.0-beta2.jar

The above jars are all from OAuth/java/lib, plus the oauth-core jar that you generated when you compiled things (see previous post--use "mvn clean install").

Here at last is the actual JSP for the dummy service. I call this OAuthTest.jsp.

--------------------

<%
//Presumably this should actually be looked up for a given key.  Use a real key.
String consumerSecret="123121212yourkeyhere18918";

//Presumably the key is sent by the client. This is part of the URL, after all.  Use a real key.
String consumerKey="orkut.com:1231212122";

//Construct the message object. Use null for the URL and let the code construct it.
OAuthMessage message=OAuthServlet.getMessage(request,null);

//Construct an accessor and a consumer
OAuthConsumer consumer=new OAuthConsumer(null, consumerKey, consumerSecret, null);
OAuthAccessor accessor=new OAuthAccessor(consumer);

//Now validate. Weirdly, validator has a void return type. It throws exceptions
//if there are problems.
SimpleOAuthValidator validator=new SimpleOAuthValidator();
validator.validateMessage(message,accessor);

//Now what? Generate some JSON here for example.
System.out.println("It must have worked"); %>


-------------------

Client Code

To build an OAuth client, we can start from our earlier OpenSocial client. For convenience, we will leave in the OpenSocialUrl and OpenSocialHttpRequest classes, which help construct and execute the REST invocation, but one could easily eliminate this and use the standard java.net classes that underly these two.

Here's the client code. Save it in a file called MyOAuthClient.java in OpenSocial's java/samples directory.
---------------------
import org.opensocial.data.*;
import org.opensocial.client.*;
import net.oauth.*;
import java.util.*;

public class MyOAuthClient {

public static void main(String[] args) {
MyOAuthClient mosc=new MyOAuthClient();
}

public MyOAuthClient() {
String REST_BASE_URI=
"http://localhost:8080/OAuthTest/OAuthTest.jsp";
String CONSUMER_SECRET=
"uynAeXiWTisflWX99KU1D2q5";
String CONSUMER_KEY=
"orkut.com:623061448914";
// String VIEWER_ID=
// "03067092798963641994";
String VIEWER_ID="08354253340777199997";

try {
OpenSocialUrl requestUrl = new OpenSocialUrl(REST_BASE_URI);
OpenSocialHttpRequest request=new OpenSocialHttpRequest(requestUrl);
requestUrl.addQueryStringParameter("xoauth_requestor_id", VIEWER_ID);
requestUrl.addQueryStringParameter("st", "");

String requestMethod=request.getMethod();
String postBody = request.getPostBody();

OAuthMessage message =
new OAuthMessage(requestMethod, requestUrl.toString(), null);

OAuthConsumer consumer =
new OAuthConsumer(null, CONSUMER_KEY, CONSUMER_SECRET, null);
consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);

OAuthAccessor accessor = new OAuthAccessor(consumer);
accessor.accessToken = "";
message.addRequiredParameters(accessor);

for (Map.Entry p : message.getParameters()) {
if (!p.getKey().equals(postBody)) {
requestUrl.addQueryStringParameter(
OAuth.percentEncode(p.getKey()),
OAuth.percentEncode(p.getValue()));
}
}

//Take a look at the signed URL
System.out.println("Signed REST URL: "+requestUrl.toString());

//Done with signing. Now back to OpenSocialBatch's submitRest()
//Finally, get the response. This is the meat of the getHttpResponse
//method, without the error checking.
request.execute();
}

catch(Exception ex) {
ex.printStackTrace();
}
}
}
------------------
Compile this from the OpenSocial SVN checkout's java directory with the command ant compile-samples.

Now set your classpath and execute. The following UNIX commands will do the trick:
export CP=`echo $HOME/opensocial-java-client-read-only/java/lib/*.jar | tr ' ' ':'`

export CP=`echo $HOME/opensocial-java-client-read-only/java/dist/*.jar | tr ' ' ':'`:$CP


java -classpath $CP:/Users/marlonpierce/opensocial-java-client-read-only/java/samples/bin/ MyOAuthClient


Check the output of your Tomcat server's catalina.out to see if it worked.

Obviously this has all been a simple exercise to see how to get things going and needs a lot of work to make it a real service.
基于粒子群优化算法的p-Hub选址优化(Matlab代码实现)内容概要:本文介绍了基于粒子群优化算法(PSO)的p-Hub选址优化问题的研究与实现,重点利用Matlab进行算法编程和仿真。p-Hub选址是物流与交通网络中的关键问题,旨在通过确定最优的枢纽节点位置和非枢纽节点的分配方式,最小化网络总成本。文章详细阐述了粒子群算法的基本原理及其在解决组合优化问题中的适应性改进,结合p-Hub中转网络的特点构建数学模型,并通过Matlab代码实现算法流程,包括初始化、适应度计算、粒子更新与收敛判断等环节。同时可能涉及对算法参数设置、收敛性能及不同规模案例的仿真结果分析,以验证方法的有效性和鲁棒性。; 适合人群:具备一定Matlab编程基础和优化算法理论知识的高校研究生、科研人员及从事物流网络规划、交通系统设计等相关领域的工程技术人员。; 使用场景及目标:①解决物流、航空、通信等网络中的枢纽选址与路径优化问题;②学习并掌握粒子群算法在复杂组合优化问题中的建模与实现方法;③为相关科研项目或实际工程应用提供算法支持与代码参考。; 阅读建议:建议读者结合Matlab代码逐段理解算法实现逻辑,重点关注目标函数建模、粒子编码方式及约束处理策略,并尝试调整参数或拓展模型以加深对算法性能的理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值