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

OAuth(2)Sample Provider Implementation in JAVA

 
阅读更多
OAuth(2)Sample Provider Implementation in JAVA

5. Modify the provider base on the example

Configure the spring listener and Servlets 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>

<servlet>
        <servlet-name>RequestTokenServlet</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>

<servlet>
<servlet-name>AuthorizationServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>

<servlet>
<servlet-name>AccessTokenServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>

<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>RequestTokenServlet</servlet-name>
<url-pattern>/request_token</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AuthorizationServlet</servlet-name>
<url-pattern>/authorize</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AccessTokenServlet</servlet-name>
<url-pattern>/access_token</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>

Spring configuration file about oauth in oauth-context.xml:
<bean id="oauthValidator" class="net.oauth.SimpleOAuthValidator" >
</bean>

<bean id="oauthProvider" class="com.sillycat.easyoauthprovider.plugins.oauth.impl.OAuthHashMemoryProvider" init-method="init">
<property name="userManager" ref="userManager" />
</bean>

Spring configuration file about servlets in servlet-context.xml:
<bean id="RequestTokenServlet" class="com.sillycat.easyoauthprovider.servlets.RequestTokenHttpRequestHandler" >
<property name="oauthProvider" ref="oauthProvider" />
<property name="oauthValidator" ref="oauthValidator" />
</bean>

<bean id="AuthorizationServlet" class="com.sillycat.easyoauthprovider.servlets.AuthorizationHttpRequestHandler" >
<property name="oauthProvider" ref="oauthProvider" />
</bean>

<bean id="AccessTokenServlet" class="com.sillycat.easyoauthprovider.servlets.AccessTokenHttpRequestHandler" >
<property name="oauthProvider" ref="oauthProvider" />
<property name="oauthValidator" ref="oauthValidator" />
</bean>

<bean id="UserServlet" class="com.sillycat.easyoauthprovider.servlets.UserHttpRequestHandler">
<property name="oauthProvider" ref="oauthProvider" />
<property name="oauthValidator" ref="oauthValidator" />
</bean>

I have the interface of OAuthProvider.java:
package com.sillycat.easyoauthprovider.plugins.oauth;
import java.io.IOException;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import com.sillycat.easyoauthprovider.model.User;
/**
* provide the OAUTH
* @author SILLYCAT
*/
public interface OAuthProvider {
public void init();
/**
* find the consumer in our database
*
* @param requestMessage
* @return
* @throws IOException
* @throws OAuthProblemException
*/
public OAuthConsumer getConsumer(OAuthMessage requestMessage)throws IOException, OAuthProblemException;
/**
* get the ACCESSOR from our database
*
* @param requestMessage
* @return
* @throws IOException
* @throws OAuthProblemException
*/
public OAuthAccessor getAccessor(OAuthMessage requestMessage) throws IOException, OAuthProblemException;
/**
* authorize
*
* @param accessor
* @param user
*/
public void markAsAuthorized(OAuthAccessor accessor, User user);
/**
* generate request token
*
* @param accessor
*/
public void generateRequestToken(OAuthAccessor accessor);
/**
* generate ACCESS token
*
* @param accessor
*/
public void generateAccessToken(OAuthAccessor accessor);
}

One of the Memory implementation OAuthHashMemoryProvider.java, but there is more work in load the properties files:
package com.sillycat.easyoauthprovider.plugins.oauth.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.example.provider.core.SampleOAuthProvider;

import org.apache.commons.codec.digest.DigestUtils;

import com.sillycat.easyoauthprovider.manager.UserManager;
import com.sillycat.easyoauthprovider.model.User;
import com.sillycat.easyoauthprovider.plugins.oauth.OAuthProvider;

public class OAuthHashMemoryProvider implements OAuthProvider {

private final Map<String, OAuthConsumer> ALL_CONSUMERS = Collections
.synchronizedMap(new HashMap<String, OAuthConsumer>(10));

private final Collection<OAuthAccessor> ALL_TOKENS = new HashSet<OAuthAccessor>();

private UserManager userManager;

public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}

public void init() {
try {
loadAllConsumerFromProperties();
} catch (IOException e) {
e.printStackTrace();
}
}

