My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
QuickStart  
Brief introduction to OpenID-enabling your webapp
Featured
zh-Hans , en
Updated Feb 4, 2010 by Johnny.B...@gmail.com

Quick Start

Once you have installed the library and have obtained the user's OpenID identifier, you have to put in the following code to have your webapp perform authentication using OpenID:

Instantiate a ConsumerManager Object

    public ConsumerManager manager;

    public SampleConsumer() throws ConsumerException
    {
        _manager = new ConsumerManager();
    }

The ConsumerManager will do all the OpenID hard work for you.

Define a ReturnURL

This is the endpoint where your webapp will receive and process the authentication responses from the OpenID Provider.

    String _returnURL = "http://example.com/openid";

Create an Authentication Request

    // 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 for later use
    // leave out for stateless operation / if there is no session
    session.setAttribute("discovered", discovered);

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

Redirect the User to Their OpenID Provider

    httpResp.sendRedirect(authReq.getDestinationUrl(true));

Verify the OpenID Provider's Authentication Response

Receive the response at your webapp's ReturnURL and process it like this:

    // extract the parameters from the authentication response
    // (which comes in as a HTTP request from the OpenID provider)
    ParameterList openidResp = new ParameterList(request.getParameterMap());

    // retrieve the previously stored discovery information
    DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovered");

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

    // verify the response
    VerificationResult verification = _consumerManager.verify(receivingURL.toString(), openidResp, discovered);

    // examine the verification result and extract the verified identifier
    Identifier verified = verification.getVerifiedId();

    if (verified != null)
        // success, use the verified identifier to identify the user
    else
        // OpenID authentication failed

Where to go next?

You can see all the above put together in the SampleConsumer class.

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 Michael.Krog, Feb 21, 2010

"it'd be really nice to get some confirmation that it is safe to share a single instance between all requests."

I agree. I have created a filter in my webapp that handles all the loginprocess at i hat only a single instance of ConsumerManager?. Should I create one for each loginprocess?

Comment by ravi.4in...@gmail.com, Jul 11, 2010

I need some help in working gmail credentials. I used my gmail username as useridentifier(id@gmail.com).But my code which is similar to sampleconsumer.java is not able to discover the google endpoint.

same code is working fine for yahoo as i am able to authenticate user and get user information.

any help will be appreciated. thanks in advance

Comment by Adam.M...@gmail.com, Aug 5, 2010

@ravi did you discover how to do this? I'm looking at creating an app and using either OpenAuth? and have my own authentication server or, preferably, using OpenID and the users Google or other OpenID account.

Now, correct me if I'm wrong but the server to authenticate against is contained within the users ID URI, so discovering the authenticaton servers shouldn't be a problem?

Comment by lovelyvi...@gmail.com, Nov 1, 2010

Hi When I run ant file given in samples (demorp project).. I get the errors saying that cannot use javahl nor command line svn client. I included required jar files in my ant build still I am getting this error: svnant-1.0.0.jar svnClientAdapter-1.0.0.jar svnjavahl-1.0.0.jar svnkit.jar

Kindly help.

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

@Michael: For correctness, each user login MUST use its own SampleConsumer. It's just like concurrent bank account updates. In this case, state is in ConsumerManager?, and if a one login overwrites an earlier login's ConsumerManager? before the earlier login has finished using the ConsumerManager?, then the earlier login will fail.

Since the entire protocol takes little time (typically less than a second) unless a site has hundreds of logins per hour, the chance of logins conflicting is quite low. But shared code is still wrong.

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

I don't understand the session.setAttribute() calls in SampleConsumer.verifyResponse(). They write to the HttpServletRequest? that contains the authentication response. However, this request isn't accessible to any other code.

It seems to me that for SampleConsumer to be useful the session.setAttribute() calls must be replaced by writing to a data structure available to all SampleConsumer references. For example, I'm saving them to a HashMap?.

Arthur

Comment by blueeins...@gmail.com, Jun 17, 2011

Question - if there's an identity provider that does not support "discovery endpoint" (ie. can't do discovery), would openid4java work for this kind of scenario?

Comment by artgoldb...@gmail.com, Jul 10, 2011

Instantiation of a ConsumerManager? (see line 70 of class SampleConsumer) fails with java.lang.ClassNotFoundException?: javax.inject.Provider

$20 to anyone who solves this within an hour!

Arthur

Comment by pixelapp...@gmail.com, Oct 17, 2011

How do I find out the user's OpenID identifier?

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