Dealing with OpenId(I)

本文详细介绍了如何使用openid4java库实现OpenID认证流程,包括下载和配置库文件、设置验证器和代理、发送认证请求、处理返回响应等关键步骤,并通过示例代码展示了整个过程。
Dealing with OpenId(I)

1. download the openid4java packages.
the file name is openid4java-full-0.9.5.593.tar.gz
unzip and find the directory openid4java-0.9.5.593/samples/simple-openid

try to run the simple sample with my maven

>mvn jetty:run

try the URL http://localhost:8080/simple-openid/

type in the OpenId:
https://www.google.com/accounts/o8/id

We can have this sample.

2. Try the demo consumer-servlet
We can authenticate successfully, but we can not fetch the data from google site.

3. Try to make a easyopenid project.
ivy.xml:
<!-- commons -->
<dependency org="commons-logging" name="commons-logging" rev="1.1.1" />
<dependency org="commons-httpclient" name="commons-httpclient" rev="3.1" />
<dependency org="commons-codec" name="commons-codec" rev="1.4" />
<!-- openid -->
<dependency org="org/openid4java" name="openid4java-nodeps" rev="0.9.5" />
<!-- 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-beans" rev="3.0.5.RELEASE"/>
<dependency org="org/springframework" name="spring-core" 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"/>
<!-- log4j -->
<dependency org="log4j" name="log4j" rev="1.2.16" />
<!-- jstl -->
<dependency org="jstl" name="jstl" rev="1.1.2" />
<dependency org="taglibs" name="standard" rev="1.1.2" />

servlet in web.xml:
<servlet>
<servlet-name>Consumer Servlet</servlet-name>
<servlet-class>com.sillycat.easyopenid.ConsumerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Consumer Servlet</servlet-name>
<url-pattern>/consumer</url-pattern>
</servlet-mapping>

My servlet class(only can be used in google OPENID API):
package com.sillycat.easyopenid;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.InMemoryConsumerAssociationStore;
import org.openid4java.consumer.InMemoryNonceVerifier;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.MessageExtension;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
import org.openid4java.message.sreg.SRegMessage;
import org.openid4java.message.sreg.SRegRequest;
import org.openid4java.message.sreg.SRegResponse;