private void loadAllConsumerFromProperties() throws IOException {
Properties p = new Properties();
String resourceName = "/"
+ SampleOAuthProvider.class.getPackage().getName()
.replace(".", "/") + "/provider.properties";
URL resource = SampleOAuthProvider.class.getClassLoader().getResource(
resourceName);
if (resource == null) {
throw new IOException("resource not found: " + resourceName);
}
InputStream stream = resource.openStream();
try {
p.load(stream);
} finally {
stream.close();
}
// for each entry in the properties file create a OAuthConsumer
for (@SuppressWarnings("rawtypes")
Map.Entry prop : p.entrySet()) {
String consumer_key = (String) prop.getKey();
// make sure it's key not additional properties
if (!consumer_key.contains(".")) {
String consumer_secret = (String) prop.getValue();
if (consumer_secret != null) {
String consumer_description = (String) p
.getProperty(consumer_key + ".description");
String consumer_callback_url = (String) p
.getProperty(consumer_key + ".callbackURL");
// Create OAuthConsumer w/ key and secret
OAuthConsumer consumer = new OAuthConsumer(
consumer_callback_url, consumer_key,
consumer_secret, null);
consumer.setProperty("name", consumer_key);
consumer.setProperty("description", consumer_description);
ALL_CONSUMERS.put(consumer_key, consumer);
}
}
}
}

@Override
public OAuthConsumer getConsumer(OAuthMessage requestMessage)
throws IOException, OAuthProblemException {
OAuthConsumer consumer = null;
// try to load from local cache if not throw exception
String consumer_key = requestMessage.getConsumerKey();

consumer = ALL_CONSUMERS.get(consumer_key);

if (consumer == null) {
OAuthProblemException problem = new OAuthProblemException(
"token_rejected");
throw problem;
}

return consumer;
}

@Override
public OAuthAccessor getAccessor(OAuthMessage requestMessage)
throws IOException, OAuthProblemException {
// try to load from local cache if not throw exception
String consumer_token = requestMessage.getToken();
OAuthAccessor accessor = null;
for (OAuthAccessor a : ALL_TOKENS) {
if (a.requestToken != null) {
if (a.requestToken.equals(consumer_token)) {
accessor = a;
break;
}
} else if (a.accessToken != null) {
if (a.accessToken.equals(consumer_token)) {
accessor = a;
break;
}
}
}

if (accessor == null) {
OAuthProblemException problem = new OAuthProblemException(
"token_expired");
throw problem;
}

return accessor;
}

@Override
public void markAsAuthorized(OAuthAccessor accessor, User user) {
// first remove the accessor from cache
ALL_TOKENS.remove(accessor);

if (userManager.login(user)) {
accessor.setProperty("user", user);
//accessor.setProperty("userName", user.getUserName());
//accessor.setProperty("emailAddress", user.getEmailAddress());
accessor.setProperty("authorized", Boolean.TRUE);
// update token in local cache
ALL_TOKENS.add(accessor);
}
}
@Override
public void generateRequestToken(OAuthAccessor accessor) {
// generate oauth_token and oauth_secret
String consumer_key = (String) accessor.consumer.getProperty("name");
// generate token and secret based on consumer_key

// for now use md5 of name + current time as token
String token_data = consumer_key + System.nanoTime();
String token = DigestUtils.md5Hex(token_data);
// for now use md5 of name + current time + token as secret
String secret_data = consumer_key + System.nanoTime() + token;
String secret = DigestUtils.md5Hex(secret_data);

accessor.requestToken = token;
accessor.tokenSecret = secret;
accessor.accessToken = null;

// add to the local cache
ALL_TOKENS.add(accessor);

}

@Override
public void generateAccessToken(OAuthAccessor accessor) {
// generate oauth_token and oauth_secret
String consumer_key = (String) accessor.consumer.getProperty("name");
// generate token and secret based on consumer_key
// for now use md5 of name + current time as token
String token_data = consumer_key + System.nanoTime();
String token = DigestUtils.md5Hex(token_data);
// first remove the accessor from cache
ALL_TOKENS.remove(accessor);
accessor.requestToken = null;
accessor.accessToken = token;
// update token in local cache
ALL_TOKENS.add(accessor);
}
}

The provider.properties is as follow:
myKey=mySecret
myKey.description=OAUTHCONSUMER
myKey.callbackURL=http://localhost:8080/easyoauthconsumer
#noCallbackConsumer=noCallbackSecret
#noCallbackConsumer.description=sample consumer

references:
分享到:
评论

