Web services openid4java ConsumerManager请求/线程安全?

Web services openid4java ConsumerManager请求/线程安全?,web-services,openid4java,Web Services,Openid4java,我在servlet中使用openid4java。我有两个servlet——一个执行第一步(将用户重定向到登录/接受应用程序访问),另一个处理结果信息 文档中写到,org.openid4java.consumer.ConsumerManager类在两个步骤中必须是同一个实例。我可以为此创建singleton吗?它是线程和请求安全的吗 谢谢你的回复 //目前仅与谷歌合作 //试试这个-这都是一个 import java.io.IOException; import java.net.Malforme

我在servlet中使用openid4java。我有两个servlet——一个执行第一步(将用户重定向到登录/接受应用程序访问),另一个处理结果信息

文档中写到,org.openid4java.consumer.ConsumerManager类在两个步骤中必须是同一个实例。我可以为此创建singleton吗?它是线程和请求安全的吗


谢谢你的回复

//目前仅与谷歌合作 //试试这个-这都是一个

import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; 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.jboss.web.tomcat.security.login.WebAuthentication; import org.openid4java.OpenIDException; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; 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.ParameterList; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchRequest; import org.openid4java.message.ax.FetchResponse; public class OpenAuth extends javax.servlet.http.HttpServlet { final static String YAHOO_ENDPOINT = "https://me.yahoo.com"; final static String GOOGLE_ENDPOINT = "https://www.google.com/ accounts/o8/id"; //Updated version of example code from : https://crisdev.wordpress.com/2011/03/23/openid4java-login-example/ //Add your servlet script path here - so if auth fails or succeeds it will carry out actions - check below in doGet public String scr="/servlets/MyServlet"; private ServletContext context; private ConsumerManager manager; private ConsumerManager mag; //Code updated by Vahid Hedayati http://pro.org.uk //Removed config init - moved post to doGet - since previous code required it to be a post but also to include identifier as part of url //identifier was also the same variable used for Identifier code - //cleaned up to make different variable and less confusion //doGet identifer changed to openid_identifier and it also now looks for openid_username which are the default variables returned from openid-selector //http://groups.google.com/group/openid4java/browse_thread/thread/ 5e8f24f51f54dc2c //After reading above post - store the manager in the session object and failing with Yahoo authentication I changed code for the manager //manage public void doPost(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException { doGet(req, response); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //New variable String ouser=(String)req.getParameter("openid_username"); if (ouser==null) { ouser="";} //Mage is the session value of openid_consumer_manager if it is null it will generate it once //And where ever manager is called within code it first returns managers value by looking up session value mag=(ConsumerManager)req.getSession().getAttribute("open_id_consumer_manager"); if (mag==null) { this.manager = new ConsumerManager(); req.getSession().setAttribute("open_id_consumer_manager", manager); } String identify=(String)req.getParameter("openid_identifier"); if (identify==null) { identify="";} if (!identify.equals("")) { this.authRequest(identify,ouser, req, resp); }else{ //If they have succeeded it will return them to welcome //welcome looks up if NEWUSER = yes in the session value below and if so //scr now has the ip city/country/postcode so it finalises user additiion by adding users ip country/city/ip as their sign up // if not new well they are already logged in from the relevant session values this code has put in so updats records and returns they my accoount //if authentication here failed or they rejected sharing their email then login page is returned Identifier identifier = this.verifyResponse(req); if (identifier != null) { resp.sendRedirect(scr+"?act=welcome"); } else { resp.sendRedirect(scr+"?act=login"); } } } // --- placing the authentication request --- public String authRequest(String userSuppliedString,String Ouser, HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException { try { // configure the return_to URL where your application will receive // the authentication responses from the OpenID provider String returnToUrl = httpReq.getRequestURL().toString(); // --- Forward proxy setup (only if needed) --- // ProxyProperties proxyProps = new ProxyProperties(); // proxyProps.setProxyName("proxy.example.com"); // proxyProps.setProxyPort(8080); // HttpClientFactory.setProxyProperties(proxyProps); // perform discovery on the user-supplied identifier //Modified - Look up manager value from session manager = (ConsumerManager) httpReq.getSession().getAttribute("open_id_consumer_manager"); 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); FetchRequest fetch = FetchRequest.createFetchRequest(); if (userSuppliedString.startsWith(GOOGLE_ENDPOINT)) { fetch.addAttribute("email", "http://axschema.org/ contact/email", true); fetch.addAttribute("firstName", "http://axschema.org/ namePerson/first", true); fetch.addAttribute("lastName", "http://axschema.org/ namePerson/last", true); } else if (userSuppliedString.startsWith(YAHOO_ENDPOINT)) { fetch.addAttribute("email", "http://axschema.org/ contact/email", true); fetch.addAttribute("fullname", "http://axschema.org/ namePerson", true); } else { // works for myOpenID fetch.addAttribute("fullname", "http:// schema.openid.net/namePerson", true); fetch.addAttribute("email", "http://schema.openid.net/ contact/email", true); } httpReq.getSession().setAttribute("Ouser",Ouser); // attach the extension to the authentication request authReq.addExtension(fetch); httpResp.sendRedirect(authReq.getDestinationUrl(true)); } catch (OpenIDException e) { // present error to the user } 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 //Modified - look up session value before running verification result manager = (ConsumerManager) httpReq.getSession().getAttribute("open_id_consumer_manager"); VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered); // examine the verification result and extract the verified // identifier Identifier verified = verification.getVerifiedId(); String id=verified.getIdentifier(); if (verified != null) { AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse(); if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX); List emails = fetchResp.getAttributeValues("email"); String email = (String) emails.get(0); //////////////////////////////////////////////////////////////////////////////// //Custom bit each person needs to implement to interact with their application: //Authenticate the user, send email verify if user exists on local system //If it does { // httpReq.getSession().setAttribute("USERNAME",usern); httpReq.getSession().setAttribute("LOGGEDIN", "on"); //}else{ String firstName = fetchResp.getAttributeValue("firstName"); String lastName = fetchResp.getAttributeValue("lastName"); String fullname=fetchResp.getAttributeValue("fullname"); if (fullname==null) {fullname="";} if (firstName==null) { firstName="";} if (lastName==null) { lastName="";} if (!fullname.equals("")) { if (fullname.indexOf(",")>-1) { firstName=fullname.substring(0,fullname.indexOf(",")); lastName=fullname.substring(fullname.indexOf(","),fullname.length()); }else if (fullname.indexOf(" ")>-1){ firstName=fullname.substring(0,fullname.indexOf(" ")); lastName=fullname.substring(fullname.indexOf(" "),fullname.length()); } } //This is username returned from the various services that ask for a username - it is returned as openid_username //When using openid-selector it uses openid_identifier and openid_username - which is what this program now looks for String ouser=(String)httpReq.getSession().getValue("Ouser"); if (ouser==null) {ouser="";} //Adduser -- pass email address and ouser //In Adduser class - if ouser is blank split email from 0 to substring.indexOf("@") // generate a random number - look up current user - if exist add random number to end //and add user with email and new username //return bac the newuser and log in like above. httpReq.getSession().setAttribute("NEWUSER","YES"); // httpReq.getSession().setAttribute("USERNAME",usern); httpReq.getSession().setAttribute("LOGGEDIN", "on"); //} return verified; // success } } } catch (OpenIDException e) { // present error to the user } return null; } 导入java.io.IOException; 导入java.net.MalformedURLException; 导入java.net.URL; 导入java.util.List; 导入javax.servlet.ServletConfig; 导入javax.servlet.ServletContext; 导入javax.servlet.ServletException; 导入javax.servlet.http.HttpServletRequest; 导入javax.servlet.http.HttpServletResponse; 导入org.apache.commons.logging.Log; 导入org.apache.commons.logging.LogFactory; //导入org.jboss.web.tomcat.security.login.WebAuthentication; 导入org.openid4java.OpenIDException; 导入org.openid4java.consumer.ConsumerException; 导入org.openid4java.consumer.ConsumerManager; 导入org.openid4java.consumer.VerificationResult; 导入org.openid4java.discovery.DiscoveryInformation; 导入org.openid4java.discovery.Identifier; 导入org.openid4java.message.AuthRequest; 导入org.openid4java.message.AuthSuccess; 导入org.openid4java.message.ParameterList; 导入org.openid4java.message.ax.AxMessage; 导入org.openid4java.message.ax.FetchRequest; 导入org.openid4java.message.ax.FetchResponse; 公共类OpenAuth扩展了javax.servlet.http.HttpServlet{ 最终静态字符串YAHOO_端点=”https://me.yahoo.com"; 最终静态字符串GOOGLE_端点=”https://www.google.com/ 账户/o8/id”; //示例代码的更新版本来自: https://crisdev.wordpress.com/2011/03/23/openid4java-login-example/ //在此处添加您的servlet脚本路径-因此如果身份验证失败或 成功,它将执行操作-在doGet中检查以下内容 公共字符串scr=“/servlets/MyServlet”; 私有服务上下文; 私人消费者管理经理; 私人消费者管理杂志; //代码由Vahid Hedayati更新http://pro.org.uk //已删除config init-已将post移动到doGet-自上一个代码 要求它是一个职位,但也包括标识符的一部分 网址 //标识符也是用于标识符代码的同一变量- //清理,使不同的变量和更少的混乱 //doGet标识符更改为openid_标识符,现在看起来 对于openid\u用户名,这是从 openid选择器 //http://groups.google.com/group/openid4java/browse_thread/thread/ 5e8f24f51f54dc2c //阅读上述内容后,将管理器存储在会话对象中 雅虎认证失败,我为经理更改了代码 //管理 public void doPost(HttpServletRequest-req、HttpServletResponse 响应)抛出ServletException、IOException{ doGet(请求、响应); } 受保护的无效数据集(HttpServletRequest-req,HttpServletResponse resp)抛出ServletException、IOException{ //新变量 字符串ouser=(字符串)req.getParameter(“openid_用户名”); 如果(ouser==null){ouser=”“;} //Mage是openid_consumer_manager的会话值(如果是) null它将生成一次 //在代码中调用管理器的地方,它首先返回 管理者通过查找会话值来实现价值 mag=(ConsumerManager)req.getSession().getAttribute(“打开消费者id管理器”); 如果(mag==null){ this.manager=new ConsumerManager(); req.getSession().setAttribute(“打开\u id\u消费者\u管理器”,管理器); } 字符串标识=(字符串)请求getParameter(“openid_标识符”); 如果(identify==null){identify=”“;} 如果(!identify.equals(“”){ 此.authRequest(标识、用户、请求、响应); }否则{ //如果他们成功了,他们将再次受到欢迎 //如果NEWUSER=yes,欢迎在下面的会话值中查找 如果是的话 //scr现在有ip城市/国家/邮政编码,因此最终确定 通过添加用户ip country/city/ip作为其注册来添加用户 //如果不是新井,则已从 此代码放入的相关会话值用于更新记录和 他们把我的帐还给我了 //如果此处的身份验证失败或他们拒绝共享 然后返回电子邮件登录页面 标识符=此。验证响应(req); if(标识符!=null){ 分别发送重定向(scr+“?act=欢迎”); }否则{ 分别发送重定向(scr+“?act=登录”); } } } //---放置身份验证请求--- 公共字符串authRequest(字符串userSuppliedString、字符串USER、, HttpServletRequest HttpRequest,HttpServletResponse httpResp)抛出 IOException{ 试一试{ //配置应用程序将返回到的URL 接收 //来自OpenID提供程序的身份验证响应 字符串returnToUrl=httpReq.getRequestURL().toString(); //---转发代理设置(仅在需要时)--- //ProxyProperties proxyProps=新的ProxyProperties(); //setProxyName(“proxy.example.com”); //proxyProps.setProxyPort(8080); //HttpClientFactory.setProxyProperties(proxyProps); //对用户提供的标识符执行发现 //修改-从会话中查找管理器值 经理=(消费者经理) httpReq.getSession().getAttribute(“打开用户id\u管理器”); 列表发现=manager.discover(userSuppliedString); //尝试与OpenID提供程序关联 //并检索一个用于身份验证的服务端点 发现发现的信息= 经理助理(发现); //将发现信息存储在用户会话中 httpReq.getSession().setAttribute(“openi