public class ConsumerServlet extends javax.servlet.http.HttpServlet {

private static final long serialVersionUID = -5998885243419513055L;

private final Log log = LogFactory.getLog(this.getClass());

private ServletContext context;

private ConsumerManager manager;

public void init(ServletConfig config) throws ServletException {
super.init(config);

context = config.getServletContext();

log.debug("context: " + context);

try {
// --- Forward proxy setup (only if needed) ---
// ProxyProperties proxyProps = new ProxyProperties();
// proxyProps.setProxyName("proxy.example.com");
// proxyProps.setProxyPort(8080);
// HttpClientFactory.setProxyProperties(proxyProps);
this.manager = new ConsumerManager();
manager.setAssociations(new InMemoryConsumerAssociationStore());
manager.setNonceVerifier(new InMemoryNonceVerifier(5000));
} catch (ConsumerException e) {
throw new ServletException(e);
}
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if ("true".equals(req.getParameter("is_return"))) {
processReturn(req, resp);
} else {
String identifier = req.getParameter("openid_identifier");
if (identifier != null) {
this.authRequest(identifier, req, resp);
} else {
this.getServletContext().getRequestDispatcher("/index.jsp")
.forward(req, resp);
}
}
}

private void processReturn(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Identifier identifier = this.verifyResponse(req);
log.debug("identifier: " + identifier);
if (identifier == null) {
this.getServletContext().getRequestDispatcher("/index.jsp")
.forward(req, resp);
} else {
req.setAttribute("identifier", identifier.getIdentifier());

this.getServletContext().getRequestDispatcher("/return.jsp")
.forward(req, resp);
}
}

// --- placing the authentication request ---
public String authRequest(String userSuppliedString,
HttpServletRequest httpReq, HttpServletResponse httpResp)
throws IOException, ServletException {
try {
// configure the return_to URL where your application will receive
// the authentication responses from the OpenID provider
// String returnToUrl = "http://example.com/openid";
String returnToUrl = httpReq.getRequestURL().toString()
+ "?is_return=true";

// perform discovery on the user-supplied identifier
List<?> discoveries = manager.discover(userSuppliedString);

// attempt to associate with the OpenID provider
// and retrieve one service endpoint for authentication
DiscoveryInformation discovered = manager.associate(discoveries);

// store the discovery information in the user's session
httpReq.getSession().setAttribute("openid-disc", discovered);

// obtain a AuthRequest message to be sent to the OpenID provider
AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

// Attribute Exchange example: fetching the 'email' attribute
FetchRequest fetch = FetchRequest.createFetchRequest();
SRegRequest sregReq = SRegRequest.createFetchRequest();

if ("1".equals(httpReq.getParameter("nickname"))) {
fetch.addAttribute("nickname",
"http://axschema.org/namePerson/last", true);
sregReq.addAttribute("nickname", true);
}
if ("1".equals(httpReq.getParameter("email"))) {
fetch.addAttribute("email",
"http://schema.openid.net/contact/email", true);
sregReq.addAttribute("email", true);
}
if ("1".equals(httpReq.getParameter("fullname"))) {
fetch.addAttribute("fullname",
"http://axschema.org/namePerson/first", true);
sregReq.addAttribute("fullname", true);
}
if ("1".equals(httpReq.getParameter("country"))) {
fetch.addAttribute("country",
"http://axschema.org/contact/country/home", true);
sregReq.addAttribute("country", true);
}
if ("1".equals(httpReq.getParameter("language"))) {
fetch.addAttribute("language",
"http://axschema.org/pref/language", true);
sregReq.addAttribute("language", true);
}

// attach the extension to the authentication request
if (!sregReq.getAttributes().isEmpty()
|| !fetch.getAttributes().isEmpty()) {
authReq.addExtension(sregReq);
authReq.addExtension(fetch);
}

if (!discovered.isVersion2()) {
// Option 1: GET HTTP-redirect to the OpenID Provider endpoint
// The only method supported in OpenID 1.x
// redirect-URL usually limited ~2048 bytes
httpResp.sendRedirect(authReq.getDestinationUrl(true));
return null;
} else {
// Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/formredirection.jsp");
httpReq.setAttribute("prameterMap", httpReq.getParameterMap());
httpReq.setAttribute("message", authReq);
// httpReq.setAttribute("destinationUrl", httpResp
// .getDestinationUrl(false));
dispatcher.forward(httpReq, httpResp);
}
} catch (OpenIDException e) {
// present error to the user
e.printStackTrace();
}

return null;
}

// --- processing the authentication response ---
public Identifier verifyResponse(HttpServletRequest httpReq) {
try {
// extract the parameters from the authentication response
// (which comes in as a HTTP request from the OpenID provider)
ParameterList response = new ParameterList(
httpReq.getParameterMap());

// retrieve the previously stored discovery information
DiscoveryInformation discovered = (DiscoveryInformation) httpReq
.getSession().getAttribute("openid-disc");

// extract the receiving URL from the HTTP request
StringBuffer receivingURL = httpReq.getRequestURL();
String queryString = httpReq.getQueryString();
if (queryString != null && queryString.length() > 0)
receivingURL.append("?").append(httpReq.getQueryString());

// verify the response; ConsumerManager needs to be the same
// (static) instance used to place the authentication request
VerificationResult verification = manager.verify(
receivingURL.toString(), response, discovered);

// examine the verification result and extract the verified
// identifier
Identifier verified = verification.getVerifiedId();
if (verified != null) {
AuthSuccess authSuccess = (AuthSuccess) verification
.getAuthResponse();

if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
MessageExtension ext = authSuccess
.getExtension(SRegMessage.OPENID_NS_SREG);
if (ext instanceof SRegResponse) {
SRegResponse sregResp = (SRegResponse) ext;
for (Iterator<?> iter = sregResp.getAttributeNames()
.iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = sregResp.getParameterValue(name);
httpReq.setAttribute(name, value);
}
}
}
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess
.getExtension(AxMessage.OPENID_NS_AX);

List<?> aliases = fetchResp.getAttributeAliases();
for (Iterator<?> iter = aliases.iterator(); iter.hasNext();) {
String alias = (String) iter.next();
List<?> values = fetchResp.getAttributeValues(alias);
if (values.size() > 0) {
log.debug(alias + " : " + values.get(0));
httpReq.setAttribute(alias, values.get(0));
}
}
}

return verified; // success
}
} catch (OpenIDException e) {
e.printStackTrace();
// present error to the user
}
return null;
}
}


