My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
SampleConsumer  
Sample code for OpenID-enabling a consumer / relying party website.
Updated Feb 4, 2010 by Johnny.B...@gmail.com

SampleConsumer

/*
 * Copyright 2006-2007 Sxip Identity Corporation
 */

package org.openid4java.consumer;

import org.openid4java.discovery.Identifier;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.*;
import org.openid4java.OpenIDException;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.io.IOException;

/**
 * Sample Consumer (Relying Party) implementation.
 */
public class SampleConsumer
{
    public ConsumerManager manager;

    public SampleConsumer() throws ConsumerException
    {
        // instantiate a ConsumerManager object
        manager = new ConsumerManager();
    }

    // --- 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 = "http://example.com/openid";

            // --- 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);

            // Attribute Exchange example: fetching the 'email' attribute
            FetchRequest fetch = FetchRequest.createFetchRequest();
            fetch.addAttribute("email",
                    // attribute alias
                    "http://schema.openid.net/contact/email",   // type URI
                    true);                                      // required

            // attach the extension to the authentication request
            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("parameterMap", authReq.getParameterMap());
                httpReq.setAttribute("destinationUrl", authReq.getDestinationUrl(false));
                dispatcher.forward(httpReq, httpResp);
            }
        }
        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);
                }

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

        return null;
    }
}
Comment by travis.m...@gmail.com, Feb 11, 2008

Note that the same instance of ConsumerManager? is used for association/authentication and verification. Otherwise, verification fails (or at least it did for me). It looks like ConsumerManager? is thread-safe, but it'd be really nice to get some confirmation that it is safe to share a single instance between all requests.

Comment by elah.nev...@gmail.com, Feb 21, 2008

Take a look at the javadoc for ConsumerManager? and I think you'll find your answer.

Comment by kwon3...@gmail.com, Mar 14, 2008

This example requires the following code in the constructor when using 0.9.4

RealmVerifier rv = new RealmVerifier();
rv.setEnforceRpId(false);
manager.setRealmVerifier(rv);
Comment by rituraj....@gmail.com, Sep 16, 2008

I created a consumer using this library. My biggest problem is: How to I make Yadis discovery work? I have currently turned off enforcement of local discovery, but I still see reams of stack traces that I would like to eliminate. It would be useful if there was a Wiki entry on this topic.

Comment by java...@gmail.com, Nov 4, 2008
Comment by zock...@gmail.com, Jun 26, 2009

@elah.nevets: the javadoc does not answer this question. maybe it did ... but it doesn't anymore. clarification would be appreciated.

@ rituraj.tiwari: if there was a "password may not be null" exception regarding the keystore you should google how to set a password. glassfish has a default keystore but the default password ("changeit") is not entered. start up the server with the jvm option "-Djavax.net.ssl.keyStorePassword=changeit" (and maybe "-Djavax.net.ssl.trustStorePassword=changeit").

Comment by riccardo...@gmail.com, Feb 11, 2010

i am behind a proxy, so i uncommented the following line:

ProxyProperties? proxyProps = new ProxyProperties?(); proxyProps.setProxyHostName("proxy.example.com"); proxyProps.setProxyPort(8080); HttpClientFactory?.setProxyProperties(proxyProps);

first of all the method setProxyName does not exist, i used setProxyHostName. Second i had to perform proxy authentication, so i add the following line:

proxyProps.setUserName("myUser"); proxyProps.setPassword("myPass");

but i had an exception INFO: org.openid4java.discovery.yadis.YadisException?: 0x706: GET failed on http://gmail.com/ : 407:HTTP/1.1 407 Proxy Authentication Required

Comment by meetshri...@gmail.com, Feb 17, 2010

What is the "userSuppliedString" in this? Can any one give example on this. I'm trying to redirect to Google Federation Sign in page by clicking an Icon in the web page.

TIA.

Comment by meetshri...@gmail.com, Feb 17, 2010

Is the above logic works for all open id providers ?

Comment by Michael.Krog, Feb 21, 2010

"What is the "userSuppliedString" in this?"


I was tricked by this one too. It is simply the Url for the openid-service you want to use for login.

Example: Novell=http://novell.com/openid Google=https://www.google.com/accounts/o8/id Yahoo=http://yahoo.com/ YourOwnService?=YourOwnUrl? etc.

However to find out the urls of the public openid services, can be tough. I eventually found another site that used openid login and took a look at his html-code. :-/

Comment by ben.tru...@gmail.com, Mar 12, 2010

"I was tricked by this one too. It is simply the Url for the openid-service you want to use for login.

Example: Novell=http://novell.com/openid Google=https://www.google.com/accounts/o8/id Yahoo=http://yahoo.com/ YourOwnService??=YourOwnUrl?? etc.

However to find out the urls of the public openid services, can be tough. I eventually found another site that used openid login and took a look at his html-code. :-/ "

Thanks so much.

This is so important and so incredibly un-obvious - this should be one of the first pieces of information in the quick start.

Comment by bab...@gmail.com, Mar 21, 2010

Can someone enlighten me on what the 'userSuppliedString' will be?

Comment by luismi.amoros, Mar 27, 2010

Can someone tell me where i can find a source code example on login with a google account in an external web?? i'm becoming crazy about that...

Comment by arturote...@gmail.com, Apr 16, 2010

"However to find out the urls of the public openid services, can be tough. I eventually found another site that used openid login and took a look at his html-code. :-/"

I've found a openid selector: http://code.google.com/p/openid-realselector/

So you can easily get the userSuppliedString.

Comment by s.j.wood...@gmail.com, May 26, 2010

Below is code that will do basic Attribute Exchange with Google, Yahoo and myOpenID. It only does name and email as that's all that I required but it took me a long time to get it working. Hope that it's of use to someone else! Note that some of the AX attributes are case sensitive (and currently incorrect in Google's documentation. None of the sites mind that the attributes come out with ext1. rather than ax. namespace names

private String yahooEndpoint = "https://me.yahoo.com";
private String googleEndpoint = "https://www.google.com/accounts/o8/id";
…
FetchRequest fetch = FetchRequest.createFetchRequest();
  if (userSuppliedString.equals(googleEndpoint)) {
    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.equals(yahooEndpoint)) {
    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);
}

if (!fetch.getAttributes().isEmpty()) {
  authReq.addExtension(fetch);
}
Comment by sergey.k...@gmail.com, Jul 5, 2010

How do I use verified identifier from

Identifier verified = verification.getVerifiedId();

I am receiving a successfully Verified Identifier. But how do I use it after that? It is an authorized access token to access gdata? Is there a sample code that shows the use of Verified Identifier?

Thank you!

Comment by newbe...@gmail.com, Jul 13, 2010

what's mean RequestDispatcher? dispatcher =

getServletContext().getRequestDispatcher("formredirection.jsp");

Comment by ohadr.de...@gmail.com, Aug 5, 2010

answer for Luci...@smartermob.com : -it means that we dispatch the call to another JSP. in this case, to formredirection.jsp :-)


About fetching the paras from the provider: thanks to s.j.woodman,; I made some changes, might interest you:

		final String yahooEndpoint = "https://me.yahoo.com"; 
		final String googleEndpoint = "https://www.google.com"; 

		FetchRequest fetch = FetchRequest.createFetchRequest(); 
		if (userSuppliedString.startsWith(googleEndpoint)) 
		{ 
			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(yahooEndpoint)) 
		{ 
			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); 
		} 
Comment by koushikg...@gmail.com, Sep 21, 2010

Hi guys,

I am getting value of this one as null authSuccess.hasExtension(AxMessage?.OPENID_NS_AX)

Any idea, i am trying yahoo and google providers..

Thank you

Comment by hao.nguy...@gmail.com, Oct 22, 2010

Hello,

If you are using GWT instead of jsp, remember that the httpResp.sendRedirect(authReq.getDestinationUrl(true)) does not work on ServletConsumer?.java (in samples/consumer-servlet). So should: 1/ set the url in header String url=authReq.getDestinationUrl(true); httpResp.setHeader("url", url); 2/ then on the client side do a Window.Location.replace when receiving the response of your POST. cf:

RequestBuilder? request = new RequestBuilder?(RequestBuilder?.POST, url); try {
request.sendRequest("ok",
new com.google.gwt.http.client.RequestCallback?() {

public void onError(Request request, Throwable exception) {
// code omitted for clarity
}
public void onResponseReceived(Request request,
Response response) {
String url=response.getHeader("url"); Window.Location.replace(url);
}
Comment by anuj0...@gmail.com, Dec 5, 2010

I am able to get all the other information from yahoo except the avatar, i am using the below code:-

FetchRequest?? fetch = FetchRequest???.createFetchRequest(); fetch.addAttribute("email", "http://axschema.org/contact/email",true); fetch.addAttribute("avatar","http://axschema.org/media/image/default", true);

ret.addExtension(fetch);

In the return I am using this:-

FetchResponse?? fetchResp = (FetchResponse???) ext;

List emails = fetchResp.getAttributeValues("email");

String avatar =fetchResp.getAttributeValue("avatar");

But I am not getting the avatar......any idea.....!

Comment by frans.lu...@gmail.com, Jan 20, 2011

What would be the appropriate contents of the formredirection.jsp JSP page?

Comment by amritpa...@gmail.com, Feb 20, 2011

While using the Simple-openid sample, I am trying to use Google openid for logging in. However, after I am redirected to the Google Login page and I enter my credentials , I get the "REQUEST-URI too Large" Error from google. Has anybody else encountered this problem.

Comment by atari.60...@gmail.com, Feb 21, 2011

Yes I got the same message. It seems to me that this is since a few days? maybe a change on the google login page?

Comment by amritpa...@gmail.com, Feb 21, 2011

So, Is there a way around this "Request URI too large" problem, if we want to use google openId for our apps.

Comment by cristibo...@gmail.com, Mar 2, 2011

Apart from this code is there any other setting which I have to do to fire this authRequest? For instance something to set up in web.xml? Thanks in advance...

Comment by dilan.wi...@gmail.com, Mar 31, 2011

can any one tell me is it possible to send AuthRequest? with the password and get the response without redirection part?

httpResp.sendRedirect(authReq.getDestinationUrl(true))

Comment by atishkum...@gmail.com, Apr 7, 2011

Hi all, I am running the step2 consumer example that uses org.openid4java.consumer.VerificationResult? but i am geting verification.getVerifiedId()as null that lead to: VerificationException?("something went wrong during response verification, such as nonce or signature checking. Check your debug logs.") any idea what may be wrong

Comment by artgoldb...@gmail.com, May 13, 2011

All

Careful. Different code in the distro: ./src/org/openid4java/consumer/SampleConsumer.java

Problems:

1: no code if ( discovered.isVersion2() )

2:

                RequestDispatcher dispatcher =
                        getServletContext().getRequestDispatcher("formredirection.jsp");
                httpReq.setAttribute("prameterMap", authReq.getParameterMap());
                httpReq.setAttribute("destinationUrl", authReq.getDestinationUrl(false));
                dispatcher.forward(httpReq, httpResp);

is wrong. Sorry, no time to fix it now.

Arthur

Comment by mgc...@gmail.com, Aug 5, 2011

I am also getting verification.getVerifiedId() as null, what can be the problem?

Comment by mgc...@gmail.com, Aug 5, 2011

Solved the null verifiedId... I looked in the samples of the openid4java files and they had this on the constructer:

manager.setAssociations(new InMemoryConsumerAssociationStore?()); manager.setNonceVerifier(new InMemoryNonceVerifier?(5000)); manager.setMinAssocSessEnc(AssociationSessionType?.DH_SHA256);
Comment by sannidh...@gmail.com, Aug 29, 2011

mgc...@gmail: Thanks much! It helped.

All: For logout feature, you may refer to http://stackoverflow.com/questions/1968814/how-to-add-logout-feature-to-an-openid-enabled-site

Comment by el...@listus.com.br, Sep 23, 2011

Thanks s.j.wood, it solve my problem !!

Comment by mateen.s...@gmail.com, Feb 1, 2012

Hi evrybdy...

i'm trying to use OpenId4Java? for myservlet in which i'm facing error "0x100: Required parameter missing: openid.mode" in the following line of code:

verifyRes = manager.verify(requestUrl, paramList,
returnDiscoveyInfo);

im using only one servlet for getting email id and loggin method i have created for this purpose, so i guess i dont have to use response.sendredirect or any request dispatcher method...

if u find any suggestion plz.... share with me

public String loggin(String OpenId?, HttpServletRequest? request) {

System.out.println("Inside loggin method");
List<DiscoveryInformation> discoveries = null; String requestUrl = request.getRequestURL().toString(); System.out.println(" return url is: " + requestUrl); ConsumerManager? manager = null; DiscoveryInformation? discoveyInfo = null; AuthRequest? authReq = null; FetchRequest? fetchRequest = null; FetchResponse? fetchResponse = null; manager = new ConsumerManager?(); try {
discoveries = manager.discover(OpenId?);
} catch (DiscoveryException? e) {
System.out.println("DiscoveryException? " + e.getStackTrace());
} discoveyInfo = manager.associate(discoveries); // setting some new attribure request.getSession().setAttribute("openid-disc", discoveyInfo); try {
authReq = manager.authenticate(discoveyInfo, requestUrl);
} catch (MessageException? e) {
e.printStackTrace(); System.out.println("MessageException?: " + e.getMessage());
} catch (ConsumerException? e) {
e.printStackTrace(); System.out.println("ConsumerException? " + e.getMessage());
} fetchRequest = FetchRequest?.createFetchRequest(); try {
fetchRequest.addAttribute("email", "http://axschema.org/contact/email", true);
} catch (MessageException? e) {
e.printStackTrace(); System.out.println("MessageException?: " + e.getMessage());
} try {
authReq.addExtension(fetchRequest);
} catch (MessageException? e) {
e.printStackTrace();
} System.out.println(discoveyInfo.isVersion2() + "discoveyInfo.isVersion2()"); // verification process for getting gmail id System.out.println("Starting verification process........."); VerificationResult? verifyRes = null; FetchResponse? successFetchResponse = null; ParameterList? paramList = new ParameterList?(request.getParameterMap());
DiscoveryInformation? returnDiscoveyInfo = (DiscoveryInformation?) request.getSession().getAttribute("openid-disc");
try {
verifyRes = manager.verify(requestUrl, paramList,returnDiscoveyInfo);
} catch (MessageException? e) {
System.out.println("Message exception ex: " + e.getMessage()); e.printStackTrace();
} catch (DiscoveryException? e) {
System.out.println("Dsicovery Exception ex " + e.getMessage()); e.printStackTrace();
} catch (AssociationException? e) {
System.out.println("Association exception ex " + e.getMessage()); e.printStackTrace();
} String identifier = verifyRes.getVerifiedId().getIdentifier(); System.out.println("identifier is: " + identifier); if (identifier != null || (!identifier.isEmpty())) {
AuthSuccess? success = (AuthSuccess?) verifyRes.getAuthResponse(); try {
successFetchResponse = (FetchResponse?)success.getExtension(AxMessage?.OPENID_NS_AX);
} catch (MessageException? e) {
System.out.println("MessageException? eee: " + e.getMessage()); e.printStackTrace();
}
} String strEmailId = successFetchResponse.getAttributeValue("emailid").toString(); System.out.println(strEmailId + " is user emailid");
System.out.println("End loggin."); return null;
}

if u find any suggestion plz.... share with me

Regards, Mateen


Sign in to add a comment
Powered by Google Project Hosting