Skip to content

OpenId4Java Login Example

March 23, 2011

I was trying these days to integrate OpenId into a web application and I’ve noticed that the documentation about this area is pretty poor so, for the ones who want to avoid a lot of headache I will post my example step by step.

I use openid4java library from here

1. Add this to a jsp page:

<!--Open IDs login-->&nbsp;
<div style="margin-left: 50px; margin-top: 40px; height: 60px;"><form action="/servlet/loginServlet?identifier=https://www.google.com/accounts/o8/id" method="post"> <input class="google openid_large_btn" style="background: #fff url(/resources/images/login/openid-logos.png?v=3); background-position: -1px -1px;" type="image" value=" " /></form>
<form action="/servlet/loginServlet?identifier=https://me.yahoo.com" method="post"><input class="google openid_large_btn" style="background: #fff url(/resources/images/login/openid-logos.png?v=3); background-position: -1px -63px;" type="image" value=" " /> </form></div>

Please note I use an image with two logos (google and yahoo) for my example (you can download it from here:  http://sstatic.net/Img/openid/openid-logos.png?v=3 )

2. Build the LoginServlet class which uses Google and Yahoo for authenticating with openid.

public class LoginServlet 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";

	private final Log log = LogFactory.getLog(this.getClass());
	private static final long serialVersionUID = 309579782731258702L;
	private ServletContext context;
	private ConsumerManager manager;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		context = config.getServletContext();
		try {
			this.manager = new ConsumerManager();
		} catch (ConsumerException e) {
			throw new ServletException(e);
		}
	}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
log.debug("------------------------");
log.debug("context: " + context);
Identifier identifier = this.verifyResponse(req);
log.debug("identifier: " + identifier);
// if openid login succeded redirect to home page using our demo account
//if your site is open to anyone without login you can do the redirect directly
if (identifier != null) {
WebAuthentication pwl = new WebAuthentication();
pwl.login("guest", "guest");**
resp.sendRedirect("/index.jsp");
} else {
System.out.println("login with openid failed");
}
}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String identifier = req.getParameter("identifier");
		this.authRequest(identifier, req, resp);
	}

	// --- placing the authentication request ---
	public String authRequest(String userSuppliedString,
			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
			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);
			}

			// 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
			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(AxMessage.OPENID_NS_AX)) {
					FetchResponse fetchResp = (FetchResponse) authSuccess
							.getExtension(AxMessage.OPENID_NS_AX);

					List emails = fetchResp.getAttributeValues("email");
					String email = (String) emails.get(0);
					log.info("OpenIdlogin done with email: " + email);
				}

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

		return null;
	}

}

3. Add the servlet configuration in web.xml

<servlet>
  <servlet-name>loginOpenIdServlet</servlet-name>
  <servlet-class>your.package.LoginServlet</servlet-class>
 </servlet>

Enjoy it;)

About these ads

From → JAVA

