|
SampleConsumer
Sample code for OpenID-enabling a consumer / relying party website.
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;
}
}
|
► Sign in to add a comment
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.
Take a look at the javadoc for ConsumerManager? and I think you'll find your answer.
This example requires the following code in the constructor when using 0.9.4
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.
http://www.oschina.net/
@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").
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:
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
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.
Is the above logic works for all open id providers ?
"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. :-/
"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.
Can someone enlighten me on what the 'userSuppliedString' will be?
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...
"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.
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); }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!
what's mean RequestDispatcher? dispatcher =
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); }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
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:
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.....!
What would be the appropriate contents of the formredirection.jsp JSP page?
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.
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?
So, Is there a way around this "Request URI too large" problem, if we want to use google openId for our apps.
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...
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))
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
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
I am also getting verification.getVerifiedId() as null, what can be the problem?
Solved the null verifiedId... I looked in the samples of the openid4java files and they had this on the constructer:
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
Thanks s.j.wood, it solve my problem !!
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:
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) {
if u find any suggestion plz.... share with me
Regards, Mateen