相关推荐

    Python库 | oauth2sample-0.1.tar.gz

    **Python库oauth2sample-0.1.tar.gz详解** 在Python开发中,库扮演着至关重要的角色,它们提供了丰富的功能,让开发者能够高效地构建应用程序。`oauth2sample`是这样一个库,它专注于OAuth 2.0协议的实现,这是一种...

    Python-djangooauth2provider为Django应用提供OAuth2接入

    **Python-django-oauth2-provider** 是一个用于 Django 框架的开源库,它使得开发者能够轻松地在自己的 Django 应用中实现 OAuth2 认证和授权机制。OAuth2 是一种广泛使用的开放标准,允许第三方应用在用户授权的...

    apache-oltu-oauth2-provider-demo, Apache Oltu提供程序服务器演示( Oauth 2.0 ).zip

    apache-oltu-oauth2-provider-demo, Apache Oltu提供程序服务器演示( Oauth 2.0 ) apache-oltu-oauth2-provider-demoApache Oltu提供程序服务器演示( Oauth 2.0 )对于基本OAuth2流程,请阅读以下内容: ...

    Oauth2实现java

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

    PyPI 官网下载 | django-oauth2-provider-0.2.0.tar.gz

    **PyPI官网下载 | django-oauth2-provider-0.2.0.tar.gz** 在Python的世界里,PyPI(Python Package Index)是官方的第三方Python软件包仓库,它为开发者提供了发布和分享自己的Python模块的平台。`django-oauth2-...

    纯java实现的OAuth2流程

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

    PyPI 官网下载 | django-oauth2-provider-ng-0.4.tar.gz

    **PyPI 官网下载 | django-oauth2-provider-ng-0.4.tar.gz 知识点详解** 在Python开发中,PyPI(Python Package Index)是官方的第三方Python软件包仓库,开发者可以发布和下载各种Python库。"django-oauth2-...

    play2-oauth2-provider:使用Play Framework中的scala-oauth2-provider启用了该库

    play2-oauth2-provider 使用Play Framework中的启用了该库。 设置 将“ play2-oauth2-provider”添加到项目的库依赖项。 libraryDependencies ++ = Seq ( " ...

    akka-http-oauth2-provider:使用Akka HTTP中的scala-oauth2-provider启用此库

    libraryDependencies ++ = Seq ( " com.nulab-inc " %% " scala-oauth2-core " % " 1.5.0 " , " com.nulab-inc " %% " akka-http-oauth2-provider " % " 1.4.0 ") 图书馆版本Akka HTTP版本1.4.0 10.1.x 1.3.0 2.4.x

    Oauth2 Java demo

    在这个"Oauth2 Java demo"中,我们将深入理解OAuth2的核心概念以及如何在Java中实现这些概念。 1. OAuth2核心概念: - 授权码(Authorization Code):用户同意访问其资源后,服务提供者返回给客户端的一个临时...

    node-oauth2-provider, 一个简单的可以定制 OAuth 2.0提供程序( 服务器) 用于 node.js.zip

    node-oauth2-provider, 一个简单的可以定制 OAuth 2.0提供程序( 服务器) 用于 node.js 用于连接 & Express的OAuth 2提供商这是用于实现支持服务器端( 代码) 和客户端( 令牌) OAuth流的OAuth2服务器( 提供者)的node....

    Oauth2获取用户基本信息JAVA

    在这个Java实现的案例中,我们将探讨如何使用OAuth2来从微信平台获取用户的基本信息。 1. **OAuth2基本流程**: OAuth2的核心流程包括四个角色:资源所有者(User)、客户端(Client)、资源服务器(Resource ...

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

    - **OAuth2AuthenticationProvider**:处理OAuth 2.0认证的提供者,用于验证令牌的有效性。 - **OAuth2AccessTokenGenerator**:生成JWT访问令牌,包括设置有效时间、签发者等信息。 最后,测试和部署服务端和...

    OAuth2Provider:ZF2 OAuth 2 ServerProvider模块

    用于Zend Framework 2的OAuth 2提供程序模块掌握: 开发: OAuth2Provider模块轻松地将Brent Shaffer的与Zend Framework 2集成在一起。安装最简单的方法是通过作曲家。 ...

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

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

    模拟OAuth2 单点登录

    当你提到“模拟OAuth2 单点登录的java代码实现”时,我们可以探讨以下几个关键知识点: 1. **OAuth2 授权流程**: OAuth2 提供了四种授权类型:授权码(Authorization Code)、隐式(Implicit)、密码(Resource ...

    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版本

    play2-oauth2-provider_2.11-0.9.0.zip

    governator.zip,governanator由netflixgovernanator开发,是一个扩展和实用程序库,它可以增强google guice的功能:类路径扫描和自动绑定、生命周期管理、配置到字段映射、字段验证和并行对象预热。

    oauth2.zip

    这个`oauth2.zip`压缩包提供了一个完整的OAuth2认证和授权的实例,对于学习和理解OAuth2在Java和Spring Boot中的实践具有很高的参考价值。你可以通过深入研究这两个项目,了解OAuth2的各个组成部分及其交互过程,...

    spring-security-oauth2-2.3.5.RELEASE-API文档-中文版.zip

    标签:spring、security、springframework、oauth2、oauth、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代

Global site tag (gtag.js) - Google Analytics