20 Comments
  1. dude_1 permalink

    Unable to compile the LoginServlet. Would it be possible to provide the whole contents of compile folder as a zip file to download?

    Also the reason why I want to try this one specifically is because it is open to most of the networks.

    Using :

    http://en.wikipedia.org/wiki/Openid#OpenID_Providers

    We should be able to increase the list of providers..

    If and when I get it to work I am going to also wrap it around in probably jquery..

    http://jvance.com/pages/JQueryOpenIDPlugin.xhtml

    https://code.google.com/p/openid-selector/

    although in the notes of the latter it seems their looking to add support or facebook which looks like a different method than using current open id (maybe wrong on this) need to still research this… after I get the damn thing to work first :)

  2. @dude_1: Have you included the libraries from here? http://code.google.com/p/openid4java/downloads/list

    Otherwise it will not compile…This is part of a bigger project and I did not have enough time to make it a simple one available for download…

  3. dude_1 permalink

    ls
    commons-codec-1.3.jar ConsumerServlet.java httpclient-4.0.jar jdom-1.0.jar nekohtml-1.9.14.jar servlet-api-2.4.jar spring-2.0-dao.jar svnjavahl-1.0.0.jar
    commons-logging-1.03.jar ehcache-1.2.4.jar httpcore-4.0.1.jar log4j-1.2.8.jar openid4java-0.9.6.jar ServletContextListener.java spring-2.0-jdbc.jar VerificationResult.java
    compile.sh full HttpServletSupport.java LoginServlet.java openid4java-full-0.9.6.662.tar.gz spring-2.0-beans.jar svnant-1.0.0.jar xercesImpl-2.8.1.jar
    ConsumerManager.java guice-2.0.jar jcip-annotations.jar maven-ant-tasks-2.0.7.jar org2 spring-2.0-core.jar svnClientAdapter-1.0.0.jar

    ———————————————-

    javac -cp ./openid4java-0.9.6.jar:./commons-codec-1.3.jar:./httpclient-4.0.jar:./log4j-1.2.8.jar:./servlet-api-2.4.jar:./spring-2.0-jdbc.jar:./xercesImpl-2.8.1.jar:./commons-logging-1.03.jar:./httpcore-4.0.1.jar:./maven-ant-tasks-2.0.7.jar:./spring-2.0-beans.jar:./svnant-1.0.0.jar:./ehcache-1.2.4.jar:./jcip-annotations.jar:./nekohtml-1.9.14.jar:./spring-2.0-core.jar:./svnClientAdapter-1.0.0.jar:./guice-2.0.jar:./jdom-1.0.jar./openid4java-0.9.6.jar:./spring-2.0-dao.jar:./svnjavahl-1.0.0.jar LoginServlet.java

    LoginServlet.java:25: cannot find symbol
    symbol : class ServletContext
    location: class LoginServlet
    private ServletContext context;
    ^
    LoginServlet.java:26: cannot find symbol
    symbol : class ConsumerManager
    location: class LoginServlet
    private ConsumerManager manager;
    ^
    ….
    12 errors

    —–
    If I add: the last ./ to look in local path
    ./svnjavahl-1.0.0.jar:./ LoginServlet.java

    it returns


    ./ConsumerManager.java:1059: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throw new ConsumerException(“Authentication cannot be performed: ” +
    ^
    ./ConsumerManager.java:1336: cannot find symbol
    symbol : variable NonceVerifier
    location: class ConsumerManager
    return (NonceVerifier.OK == _nonceVerifier.seen(
    ^
    Note: ./ConsumerManager.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    30 errors

    ———-

    grep ConsumerManager *.jar
    Binary file openid4java-0.9.6.jar matches

    The file that contains the ConsumerManager is within the path

    Even when I extract out the files and make it part of local files it finds loads of other errors..

    How did you compile it ? i.e. which folder did you put your LoginServlet in and what path provided to javac ?

  4. dude_1 permalink

    I downloaded the full version and now I copied entire new set of jars in to this folder.

    find full/ -name \*.jar -exec cp {} ./ \;

    ls *.jar
    appengine-api-1.0-sdk-1.2.5.jar higgins-configuration-api.jar httpcore-4.0.1.jar log4j-1.2.8.jar openxri-syntax-1.2.0.jar spring-context-2.0.jar svnClientAdapter-1.0.0.jar
    axiom-api-1.2.2.jar higgins-sts-api.jar icu4j-3.4.4.jar maven-ant-tasks-2.0.7.jar servlet-api-2.4.jar spring-web-2.0.jar svnjavahl-1.0.0.jar
    commons-codec-1.3.jar higgins-sts-common.jar jcip-annotations.jar nekohtml-1.9.14.jar spring-2.0-beans.jar spring-webmvc-2.0.jar xalan-2.7.0.jar
    commons-logging-1.03.jar higgins-sts-server-token-handler.jar jdom-1.0.jar openid4java-0.9.6.jar spring-2.0-core.jar standard.jar xercesImpl-2.8.1.jar
    ehcache-1.2.4.jar higgins-sts-spi.jar jstl.jar openid4java-full-0.9.6.jar spring-2.0-dao.jar stax-api-1.0.1.jar xml-apis-1.0.b2.jar
    guice-2.0.jar httpclient-4.0.jar jug-1.1.2.jar openxri-client-1.2.0.jar spring-2.0-jdbc.jar svnant-1.0.0.jar xmlsec-1.3.0.jar

    Automated the javac line by the following:

    echo javac -cp ./`ls *.jar|sed -e “s/$/:.\//g”|tr -d “\n”`
    javac -cp ./appengine-api-1.0-sdk-1.2.5.jar:./axiom-api-1.2.2.jar:./commons-codec-1.3.jar:./commons-logging-1.03.jar:./ehcache-1.2.4.jar:./guice-2.0.jar:./higgins-configuration-api.jar:./higgins-sts-api.jar:./higgins-sts-common.jar:./higgins-sts-server-token-handler.jar:./higgins-sts-spi.jar:./httpclient-4.0.jar:./httpcore-4.0.1.jar:./icu4j-3.4.4.jar:./jcip-annotations.jar:./jdom-1.0.jar:./jstl.jar:./jug-1.1.2.jar:./log4j-1.2.8.jar:./maven-ant-tasks-2.0.7.jar:./nekohtml-1.9.14.jar:./openid4java-0.9.6.jar:./openid4java-full-0.9.6.jar:./openxri-client-1.2.0.jar:./openxri-syntax-1.2.0.jar:./servlet-api-2.4.jar:./spring-2.0-beans.jar:./spring-2.0-core.jar:./spring-2.0-dao.jar:./spring-2.0-jdbc.jar:./spring-context-2.0.jar:./spring-web-2.0.jar:./spring-webmvc-2.0.jar:./standard.jar:./stax-api-1.0.1.jar:./svnant-1.0.0.jar:./svnClientAdapter-1.0.0.jar:./svnjavahl-1.0.0.jar:./xalan-2.7.0.jar:./xercesImpl-2.8.1.jar:./xml-apis-1.0.b2.jar:./xmlsec-1.3.0.jar:./

    javac -cp ./`ls *.jar|sed -e “s/$/:.\//g”|tr -d “\n”` LoginServlet.java
    LoginServlet.java:25: cannot find symbol
    symbol : class ServletContext
    location: class LoginServlet
    private ServletContext context;
    ^
    LoginServlet.java:28: cannot find symbol
    symbol : class ServletConfig
    location: class LoginServlet
    public void init(ServletConfig config) throws ServletException {
    ^
    LoginServlet.java:28: cannot find symbol
    symbol : class ServletException
    location: class LoginServlet
    public void init(ServletConfig config) throws ServletException {
    ^
    LoginServlet.java:39: cannot find symbol
    symbol : class ServletException
    location: class LoginServlet
    throws ServletException, IOException {
    ^
    LoginServlet.java:55: cannot find symbol
    symbol : class ServletException
    location: class LoginServlet
    throws ServletException, IOException {
    ^
    ./ConsumerManager.java:87: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    private ConsumerAssociationStore _associations = new InMemoryConsumerAssociationStore();
    ^
    ./ConsumerManager.java:98: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    private ConsumerAssociationStore _privateAssociations = new InMemoryConsumerAssociationStore();
    ^
    ./ConsumerManager.java:104: cannot find symbol
    symbol : class NonceVerifier
    location: class ConsumerManager
    private NonceVerifier _nonceVerifier = new InMemoryNonceVerifier(60);
    ^
    ./ConsumerManager.java:215: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    public ConsumerAssociationStore getAssociations()
    ^
    ./ConsumerManager.java:228: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    public void setAssociations(ConsumerAssociationStore associations)
    ^
    ./ConsumerManager.java:239: cannot find symbol
    symbol : class NonceVerifier
    location: class ConsumerManager
    public NonceVerifier getNonceVerifier()
    ^
    ./ConsumerManager.java:252: cannot find symbol
    symbol : class NonceVerifier
    location: class ConsumerManager
    public void setNonceVerifier(NonceVerifier nonceVerifier)
    ^
    ./ConsumerManager.java:559: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    public void setPrivateAssociationStore(ConsumerAssociationStore associations)
    ^
    ./ConsumerManager.java:560: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throws ConsumerException
    ^
    ./ConsumerManager.java:575: cannot find symbol
    symbol : class ConsumerAssociationStore
    location: class ConsumerManager
    public ConsumerAssociationStore getPrivateAssociationStore()
    ^
    ./ConsumerManager.java:929: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throws ConsumerException, MessageException
    ^
    ./ConsumerManager.java:966: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throws ConsumerException, MessageException
    ^
    ./ConsumerManager.java:995: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throws MessageException, ConsumerException
    ^
    ./ConsumerManager.java:1025: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throws MessageException, ConsumerException
    ^
    LoginServlet.java:33: cannot find symbol
    symbol : class ConsumerException
    location: class LoginServlet
    } catch (ConsumerException e) {
    ^
    LoginServlet.java:34: cannot find symbol
    symbol : class ServletException
    location: class LoginServlet
    throw new ServletException(e);
    ^
    LoginServlet.java:47: cannot find symbol
    symbol : class WebAuthentication
    location: class LoginServlet
    WebAuthentication pwl = new WebAuthentication();
    ^
    LoginServlet.java:47: cannot find symbol
    symbol : class WebAuthentication
    location: class LoginServlet
    WebAuthentication pwl = new WebAuthentication();
    ^
    ./ConsumerManager.java:87: cannot find symbol
    symbol : class InMemoryConsumerAssociationStore
    location: class ConsumerManager
    private ConsumerAssociationStore _associations = new InMemoryConsumerAssociationStore();
    ^
    ./ConsumerManager.java:98: cannot find symbol
    symbol : class InMemoryConsumerAssociationStore
    location: class ConsumerManager
    private ConsumerAssociationStore _privateAssociations = new InMemoryConsumerAssociationStore();
    ^
    ./ConsumerManager.java:104: cannot find symbol
    symbol : class InMemoryNonceVerifier
    location: class ConsumerManager
    private NonceVerifier _nonceVerifier = new InMemoryNonceVerifier(60);
    ^
    ./ConsumerManager.java:563: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throw new ConsumerException(
    ^
    ./ConsumerManager.java:1028: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throw new ConsumerException(“Authentication cannot continue: ” +
    ^
    ./ConsumerManager.java:1059: cannot find symbol
    symbol : class ConsumerException
    location: class ConsumerManager
    throw new ConsumerException(“Authentication cannot be performed: ” +
    ^
    ./ConsumerManager.java:1336: cannot find symbol
    symbol : variable NonceVerifier
    location: class ConsumerManager
    return (NonceVerifier.OK == _nonceVerifier.seen(
    ^
    Note: ./ConsumerManager.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    30 errors

  5. I have these imports in my LoginServlet class:

    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;

    If you have them also you should be able to run the code without any problems…

  6. dude_1 permalink

    Cristian

    Thanks I have it compiled now :)

    I also noticed the WebAuthentication (which looks like a jboss) feature.

    I am using Tomcat and currently working on getting it all working (google appears to work) but now gonna figure out session store of details and back into own app.

    Will get back and give my input

    Hoping to do a document of my own when its all working which I will link to your kind and wonderful input.

  7. I have managed to make this work now on all my sites – but it only appears that google authentication works and I been struggling with the rest – unsure why yahoo is not working

    I have done a few changes to the code…

    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”;

    //Add your servlet script path here – auth status: 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

    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 (id != 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;
    }

    }

  8. Identifier verified = verification.getVerifiedId();
    String id=verified.getIdentifier();
    if (id != null) {
    //
    }

    unsure about this this from the groups where the other post returned id
    Unsure if this is even valid if anyone does reuse the code

    its possibly worth changing it to original method i.e.

    Identifier verified = verification.getVerifiedId();
    String id=verified.getIdentifier();
    if (verified != null) {
    //
    }

  9. The above code has been working on Tomcat – but it worth also taking into consideration – tomcat security !

    If you are running security – none of them will work until for each outgoing domain permission is granted:

    –Ubuntu/debian: (update this file and restart) –
    –rest find relevant policy file for permissions and update

    /etc/tomcat/policy.d/04webapps.policy
    grant {
    permission java.net.SocketPermission “209.85.149.103:443″, “connect,resolve”;
    permission java.net.SocketPermission “68.142.242.195:443″, “connect,resolve”;
    permission java.net.SocketPermission “*.yahoo.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “me.yahoo.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “login.yahoo.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “217.12.8.76:443″, “connect,resolve”;
    permission java.net.SocketPermission “217.146.187.123:443″, “connect,resolve”;
    permission java.net.SocketPermission “*.yahoo.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “*.yahoo.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “openid.yahoo.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “openid.yahoo.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “me.yahoo.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “www.google.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “www.google.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “google.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “google.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “aol.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “aol.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “openid.aol.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “openid.aol.com:80″, “connect,resolve”;
    permission java.net.SocketPermission “myopenid.com:443″, “connect,resolve”;
    permission java.net.SocketPermission “myopenid.com:80″, “connect,resolve”;
    }

  10. Final comments to help those who want to compile it these are the only libraries required to compile it – most cleanest way:

    These jar files:

    ~# ls *.jar
    commons-logging-1.03.jar log4j-1.2.8.jar openid4java-full-0.9.6.jar servlet-api-2.4.jar

    These are all my files in this folder
    ~# ls
    commons-logging-1.03.jar compile2.sh log4j-1.2.8.jar old OpenAuth.class OpenAuth.java OpenAuth.java.1 OpenAuth.java.7 openid4java-full-0.9.6.jar servlet-api-2.4.jar

    This is my compile script which grabs all the jars and runs it with java file supplied as var1
    ~# more compile2.sh
    javac -classpath classes:./`ls *.jar|sed -e “s/$/:.\//g”|tr -d “\n”` $1

    #this is t showing what it is going to do
    ~# echo javac -classpath classes:./`ls *.jar|sed -e “s/$/:.\//g”|tr -d “\n”` $1
    javac -classpath classes:./commons-logging-1.03.jar:./log4j-1.2.8.jar:./openid4java-full-0.9.6.jar:./servlet-api-2.4.jar:./

    run it – i had ot comment out the usern session values from the above code – and then it compiled
    ~# sh compile2.sh OpenAuth.java
    Note: OpenAuth.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    ~#

    Finally to make it work within tomcat – you will need all the lib files from the main lib folder of the project

    ls *.jar
    commons-codec-1.3.jar commons-logging-1.03.jar guice-2.0.jar httpclient-4.0.jar httpcore-4.0.1.jar nekohtml-1.9.14.jar xercesImpl-2.8.1.jar

    So all the above jar files will need to be put into tomcat lib folder for the host

    ##Please note I found that openid-jar file made my tomcat keep reinitiating it and then did a Perm Gen after 10 minutes.

    Could not figure out why it did this so a work around was to jar -xvf all the above jar files from the main lib folder (which comes out as two folders org and com ) and to then include those two org and com folders within the class path of my servlets so sitting in the same directory ie WEB-INF/classes as OpenAuth.class

    and it then works with no issues

    Hopes it helps :)

  11. Neha permalink

    Hi,
    I am getting error in LoginServlet.java file as WebAuthentication is not found and after importing the file its import org.jboss.web.tomcat.security.login.WebAuthentication;
    still not able to resolve the issue.
    Can any body please answere for this?
    Thanks in advance,

  12. Neha permalink

    Hi,
    I have a created a project with name ServletExample in eclipse and added LoginServlet.java under servlet package of src dir. All the neccessary jars to lib dir of WEB-INF dir. Added the jsp code to index.jsp. According to the above said jar are also added to tomcat lib. but i am not able to run the example if i click the image i am getting the error as

    “HTTP Status 404 – /servlet/loginServlet”
    description : The requested resource (/servlet/loginServlet) is not available.

    Please help me to run this application successfuly.

    Thanks

  13. Neha permalink

    Hi,
    I configured and I am able to compile the files.
    Images are not displayed.By clicking the images i am getting the following error msg

    Jul 24, 2012 11:27:41 AM org.openid4java.server.RealmVerifier setEnforceRpId
    WARNING: RP discovery / realm validation disabled;
    Jul 24, 2012 11:27:42 AM org.openid4java.consumer.ConsumerManager verify
    INFO: Verifying authentication response…
    login with openid failed

    Please can you help me in solving the problem?
    Thanks in Advance.

  14. madhu permalink

    Thank you very much for this sample code. It helped me a lot.

  15. Rachel permalink

    hi…..
    I tried the above code and its working… i am able to login… but i can’t retrieve email id from its response… (ie: the verifyResponse() method is not working).. please help me….

  16. Congrats on this post! Your right the OpenId4Java docs are really poor as is their build (they don’t use Maven correctly). Yours is the best available, thanks! One suggestion would be for you to have a downloadable zip/archive of all source. The one thing I would like to see is your CSS for the login image that you referenced.

  17. “OpenId4Java Login Example Coding tips and notes” was a superb post.
    If solely there were significantly more web blogs just like this one on the world wide web.
    Well, many thanks for your personal time, Abbie

  18. an you answer my question ? http://stackoverflow.com/questions/15254334/openidjsf-redirect-user-to-the-page-he-login

  19. Rahul permalink

    Hi,

    I m using Spring mvc, I got ur code .
    I am getting one exception , java.lang.IllegalArgumentException: Host name may not be null.
    at below lines…
    // perform discovery on the user-supplied identifier
    List discoveries = manager.discover(userSuppliedString);

    can u tell me what is the reason..? and fix for it.

  20. Friso permalink

    Thanks for this. Works like a charm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: