OAuth(1)Sample Con
sumer Implementation in JAVA
1. Some Co
ncepts of the OAuth
Service Prov
ider ------- Consumer ------ User
Consumer Key : the key for the consumer to the server provider
Consumer Secret: the password of the consumer key
Request Token: request
Access Token:
Token Secret:
The service provider ne
ed these parts:
a, 3 Service EndPoints:
get unauthorized request token;
get authorized request token;
get Access Token from authorized request token.
b, post fo
rm for loginning
c, manage the authorized things
The consumer need these parts:
a, get the customer key/customer secret
b, contact to the service provider via HTTP
2. Try the Sample Codes to learn this feature
download the java source code from here:
http://oauth.googlecode.com/svn/code/java/
Using maven to compile the old core part
>
cd D:\book\oauth\java\oauth\core-old
>
mvn install -DskipTests=
true
>cd D:\book\oauth\java\oauth\core
>mvn install -DskipTests=true
Copy and import the service provider project D:\book\oauth\java\oauth\
example\oauth-provider
The project name in eclipse is oauth-example-provider.
Copy and import the consumer provider project D:\book\oauth\java\oauth\example\webapp
The project name in eclipse is oauth-example-consumer.
Three URLs of the server side:
http://localhost:8080/oauth-provider/request_token
http://localhost:8080/oauth-provider/authorize
http://localhost:8080/oauth-provider/access_token
provider just use memory to store and get the key and password. It is very simple. we need to change them.
the consumer is a
lso very simple.
3. Try another example consumer
open the
git bash in the window console.
>cd /d/work
>git clone git://github.com/kaeppler/signpost.git
>cd signpost
>mvn install
take this java class as example
https://github.com/kaeppler/signpost-examples/blob/master/OAuthGoogleExample/src/GoogleMain.java
4. Modify the consumer base on a filter implementation from internet resources
The sample codes are in project easyoauthconsumer.
The most import part in consumer is this filter class OauthFilter.java:
package com.silly
cat.easyoauthconsumer.web;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.oauth.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class OauthFilter implements Filter {
private String IS_USER_AUTHORISED = "is_user_authori
sed";
private String USER_INFO = "oauth_user_info";
private String FORBIDDEN_PAGE = "403.jsp";
private OAuthProvider provider;
private OAuthConsumer consumer;
private String protectedResourceUrl;
@Override
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
ServletContext context = req.getSession().getServletContext();
String uri = req.getRequestURI();
if (uri.endsWith(FORBIDDEN_PAGE)) {
chain.doFilter(request, response);
return;
}
// check the request is authorized
HttpSession session = req.getSession();
Boolean isAuthorized = (Boolean) session
.getAttribute(IS_USER_AUTHORISED);
if (isAuthorized != null && Boolean.TRUE.equals(isAuthorized)) {
// only if the user is authorized
chain.doFilter(request, response);
return;
}
if (null == provider || null == consumer
|| null == protectedResourceUrl) {
// prepare the beans
WebApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(context);
provider = (OAuthProvider) ctx.getBean("provider");
consumer = (OAuthConsumer) ctx.getBean("consumer");
protectedResourceUrl = (String) ctx.getBean("protectedResourceUrl");
}
try {
String verifier = request.getParameter(OAuth.OAUTH_VERIFIER);
// oauth_verifier is not null, we get authorized from the server
if (verifier != null) {
//
set to true if we use oauth 1.0
provider.setOAuth10a(true);
// get AccessToken
provider.retrieveAccessToken(consumer, verifier);
// visit the resources once we get access token
String result = getFromCAS(protectedResourceUrl);
session.setAttribute(IS_USER_AUTHORISED, true);
session.setAttribute(USER_INFO, result);
chain.doFilter(request, response);
return;
} else {
String returnUrl = req.getRequestURL().toString();
String url = provider.retrieveRequestToken(consumer, returnUrl);
((HttpServletResponse) response).sendRedirect(url);
}
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
private String getFromCAS(String urlString)
throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException,
IOException {
URL url = new URL(urlString);
HttpURLConnection userRequest = (HttpURLConnection) url
.openConnection();
userRequest.setDoOutput(true);
consumer.sign(userRequest);
userRequest.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
userRequest.getInputStream()));
String inputLine;
StringBuffer result = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
System.out.print
ln(inputLine);
result.append(" " + inputLine);
}
return result.toString();
}
}
The spring configuration
file consumer-context.xml:
<bean id="provider" class="oauth.signpost.basic.DefaultOAuthProvider">
<constructor-arg index="0">
<!-- oauth requestToken -->
<value>http://localhost:8080/easyoauthprovider/request_token</value>
</constructor-arg>
<constructor-arg index="1">
<!-- oauth AcessToken-->
<value>http://localhost:8080/easyoauthprovider/access_token</value>
</constructor-arg>
<constructor-arg index="2">
<!-- oauth authorize-->
<value>http://localhost:8080/easyoauthprovider/authorize</value>
</constructor-arg>
</bean>
<!-- oauth resouce URLs-->
<bean id="protectedResourceUrl" class="java.lang.String" >
<constructor-arg>
<value>http://localhost:8080/easyoauthprovider/user</value>
</constructor-arg>
</bean>
<bean id="consumer" class="oauth.signpost.basic.DefaultOAuthConsumer">
<constructor-arg index="0">
<value>myKey</value>
</constructor-arg>
<constructor-arg index="1">
<value>mySecret</value>
</constructor-arg>
</bean>
Configure the filter and spring listener in web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:main-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>oauthFilter</filter-name>
<filter-class>com.sillycat.easyoauthconsumer.web.OauthFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-map
ping>
<filter-name>oauthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And all the jar packages are managed by ant ivy tool. ivy.xml:
<!-- commons -->
<dependency org="commons-logging" name="commons-logging" rev="1.1.1"/>
<dependency org="commons-httpclient" name="commons-httpclient" rev="3.0.1" />
<dependency org="commons-codec" name="commons-codec" rev="1.4" />
<!-- oauth jar -->
<dependency org="net/oauth" name="oauth" rev="20100601" />
<dependency org="net/oauth" name="oauth-provider" rev="20100601" />
<dependency org="net/oauth" name="oauth-consumer" rev="20100601" />
<dependency org="net/oauth" name="oauth-httpclient3" rev="20100601" />
<!-- log4j -->
<dependency org="log4j" name="log4j" rev="1.2.16" />
<!-- spring -->
<dependency org="org/springframework" name="spring-web" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-context" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-core" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-beans" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-asm" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-
expression" rev="3.0.5.RELEASE"/>
<!-- signpost -->
<dependency org="oauth/signpost" name="signpost-core" rev="1.2"/>
That is it. The sample consumer is ready.
refereces:
http://oauth.net/code/
http://dsb
joe.iteye.com/blog/1158233
http://www.ibm.com/developerworks/cn/java/j-lo-oauth/index.html
http://oauth.googlecode.com/svn/code/
https://github.com/kaeppler/signpost-examples
http://code.google.com/p/oauth-signpost/wiki/GettingStarted
https://github.com/kaeppler/signpost-examples/blob/master/OAuthGoogleExample/src/GoogleMain.java
http://spring-security-oauth.codehaus.org/tutorial.html
http://spring-security-oauth.codehaus.org/userguide.html
http://hueniverse.com/oauth/
http://hueniverse.com/oauth/guide/
http://hueniverse.com/2010/05/intro
ducing-oauth-2-0/