references:
http://www.blogjava.net/i369/articles/238670.html
http://code.google.com/p/openid4java/
http://code.google.com/p/openid4java/wiki/SRegHowTo
http://code.google.com/p/openid4java/wiki/SampleConsumer
http://www.bookfm.com/discussion/discussionview.html?did=100647
http://code.google.com/apis/accounts/docs/OpenID.html
在处理网络或系统编程中的连接条目时,尤其是需要根据 `DIR_ORIGINAL` 类型的元组(tuple)进行过滤的情况下,通常涉及对连接跟踪(connection tracking)机制的理解和操作。`DIR_ORIGINAL` 通常用于表示连接的初始方向,即数据包最初是由哪一方发起的。这种机制广泛应用于 Linux 的 Netfilter 框架中,尤其是在使用 `libnetfilter_queue` 或 `conntrack` 工具进行连接状态跟踪时[^1]。 在实际编程中,可以通过访问连接跟踪表来获取连接条目,并基于 `DIR_ORIGINAL` 进行过滤。以下是一个使用 `libnetfilter_conntrack` 库的示例代码片段,展示如何遍历连接条目并筛选出 `DIR_ORIGINAL` 方向的数据: ```c #include <libnetfilter_conntrack/libnetfilter_conntrack.h> #include <stdio.h> int callback(enum nf_conntrack_msg_type type, struct nf_conntrack *ct, void *data) { // 获取连接的方向 int direction = nfct_get_attr_u8(ct, ATTR_DIR); // 判断是否为 DIR_ORIGINAL 方向 if (direction == IP_CT_DIR_ORIGINAL) { char buf[1024]; nfct_snprintf(buf, sizeof(buf), ct, NFCT_T_UNKNOWN, NFCT_O_DEFAULT, 0); printf("Original direction connection: %s\n", buf); } return NFCT_CB_CONTINUE; } int main() { struct nfct_handle *h; h = nfct_open(CONNTRACK, 0); if (!h) { perror("nfct_open"); return -1; } if (nfct_register_callback(h, NFCT_T_ALL, callback, NULL) < 0) { perror("nfct_register_callback"); nfct_close(h); return -1; } // 开始监听连接事件 if (nfct_loop(h, 0, NULL) < 0) { perror("nfct_loop"); } nfct_close(h); return 0; } ``` 在上述代码中,程序通过 `nfct_register_callback` 注册一个回调函数,每当有连接状态变化时触发。回调函数内部通过 `nfct_get_attr_u8` 获取连接的方向属性,并与 `IP_CT_DIR_ORIGINAL` 进行比较,以判断是否为初始方向的连接条目。如果是,则将其格式化输出。 此外,对于更高级的用例,例如在用户空间中对连接进行更复杂的过滤或操作,可以结合 `nftables` 或 `iptables` 的扩展功能,利用其提供的 `conntrack` 匹配规则来实现。例如,在 `nftables` 中可以使用如下规则来匹配 `DIR_ORIGINAL` 方向的流量: ```bash nft add rule ip filter input ct direction original counter ``` 该规则将匹配所有初始方向的连接,并对其进行计数。这种方式适合在不需要编写完整程序的情况下快速实现方向过滤。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值