`
sillycat
  • 浏览: 2552805 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

OAuth(1)Sample Consumer Implementation in JAVA

阅读更多
OAuth(1)Sample Consumer Implementation in JAVA

1. Some Concepts of the OAuth
Service Provider -------   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 need these parts:
a, 3 Service EndPoints:
         get unauthorized request token;
         get authorized request token; 
         get Access Token from authorized request token.
b, post form 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 also 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.sillycat.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_authorised";
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.println(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-mapping>
<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://dsbjoe.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/introducing-oauth-2-0/

分享到:
评论

相关推荐

    Python库 | oauth2sample-0.1.tar.gz

    1. **安装库**:使用`pip`工具将`oauth2sample-0.1.tar.gz`解压后的目录安装到Python环境中,例如`pip install path/to/oauth2sample-0.1/`。 2. **导入库**:在Python脚本中,使用`import oauth2sample`引入库。 ...

    OAuth Server和OAuth Client(JAVA实现,eclipse环境)

    资源为在eclipse开发环境中使用Java搭建OAuth Server和OAuth Client 参考代码为http://code.google.com/p/oauth/ OAuth Server为遵守OAuth 1.0协议的OAuth认证服务器 OAuth Client分为Desktop版本和Webapp版本

    Oauth2实现java

    OAuth2在Java中的实现通常涉及到服务端和客户端两个部分,这两个部分在Java开发中都有相应的库支持。 Apache Oltu是Apache基金会提供的一个针对OAuth2协议的Java实现,它为开发者提供了全面的API来处理OAuth2的授权...

    OAuth WCF Service Sample

    OAuth WCF Service Sample是一个示例项目,展示了如何在Windows Communication Foundation (WCF)服务中实现OAuth,以便为RESTful API提供安全的数据访问控制。OAuth是一种授权框架,允许第三方应用在用户授权的情况...

    java实现oauth2.0服务端+客户端(含JWT)

    在这个Java实现中,我们利用了MAVEN作为项目管理工具和OLTU库来构建OAuth 2.0服务端和客户端。同时,数据加密采用了MD5算法,以增强安全性。 首先,OAuth 2.0的核心概念包括四个角色:资源所有者(Resource Owner)...

    Java的oauth2.0 服务端与客户端的实现 (完整源码、demo)

    Java的oauth2.0 服务端与客户端的实现.zip 封装了oauth2.0的基本架构和实现,对照我的博客http://blog.csdn.net/jing12062011/article/details/78147306使用该源码。 下载项目压缩包,解压,里面两个maven项目:...

    纯java实现的OAuth2流程

    在这个"纯Java实现的OAuth2流程"中,我们将深入探讨如何不依赖Spring Boot来独立构建OAuth2的客户端和服务端。 首先,我们要理解OAuth2的基本流程,它通常包括四个角色:资源所有者(Resource Owner)、资源服务器...

    java对微信的OAuth2.0网页授权进行访问授权

    1. **OAuth2.0授权流程概述** OAuth2.0是一种授权框架,允许第三方应用在用户同意的情况下,获取其在特定服务上的部分权限。微信OAuth2.0网页授权流程包括四个步骤:授权请求、重定向URI、获取Access Token和获取...

    Java的oauth2.0 服务端与客户端的实现(源码)

    在Java中实现OAuth 2.0,我们可以利用Spring Security OAuth2库,它提供了服务端(Authorization Server)和客户端(Resource Server)的支持。在提供的压缩包中,包含两个Maven项目,一个是`oauthserver`,代表了...

    oauth1-signer-java:零依赖库,用于生成符合Mastercard API的OAuth签名

    oauth1-signer-java 目录 签署HTTP客户端请求对象 与OpenAPI Generator API客户端库集成 概述 零依赖性库,用于生成符合Mastercard API的OAuth签名。 兼容性 Java 7+ 参考 OAuth 1.0a规范 非应用程序/ x-...

    oauth_signpost

    OAuth Signpost是一个针对OAuth协议的Java库,它简化了OAuth认证流程,使得开发者在Java应用中集成OAuth服务变得更加便捷。OAuth是一种授权框架,允许第三方应用在用户授权的情况下访问其存储在另一服务提供者上的...

    Oauth实例(使用Scribe-java)

    1. **OAuth流程概述** OAuth流程通常分为四个步骤: - 请求临时凭证(Request Token):应用向服务提供商发送请求,获取一个临时的请求令牌和请求令牌的秘密。 - 用户授权(Authorization):应用引导用户到服务...

    Oauth2 Java demo

    1. OAuth2核心概念: - 授权码(Authorization Code):用户同意访问其资源后,服务提供者返回给客户端的一个临时代码。 - 密码凭证(Resource Owner Password Credentials):用户直接提供用户名和密码给客户端,...

    oauth2.in.action

    We want you to come away from this book with a deep understanding of what OAuth can do, why it works the way that it does, and how to deploy it properly and securely in an unsafe internet. ...

    Java 微信网页授权登陆 OAuth2.0源码

    1、公众号 扫描测试号二维码关注 2、ngrok 创建本机域名 3、网页服务--》网页帐号--》修改--》授权回调页面域名: 882c783d.ngrok.io 该域名为ngrok域名 4、修改程序中 appID值 org.liufeng.course.servlet....

    Oauth2获取用户基本信息JAVA

    1. **OAuth2基本流程**: OAuth2的核心流程包括四个角色:资源所有者(User)、客户端(Client)、资源服务器(Resource Server)和授权服务器(Authorization Server)。在微信API的上下文中,资源所有者是微信...

    OAuth.2.in.Action.pdf

    《OAuth 2.0 实战》是一本深入探讨OAuth 2.0协议的专业书籍,它主要面向开发者和系统架构师,旨在帮助读者理解和实施OAuth 2.0授权框架,以安全地实现第三方应用的访问权限控制。OAuth 2.0是互联网上广泛采用的开放...

    小米oauth2.0java实现以及第三方云接入

    本教程将详细讲解如何使用Java实现小米的OAuth2.0流程,并实现与第三方云服务的对接。 OAuth2.0的主要流程包括四个角色:资源所有者(用户)、客户端(第三方应用)、授权服务器(小米平台)和资源服务器(存储用户...

    新浪微博 OAuth 授权Sample

    最近开放平台非常火,各大互联网公司都纷纷推出各自的开放平台,随之流行的 OpenID, OAuth 则成为认证和授权的主要技术。本文将以登陆新浪微博获得授权取得用户数据作为示例简单研究 OAuth 的使用

Global site tag (gtag.js) - Google Analytics