openid4java-0.9.6.662/0000755001501200150120000000000011627733442013575 5ustar miguelmiguelopenid4java-0.9.6.662/src/0000755001501200150120000000000011627733442014364 5ustar miguelmiguelopenid4java-0.9.6.662/src/overview.html0000644001501200150120000001603711034531517017116 0ustar miguelmiguel

OpenID4Java library offers support for OpenID-enabling a consumer site or implementing an OpenID Provider server.

Consumer Site / Relying Party:

The main interaction points between a web application acting as a Relying Party (Consumer) and the library are the {@link org.openid4java.consumer.ConsumerManager ConsumerManager} and {@link org.openid4java.discovery.Discovery Discovery} classes. A reference {@link org.openid4java.consumer.SampleConsumer SampleConsumer} implementation is provided in the consumer package. See the general usage pattern below.

OpenID Provider / Server:

The main interaction point between a web application acting as a OpenID Provider (Server) and the library is the {@link org.openid4java.server.ServerManager ServerManager} class. A reference {@link org.openid4java.server.SampleServer SampleServer} implementation is provided in the server package. See the general usage pattern below.

Relying Party / Consumer Usage Pattern:

    // instantiate a ConsumerManager object
    public static manager = new ConsumerManager();

    // --- placing the authentication request ---

    // determine a return_to URL where your application will receive
    // the authentication responses from the OpenID provider
    String returnToUrl = "http://example.com/openid";

    // build an Identifier instance from the user-supplied identifier
    Identifier identifier = Discovery.parseIdentifier(userSuppliedString);

    // perform discovery on the user-supplied identifier
    List discoveries = Discovery.discover(identifier);

    // attempt to associate with an OpenID provider
    // and retrieve one service endpoint for authentication
    DiscoveryInformation discovered = manager.associate(discoveries);

    // store the discovery information in the user's session
    session.setAttribute("openid-disco", discovered);

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

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

    // attach the extension to the authentication request
    authReq.addExtensionParams(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 to 255 bytes
        return authReq.getRedirectUrl();
    }
    else
    {
        // Option 2: HTML FORM Redirection
        // Allows payloads > 255 bytes

        // <FORM action="OpenID Provider's service endpoint">
        // see samples/formredirection.jsp for a JSP example
        authReq.getOPEndpoint();

        // build a HTML FORM with the message parameters
        authReq.getParameterMap();
    }

    // --- processing the authentication response

    // 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) session.getAttribute("openid-disco");

    // 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)
    {
        // Attribute Exchange: retrieving the fetched "email" attribute
        AuthSuccess authSuccess = AuthSuccess.createAuthSuccess(response);
        MessageExtension ext =
                authSuccess.getExtension(AxMessage.OPENID_NS_AX);
        if (ext != null)
        {
            FetchResponse fetchResp =
                    new FetchResponse(ext.getParameters());
            String email = fetchResp.getParameter("email");
        }

        return verified;  // success
    }

OpenID Provider / Server Usage Pattern:

    // instantiate a ServerManager object
    public static ServerManager manager = new ServerManager();

    // configure the OpenID Provider's endpoint URL
    static
    {
        manager.setOPEndpointUrl("Http://my.openidprovider.com/server");
    }

    // extract the parameters from the request
    ParameterList request = new ParameterList(httpReq.getParameterMap());

    String mode = request.hasParameter("openid.mode") ?
            request.getParameterValue("openid.mode") : null;

    Message response;
    String responseText;

    if ("associate".equals(mode))
    {
        // --- process an association request ---
        response = manager.associationResponse(request);
        responseText = response.keyValueFormEncoding();
    }
    else if ("checkid_setup".equals(mode)
            || "checkid_immediate".equals(mode))
    {
        // interact with the user and obtain data needed to continue
        List userData = userInteraction(request);

        String userSelectedId = (String) userData.get(0);
        String userSelectedClaimedId = (String) userData.get(1);
        Boolean authenticatedAndApproved = (Boolean) userData.get(2);

        // --- process an authentication request ---
        response = manager.authResponse(request,
                userSelectedId,
                userSelectedClaimedId,
                authenticatedAndApproved.booleanValue());

        // caller will need to decide which of the following to use:
        // - GET HTTP-redirect to the return_to URL
        // - HTML FORM Redirection
        responseText = response.wwwFormEncoding();
    }
    else if ("check_authentication".equals(mode))
    {
        // --- processing a verification request ---
        response = manager.verify(request);
        responseText = response.keyValueFormEncoding();
    }
    else
    {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
    }

    // return the result to the user
    return responseText;

openid4java-0.9.6.662/src/org/0000755001501200150120000000000011034531510015133 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/0000755001501200150120000000000011627733442017357 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/consumer/0000755001501200150120000000000011627733442021212 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/consumer/InMemoryConsumerAssociationStore.java0000644001501200150120000001033411034531517030532 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import org.openid4java.association.Association; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class InMemoryConsumerAssociationStore implements ConsumerAssociationStore { private static Log _log = LogFactory.getLog(InMemoryConsumerAssociationStore.class); private static final boolean DEBUG = _log.isDebugEnabled(); private Map _opMap = new HashMap(); public synchronized void save(String opUrl, Association association) { removeExpired(); Map handleMap = (Map) _opMap.get(opUrl); if (handleMap == null) { handleMap = new HashMap(); _opMap.put(opUrl, handleMap); } String handle = association.getHandle(); if(DEBUG) _log.debug("Adding association to the in-memory store: " + handle + " with OP: " + opUrl); handleMap.put(association.getHandle(), association); } public synchronized Association load(String opUrl, String handle) { removeExpired(); if (_opMap.containsKey(opUrl)) { Map handleMap = (Map) _opMap.get(opUrl); if (handleMap.containsKey(handle)) { return (Association) handleMap.get(handle); } } return null; } public synchronized Association load(String opUrl) { removeExpired(); Association latest = null; if (_opMap.containsKey(opUrl)) { Map handleMap = (Map) _opMap.get(opUrl); Iterator handles = handleMap.keySet().iterator(); while (handles.hasNext()) { String handle = (String) handles.next(); Association association = (Association) handleMap.get(handle); if (latest == null || latest.getExpiry().before(association.getExpiry())) latest = association; } } return latest; } public synchronized void remove(String opUrl, String handle) { removeExpired(); if (_opMap.containsKey(opUrl)) { Map handleMap = (Map) _opMap.get(opUrl); _log.info("Removing association: " + handle + " widh OP: " + opUrl); handleMap.remove(handle); if (handleMap.size() == 0) _opMap.remove(opUrl); } } private synchronized void removeExpired() { Set opToRemove = new HashSet(); Iterator opUrls = _opMap.keySet().iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); Map handleMap = (Map) _opMap.get(opUrl); Set handleToRemove = new HashSet(); Iterator handles = handleMap.keySet().iterator(); while (handles.hasNext()) { String handle = (String) handles.next(); Association association = (Association) handleMap.get(handle); if (association.hasExpired()) { handleToRemove.add(handle); } } handles = handleToRemove.iterator(); while (handles.hasNext()) { String handle = (String) handles.next(); _log.info("Removing expired association: " + handle + " with OP: " + opUrl); handleMap.remove(handle); } if (handleMap.size() == 0) opToRemove.add(opUrl); } opUrls = opToRemove.iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); _opMap.remove(opUrl); } } protected synchronized int size() { int total = 0; Iterator opUrls = _opMap.keySet().iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); Map handleMap = (Map) _opMap.get(opUrl); total += handleMap.size(); } return total; } } openid4java-0.9.6.662/src/org/openid4java/consumer/ConsumerException.java0000644001501200150120000000155111034531517025520 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class ConsumerException extends OpenIDException { public ConsumerException(String message) { super(message, CONSUMER_ERROR); } public ConsumerException(String message, int code) { super(message, code); } public ConsumerException(String message, Throwable cause) { super(message, CONSUMER_ERROR, cause); } public ConsumerException(String message, int code, Throwable cause) { super(message, code, cause); } public ConsumerException(Throwable cause) { super(SERVER_ERROR, cause); } public ConsumerException(int code, Throwable cause) { super(code, cause); } } openid4java-0.9.6.662/src/org/openid4java/consumer/AbstractNonceVerifier.java0000644001501200150120000000435511130536343026274 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import org.openid4java.util.InternetDateFormat; import java.util.Date; import java.text.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public abstract class AbstractNonceVerifier implements NonceVerifier { private static Log _log = LogFactory.getLog(AbstractNonceVerifier.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected static InternetDateFormat _dateFormat = new InternetDateFormat(); protected int _maxAgeSeconds; /** * @param maxAge maximum token age in seconds */ protected AbstractNonceVerifier(int maxAge) { _maxAgeSeconds = maxAge; } public int getMaxAge() { return _maxAgeSeconds; } public void setMaxAge(int ageSeconds) { _maxAgeSeconds = ageSeconds; } /** * Checks if nonce date is valid and if it is in the max age boundary. Other checks are delegated to {@link #seen(java.util.Date, String, String)} */ public synchronized int seen(String opUrl, String nonce) { if (DEBUG) _log.debug("Verifying nonce: " + nonce); Date now = new Date(); try { Date nonceDate = _dateFormat.parse(nonce); if (isTooOld(now, nonceDate)) { _log.warn("Nonce is too old: " + nonce); return TOO_OLD; } return seen(now, opUrl, nonce); } catch (ParseException e) { _log.error("Error verifying the nonce: " + nonce, e); return INVALID_TIMESTAMP; } } /** * Subclasses should implement this method and check if the nonce was seen before. * The nonce timestamp was verified at this point, it is valid and it is in the max age boudary. * * @param now The timestamp used to check the max age boudary. */ protected abstract int seen(Date now, String opUrl, String nonce); protected boolean isTooOld(Date now, Date nonce) { long age = now.getTime() - nonce.getTime(); return age > _maxAgeSeconds * 1000; } } openid4java-0.9.6.662/src/org/openid4java/consumer/VerificationResult.java0000644001501200150120000000460311034531517025670 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import org.openid4java.discovery.Identifier; import org.openid4java.message.MessageException; import org.openid4java.message.Message; /** * @author Marius Scurtescu, Johnny Bufu */ public class VerificationResult { /** * Identifier on which authentication and verification were performed * succesfully and which can be used henceforth by Relying Parties to * identify the user. *

* Null if authentication or verification on the claimed identifier failed. */ private Identifier _verifiedId; /** * Optional parameter returned in a failure response to a immediate * authentication request (AuthImmediateFailure). */ private String _opSetupUrl; /** * The authentication response received from the server. */ private Message _authResponse; /** * An unstructured status / error message. */ private String _statusMsg; /** * Gets the verified identifier. */ public Identifier getVerifiedId() { return _verifiedId; } /** * Sets the verified identifier. */ public void setVerifiedId(Identifier verifiedId) { this._verifiedId = verifiedId; } /** * Gets the optional OP user_setup_url parameter, if one was returned in a * failure response to a immediate authentication request. *

* Null if the response did not include the user_setup_url parameter. */ public String getOPSetupUrl() { return _opSetupUrl; } /** * Sets the OP user_setup_url parameter, if one was returned in a failure * response to a immediate authentication request. */ public void setOPSetupUrl(String opSetupUrl) throws MessageException { this._opSetupUrl = opSetupUrl; } /** * Gets the authentication response message received from the server. */ public Message getAuthResponse() { return _authResponse; } /** * Sets the authentication response message received from the server. */ public void setAuthResponse(Message authResponse) { this._authResponse = authResponse; } public String getStatusMsg() { return _statusMsg; } public void setStatusMsg(String statusMsg) { this._statusMsg = statusMsg; } } openid4java-0.9.6.662/src/org/openid4java/consumer/SampleConsumer.java0000644001501200150120000001605511034531517025010 0ustar miguelmiguel/* * Copyright 2006-2008 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.sreg.SRegMessage; import org.openid4java.message.sreg.SRegRequest; import org.openid4java.message.sreg.SRegResponse; import org.openid4java.message.*; import org.openid4java.OpenIDException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; import java.io.IOException; /** * Sample Consumer (Relying Party) implementation. */ public class SampleConsumer { private ConsumerManager manager; private String returnToUrl; public SampleConsumer() throws ConsumerException { this("http://example.com/openid"); } public SampleConsumer(String returnToUrl) throws ConsumerException { // configure the return_to URL where your application will receive // the authentication responses from the OpenID provider this.returnToUrl = returnToUrl; // instantiate a ConsumerManager object manager = new ConsumerManager(); manager.setAssociations(new InMemoryConsumerAssociationStore()); manager.setNonceVerifier(new InMemoryNonceVerifier(5000)); // for a working demo, not enforcing RP realm discovery // since this new feature is not deployed manager.getRealmVerifier().setEnforceRpId(false); } // --- placing the authentication request --- public String authRequest(String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException { try { // --- 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); // example using Simple Registration to fetching the 'email' attribute SRegRequest sregReq = SRegRequest.createFetchRequest(); sregReq.addAttribute("email", true); authReq.addExtension(sregReq); 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("prameterMap", response.getParameterMap()); //httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false)); //dispatcher.forward(request, response); } } catch (OpenIDException e) { // present error to the user throw new RuntimeException("wrap:" + e.getMessage(), e); } 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(); HttpSession session = httpReq.getSession(true); session.setAttribute("openid_identifier", authSuccess.getIdentity()); if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) { FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX); session.setAttribute("emailFromFetch", fetchResp.getAttributeValues("email").get(0)); } if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) { SRegResponse sregResp = (SRegResponse) authSuccess.getExtension(SRegMessage.OPENID_NS_SREG); session.setAttribute("emailFromSReg", sregResp.getAttributeValue("email")); } return verified; // success } } catch (OpenIDException e) { // present error to the user throw new RuntimeException("wrap:" + e.getMessage(), e); } return null; } } openid4java-0.9.6.662/src/org/openid4java/consumer/package.html0000644001501200150120000001417211034531517023467 0ustar miguelmiguel Provides functionality for OpenID-enabling Consumer (Relying Party) sites.

The general usage pattern for a Consumer site is outlined below:

/*
 * Copyright 2006-2008 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", response.getParameterMap());
                //httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false));
                //dispatcher.forward(request, response);
            }
        }
        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;
    }
}
openid4java-0.9.6.662/src/org/openid4java/consumer/ConsumerAssociationStore.java0000644001501200150120000000104611352263621027053 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import com.google.inject.ImplementedBy; import org.openid4java.association.Association; /** * @author Marius Scurtescu, Johnny Bufu */ @ImplementedBy(InMemoryConsumerAssociationStore.class) public interface ConsumerAssociationStore { public void save(String opUrl, Association association); public Association load(String opUrl, String handle); public Association load(String opUrl); public void remove(String opUrl, String handle); } openid4java-0.9.6.662/src/org/openid4java/consumer/JdbcConsumerAssociationStore.java0000644001501200150120000001667311155267317027661 0ustar miguelmiguel package org.openid4java.consumer ; import java.util.Date; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; /** * * The specified table must have the following structure: * * * @author Andrew Evenson, Graff Haley * @created May 19, 2008 */ public class JdbcConsumerAssociationStore extends JdbcDaoSupport implements ConsumerAssociationStore { private static Log _log = LogFactory.getLog ( JdbcConsumerAssociationStore.class ) ; private String _tableName ; private String _sqlInsert ; private String _sqlDelete ; private String _sqlCleanup ; private String _sqlSelect ; private String _sqlSelectAlt ; public JdbcConsumerAssociationStore ( ) { } public JdbcConsumerAssociationStore ( String tableName ) { setTableName ( tableName ) ; } public String getTableName ( ) { return _tableName ; } public void setTableName ( String tableName ) { this._tableName = tableName ; this._sqlInsert = "INSERT INTO " + _tableName + " VALUES (?,?,?,?,?)" ; this._sqlDelete = "DELETE FROM " + _tableName + " WHERE opurl=? AND handle=?" ; this._sqlCleanup = "DELETE FROM " + _tableName + " WHERE expdate < ?" ; this._sqlSelect = "SELECT * FROM " + _tableName + " WHERE opurl=? AND handle=?" ; this._sqlSelectAlt = "SELECT * FROM " + _tableName + " T1 JOIN (SELECT opurl, max(expdate) AS expdate FROM " + _tableName + " WHERE opurl=? GROUP BY opurl) T2 ON (T1.expdate = T2.expdate AND T1.opurl = T2.opurl)" ; } public Association load ( String opUrl, String handle ) { try { JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; Map res = jdbcTemplate.queryForMap ( _sqlSelect, new Object[] { opUrl, handle } ) ; String type = (String) res.get ( "type" ) ; String macKey = (String) res.get ( "mackey" ) ; Date expDate = (Date) res.get ( "expdate" ) ; if ( type == null || macKey == null || expDate == null ) throw new AssociationException ( "Invalid association data retrived from database; cannot create Association " + "object for handle: " + handle ) ; Association assoc ; if ( Association.TYPE_HMAC_SHA1.equals ( type ) ) assoc = Association.createHmacSha1 ( handle, Base64.decodeBase64 ( macKey.getBytes ( ) ), expDate ) ; else if ( Association.TYPE_HMAC_SHA256.equals ( type ) ) assoc = Association.createHmacSha256 ( handle, Base64.decodeBase64 ( macKey.getBytes ( ) ), expDate ) ; else throw new AssociationException ( "Invalid association type " + "retrieved from database: " + type ) ; if ( _log.isDebugEnabled ( ) ) _log.debug ( "Retrieved association for handle: " + handle + " from table: " + _tableName ) ; return assoc ; } catch ( AssociationException ase ) { _log.error ( "Error retrieving association from table: " + _tableName, ase ) ; return null ; } catch ( IncorrectResultSizeDataAccessException rse ) { _log.warn ( "Association not found for handle: " + handle + " in the table: " + _tableName ) ; return null ; } catch ( DataAccessException dae ) { _log.error ( "Error retrieving association for handle: " + handle + "from table: " + _tableName, dae ) ; return null ; } } public Association load ( String opUrl ) { try { JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; Map res = jdbcTemplate.queryForMap ( _sqlSelectAlt, new Object[] { opUrl } ) ; String handle = (String) res.get ( "handle" ) ; String type = (String) res.get ( "type" ) ; String macKey = (String) res.get ( "mackey" ) ; Date expDate = (Date) res.get ( "expdate" ) ; Association assoc ; if ( expDate == null || ( type == null || macKey == null ) && ! Association.FAILED_ASSOC_HANDLE.equals(handle) ) { throw new AssociationException ( "Invalid expiry date retrived from database; cannot create Association " + "object for handle: " + handle ) ; } else if (Association.FAILED_ASSOC_HANDLE.equals(handle)) { assoc = Association.getFailedAssociation(expDate); } else if ( Association.TYPE_HMAC_SHA1.equals ( type ) ) { assoc = Association.createHmacSha1 ( handle, Base64.decodeBase64 ( macKey.getBytes ( ) ), expDate ) ; } else if ( Association.TYPE_HMAC_SHA256.equals ( type ) ) { assoc = Association.createHmacSha256 ( handle, Base64.decodeBase64 ( macKey.getBytes ( ) ), expDate ) ; } else { throw new AssociationException ( "Invalid association type " + "retrieved from database: " + type ) ; } if ( _log.isDebugEnabled ( ) ) _log.debug ( "Retrieved association for handle: " + handle + " from table: " + _tableName ) ; return assoc ; } catch ( AssociationException ase ) { _log.error ( "Error retrieving association from table: " + _tableName, ase ) ; return null ; } catch ( IncorrectResultSizeDataAccessException rse ) { _log.warn ( "Association not found for opUrl: " + opUrl + " in the table: " + _tableName ) ; return null ; } catch ( DataAccessException dae ) { _log.error ( "Error retrieving association for opUrl: " + opUrl + "from table: " + _tableName, dae ) ; return null ; } } public void remove ( String opUrl, String handle ) { try { JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; int cnt = jdbcTemplate.update ( _sqlDelete, new Object[] { opUrl, handle } ) ; } catch ( Exception e ) { _log.error ( "Error removing association from table: " + _tableName, e ) ; } } public void save ( String opUrl, Association association ) { cleanupExpired ( ) ; try { JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; int cnt = jdbcTemplate.update ( _sqlInsert, new Object[] { opUrl, association.getHandle ( ), association.getType ( ), association.getMacKey ( ) == null ? null : new String ( Base64.encodeBase64 ( association.getMacKey ( ).getEncoded ( ) ) ), association.getExpiry ( ) } ) ; } catch ( Exception e ) { _log.error ( "Error saving association to table: " + _tableName, e ) ; } } private void cleanupExpired ( ) { try { Date boundary = new Date ( ) ; JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; int cnt = jdbcTemplate.update ( _sqlCleanup, new Object[] { boundary } ) ; if ( _log.isDebugEnabled ( ) ) _log.debug ( "Client associations cleanup removed " + cnt + " entries" ) ; } catch ( Exception e ) { _log.error ( "Error cleaning up client associations from table: " + _tableName, e ) ; } } } openid4java-0.9.6.662/src/org/openid4java/consumer/NonceVerifier.java0000644001501200150120000000272211352263621024606 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import com.google.inject.ImplementedBy; /** * @author Marius Scurtescu, Johnny Bufu */ @ImplementedBy(InMemoryNonceVerifier.class) public interface NonceVerifier { /** * This noce is valid and it was not seen before. Nonce should be accepted. */ public static final int OK = 0; /** * The nonce was seen before. Nonce should be rejected. */ public static final int SEEN = 1; /** * The timestamp of the nonce is invalid, it cannot be parsed. Nonce should be rejected. */ public static final int INVALID_TIMESTAMP = 2; /** * The timestamp of the nonce is too old and it is not tracked anymore. Nonce should be rejected. */ public static final int TOO_OLD = 3; /** * Checks if a nonce was seen before. It also checks if the time stamp at the beginning of the noce is valid. * Also, if old nonces are discarded the it should check if the time stamp for this noce is still valid. * * @return {@link #OK} only if this nonce has a valid time stamp, the time stamp did not age and the nonce was not * seen before. */ public int seen(String opUrl, String nonce); /** * Returns the expiration timeout for nonces, in seconds. */ public int getMaxAge(); /** * Sets the expiration timeout for nonces, in seconds. */ public void setMaxAge(int ageSeconds); } openid4java-0.9.6.662/src/org/openid4java/consumer/InMemoryNonceVerifier.java0000644001501200150120000000615611352263621026273 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.*; import java.text.ParseException; /** * @author Marius Scurtescu, Johnny Bufu */ public class InMemoryNonceVerifier extends AbstractNonceVerifier { private static Log _log = LogFactory.getLog(InMemoryNonceVerifier.class); private static final boolean DEBUG = _log.isDebugEnabled(); private Map _opMap = new HashMap(); public InMemoryNonceVerifier() { this(60); } public InMemoryNonceVerifier(int maxAge) { super(maxAge); } protected synchronized int seen(Date now, String opUrl, String nonce) { removeAged(now); Set seenSet = (Set) _opMap.get(opUrl); if (seenSet == null) { seenSet = new HashSet(); _opMap.put(opUrl, seenSet); } if (seenSet.contains(nonce)) { _log.error("Possible replay attack! Already seen nonce: " + nonce); return SEEN; } seenSet.add(nonce); if (DEBUG) _log.debug("Nonce verified: " + nonce); return OK; } private synchronized void removeAged(Date now) { Set opToRemove = new HashSet(); Iterator opUrls = _opMap.keySet().iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); Set seenSet = (Set) _opMap.get(opUrl); Set nonceToRemove = new HashSet(); Iterator nonces = seenSet.iterator(); while (nonces.hasNext()) { String nonce = (String) nonces.next(); try { Date nonceDate = _dateFormat.parse(nonce); if (isTooOld(now, nonceDate)) { nonceToRemove.add(nonce); } } catch (ParseException e) { nonceToRemove.add(nonce); } } nonces = nonceToRemove.iterator(); while (nonces.hasNext()) { String nonce = (String) nonces.next(); if (DEBUG) _log.debug("Removing nonce: " + nonce + " from OP: " + opUrl); seenSet.remove(nonce); } if (seenSet.size() == 0) opToRemove.add(opUrl); } opUrls = opToRemove.iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); if (DEBUG) _log.debug("Removed all nonces from OP: " + opUrl); _opMap.remove(opUrl); } } protected synchronized int size() { int total = 0; Iterator opUrls = _opMap.keySet().iterator(); while (opUrls.hasNext()) { String opUrl = (String) opUrls.next(); Set seenSet = (Set) _opMap.get(opUrl); total += seenSet.size(); } return total; } } openid4java-0.9.6.662/src/org/openid4java/consumer/ConsumerManager.java0000644001501200150120000021025011352263621025133 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import com.google.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.openid4java.OpenIDException; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import org.openid4java.association.AssociationSessionType; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.discovery.Discovery; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.message.AssociationError; import org.openid4java.message.AssociationRequest; import org.openid4java.message.AssociationResponse; import org.openid4java.message.AuthFailure; import org.openid4java.message.AuthImmediateFailure; import org.openid4java.message.AuthRequest; import org.openid4java.message.AuthSuccess; import org.openid4java.message.DirectError; import org.openid4java.message.Message; import org.openid4java.message.MessageException; import org.openid4java.message.ParameterList; import org.openid4java.message.VerifyRequest; import org.openid4java.message.VerifyResponse; import org.openid4java.server.IncrementalNonceGenerator; import org.openid4java.server.NonceGenerator; import org.openid4java.server.RealmVerifier; import org.openid4java.server.RealmVerifierFactory; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.HttpResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Stack; import javax.crypto.spec.DHParameterSpec; /** * Manages OpenID communications with an OpenID Provider (Server). *

* The Consumer site needs to have the same instance of this class throughout * the lifecycle of a OpenID authentication session. * * @author Marius Scurtescu, Johnny Bufu */ public class ConsumerManager { private static Log _log = LogFactory.getLog(ConsumerManager.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Discovery process manager. */ private Discovery _discovery; /** * Direct pointer to HttpFetcher, for association and signature * verification requests. */ private HttpFetcher _httpFetcher; /** * Store for keeping track of the established associations. */ private ConsumerAssociationStore _associations = new InMemoryConsumerAssociationStore(); /** * Consumer-side nonce generator, needed for compatibility with OpenID 1.1. */ private NonceGenerator _consumerNonceGenerator = new IncrementalNonceGenerator(); /** * Private association store used for signing consumer nonces when operating * in compatibility (v1.x) mode. */ private ConsumerAssociationStore _privateAssociations = new InMemoryConsumerAssociationStore(); /** * Verifier for the nonces in authentication responses; * prevents replay attacks. */ private NonceVerifier _nonceVerifier = new InMemoryNonceVerifier(60); // --- association preferences --- /** * Maximum number of attmpts for establishing an association. */ private int _maxAssocAttempts = 4; /** * Flag for enabling or disabling stateless mode. */ private boolean _allowStateless = true; /** * The lowest encryption level session accepted for association sessions. */ private AssociationSessionType _minAssocSessEnc = AssociationSessionType.NO_ENCRYPTION_SHA1MAC; /** * The preferred association session type; will be attempted first. */ private AssociationSessionType _prefAssocSessEnc; /** * Parameters (modulus and generator) for the Diffie-Hellman sessions. */ private DHParameterSpec _dhParams = DiffieHellmanSession.getDefaultParameter(); /** * Timeout (in seconds) for keeping track of failed association attempts. * Default 5 minutes. */ private int _failedAssocExpire = 300; /** * Interval before the expiration of an association (in seconds) * in which the association should not be used, in order to avoid * the expiration from occurring in the middle of an authentication * transaction. Default: 300s. */ private int _preExpiryAssocLockInterval = 300; // --- authentication preferences --- /** * Flag for generating checkid_immediate authentication requests. */ private boolean _immediateAuth = false; /** * Used to perform verify realms against return_to URLs. */ private RealmVerifier _realmVerifier; /** * Instantiates a ConsumerManager with default settings. */ public ConsumerManager() { this( new RealmVerifierFactory(new YadisResolver(new HttpFetcherFactory())), new Discovery(), // uses HttpCache internally new HttpFetcherFactory()); } @Inject public ConsumerManager(RealmVerifierFactory realmFactory, Discovery discovery, HttpFetcherFactory httpFetcherFactory) { _realmVerifier = realmFactory.getRealmVerifierForConsumer(); // don't verify own (RP) identity, disable RP discovery _realmVerifier.setEnforceRpId(false); _discovery = discovery; _httpFetcher = httpFetcherFactory.createFetcher(HttpRequestOptions.getDefaultOptionsForOpCalls()); if (Association.isHmacSha256Supported()) _prefAssocSessEnc = AssociationSessionType.DH_SHA256; else _prefAssocSessEnc = AssociationSessionType.DH_SHA1; } /** * Returns discovery process manager. * * @return discovery process manager. */ public Discovery getDiscovery() { return _discovery; } /** * Sets discovery process manager. * * @param discovery discovery process manager. */ public void setDiscovery(Discovery discovery) { _discovery = discovery; } /** * Gets the association store that holds established associations with * OpenID providers. * * @see ConsumerAssociationStore */ public ConsumerAssociationStore getAssociations() { return _associations; } /** * Configures the ConsumerAssociationStore that will be used to store the * associations established with OpenID providers. * * @param associations ConsumerAssociationStore implementation * @see ConsumerAssociationStore */ @Inject public void setAssociations(ConsumerAssociationStore associations) { this._associations = associations; } /** * Gets the NonceVerifier implementation used to keep track of the nonces * that have been seen in authentication response messages. * * @see NonceVerifier */ public NonceVerifier getNonceVerifier() { return _nonceVerifier; } /** * Configures the NonceVerifier that will be used to keep track of the * nonces in the authentication response messages. * * @param nonceVerifier NonceVerifier implementation * @see NonceVerifier */ @Inject public void setNonceVerifier(NonceVerifier nonceVerifier) { this._nonceVerifier = nonceVerifier; } /** * Sets the Diffie-Hellman base parameters that will be used for encoding * the MAC key exchange. *

* If not provided the default set specified by the Diffie-Hellman algorithm * will be used. * * @param dhParams Object encapsulating modulus and generator numbers * @see DHParameterSpec DiffieHellmanSession */ public void setDHParams(DHParameterSpec dhParams) { this._dhParams = dhParams; } /** * Gets the Diffie-Hellman base parameters (modulus and generator). * * @see DHParameterSpec DiffieHellmanSession */ public DHParameterSpec getDHParams() { return _dhParams; } /** * Maximum number of attempts (HTTP calls) the RP is willing to make * for trying to establish an association with the OP. * * Default: 4; * 0 = don't use associations * * Associations and stateless mode cannot be both disabled at the same time. */ public void setMaxAssocAttempts(int maxAssocAttempts) { if (maxAssocAttempts > 0 || _allowStateless) this._maxAssocAttempts = maxAssocAttempts; else throw new IllegalArgumentException( "Associations and stateless mode " + "cannot be both disabled at the same time."); if (_maxAssocAttempts == 0) _log.info("Associations disabled."); } /** * Gets the value configured for the maximum number of association attempts * that will be performed for a given OpenID provider. *

* If an association cannot be established after this number of attempts the * ConsumerManager will fallback to stateless mode, provided the * #allowStateless preference is enabled. *

* See also: {@link #allowStateless(boolean)} {@link #statelessAllowed()} */ public int getMaxAssocAttempts() { return _maxAssocAttempts; } /** * Flag used to enable / disable the use of stateless mode. *

* Default: enabled. *

* Associations and stateless mode cannot be both disabled at the same time. * @deprecated * @see #setAllowStateless(boolean) */ public void allowStateless(boolean allowStateless) { setAllowStateless(allowStateless); } /** * Flag used to enable / disable the use of stateless mode. *

* Default: enabled. *

* Associations and stateless mode cannot be both disabled at the same time. */ public void setAllowStateless(boolean allowStateless) { if (_allowStateless || _maxAssocAttempts > 0) this._allowStateless = allowStateless; else throw new IllegalArgumentException( "Associations and stateless mode " + "cannot be both disabled at the same time."); } /** * Returns true if the ConsumerManager is configured to fallback to * stateless mode when failing to associate with an OpenID Provider. * * @deprecated * @see #isAllowStateless() */ public boolean statelessAllowed() { return _allowStateless; } /** * Returns true if the ConsumerManager is configured to fallback to * stateless mode when failing to associate with an OpenID Provider. */ public boolean isAllowStateless() { return _allowStateless; } /** * Configures the minimum level of encryption accepted for association * sessions. *

* Default: no-encryption session, SHA1 MAC association. *

* See also: {@link #allowStateless(boolean)} */ public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc) { this._minAssocSessEnc = minAssocSessEnc; } /** * Gets the minimum level of encryption that will be accepted for * association sessions. *

* Default: no-encryption session, SHA1 MAC association *

*/ public AssociationSessionType getMinAssocSessEnc() { return _minAssocSessEnc; } /** * Sets the preferred encryption type for the association sessions. *

* Default: DH-SHA256 */ public void setPrefAssocSessEnc(AssociationSessionType prefAssocSessEnc) { this._prefAssocSessEnc = prefAssocSessEnc; } /** * Gets the preferred encryption type for the association sessions. */ public AssociationSessionType getPrefAssocSessEnc() { return _prefAssocSessEnc; } /** * Sets the expiration timeout (in seconds) for keeping track of failed * association attempts. *

* If an association cannot be establish with an OP, subsequesnt * authentication request to that OP will not try to establish an * association within the timeout period configured here. *

* Default: 300s * 0 = disabled (attempt to establish an association with every * authentication request) * * @param _failedAssocExpire time in seconds to remember failed * association attempts */ public void setFailedAssocExpire(int _failedAssocExpire) { this._failedAssocExpire = _failedAssocExpire; } /** * Gets the timeout (in seconds) configured for keeping track of failed * association attempts. *

* See also: {@link #setFailedAssocExpire(int)} */ public int getFailedAssocExpire() { return _failedAssocExpire; } /** * Gets the interval before the expiration of an association * (in seconds) in which the association should not be used, * in order to avoid the expiration from occurring in the middle * of a authentication transaction. Default: 300s. */ public int getPreExpiryAssocLockInterval() { return _preExpiryAssocLockInterval; } /** * Sets the interval before the expiration of an association * (in seconds) in which the association should not be used, * in order to avoid the expiration from occurring in the middle * of a authentication transaction. Default: 300s. * * @param preExpiryAssocLockInterval The number of seconds for the * pre-expiry lock inteval. */ public void setPreExpiryAssocLockInterval(int preExpiryAssocLockInterval) { this._preExpiryAssocLockInterval = preExpiryAssocLockInterval; } /** * Configures the authentication request mode: * checkid_immediate (true) or checkid_setup (false). *

* Default: false / checkid_setup */ public void setImmediateAuth(boolean _immediateAuth) { this._immediateAuth = _immediateAuth; } /** * Returns true if the ConsumerManager is configured to attempt * checkid_immediate authentication requests. *

* Default: false */ public boolean isImmediateAuth() { return _immediateAuth; } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } /** * Gets the max age (in seconds) configured for keeping track of nonces. *

* Nonces older than the max age will be removed from the store and * authentication responses will be considered failures. */ public int getMaxNonceAge() { return _nonceVerifier.getMaxAge(); } /** * Sets the max age (in seconds) configured for keeping track of nonces. *

* Nonces older than the max age will be removed from the store and * authentication responses will be considered failures. */ public void setMaxNonceAge(int ageSeconds) { _nonceVerifier.setMaxAge(ageSeconds); } /** * Does discovery on an identifier. It delegates the call to its * discovery manager. * * @return A List of {@link DiscoveryInformation} objects. * The list could be empty if no discovery information can * be retrieved. * * @throws DiscoveryException if the discovery process runs into errors. */ public List discover(String identifier) throws DiscoveryException { return _discovery.discover(identifier); } /** * Configures a private association store for signing consumer nonces. *

* Consumer nonces are needed to prevent replay attacks in compatibility * mode, because OpenID 1.x Providers to not attach nonces to * authentication responses. *

* One way for the Consumer to know that a consumer nonce in an * authentication response was indeed issued by itself (and thus prevent * denial of service attacks), is by signing them. * * @param associations The association store to be used for signing consumer nonces; * signing can be deactivated by setting this to null. * Signing is enabled by default. */ public void setPrivateAssociationStore(ConsumerAssociationStore associations) throws ConsumerException { if (associations == null) throw new ConsumerException( "Cannot set null private association store, " + "needed for consumer nonces."); _privateAssociations = associations; } /** * Gets the private association store used for signing consumer nonces. * * @see #setPrivateAssociationStore(ConsumerAssociationStore) */ public ConsumerAssociationStore getPrivateAssociationStore() { return _privateAssociations; } public void setConnectTimeout(int connectTimeout) { _httpFetcher.getDefaultRequestOptions() .setConnTimeout(connectTimeout); } public void setSocketTimeout(int socketTimeout) { _httpFetcher.getDefaultRequestOptions() .setSocketTimeout(socketTimeout); } public void setMaxRedirects(int maxRedirects) { _httpFetcher.getDefaultRequestOptions() .setMaxRedirects(maxRedirects); } /** * Makes a HTTP call to the specified URL with the parameters specified * in the Message. * * @param url URL endpoint for the HTTP call * @param request Message containing the parameters * @param response ParameterList that will hold the parameters received in * the HTTP response * @return the status code of the HTTP call */ private int call(String url, Message request, ParameterList response) throws MessageException { int responseCode = -1; try { if (DEBUG) _log.debug("Performing HTTP POST on " + url); HttpResponse resp = _httpFetcher.post(url, request.getParameterMap()); responseCode = resp.getStatusCode(); String postResponse = resp.getBody(); response.copyOf(ParameterList.createFromKeyValueForm(postResponse)); if (DEBUG) _log.debug("Retrived response:\n" + postResponse); } catch (IOException e) { _log.error("Error talking to " + url + " response code: " + responseCode, e); } return responseCode; } /** * Tries to establish an association with on of the service endpoints in * the list of DiscoveryInformation. *

* Iterates over the items in the discoveries parameter a maximum of * #_maxAssocAttempts times trying to esablish an association. * * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @return The DiscoveryInformation instance with which * an association was established, or the one * with the highest priority if association failed. * * @see Discovery#discover(org.openid4java.discovery.Identifier) */ public DiscoveryInformation associate(List discoveries) { DiscoveryInformation discovered; Association assoc; int attemptsLeft = _maxAssocAttempts; Iterator itr = discoveries.iterator(); while (itr.hasNext() && attemptsLeft > 0) { discovered = (DiscoveryInformation) itr.next(); attemptsLeft -= associate(discovered, attemptsLeft); // check if an association was established assoc = _associations.load(discovered.getOPEndpoint().toString()); if ( assoc != null && ! Association.FAILED_ASSOC_HANDLE.equals(assoc.getHandle())) return discovered; } if (discoveries.size() > 0) { // no association established, return the first service endpoint DiscoveryInformation d0 = (DiscoveryInformation) discoveries.get(0); _log.warn("Association failed; using first entry: " + d0.getOPEndpoint()); return d0; } else { _log.error("Association attempt, but no discovey endpoints provided."); return null; } } /** * Tries to establish an association with the OpenID Provider. *

* The resulting association information will be kept on storage for later * use at verification stage. If there exists an association for the opUrl * that is not near expiration, will not construct new association. * * @param discovered DiscoveryInformation obtained during the discovery * @return The number of association attempts performed. */ private int associate(DiscoveryInformation discovered, int maxAttempts) { if (_maxAssocAttempts == 0) return 0; // associations disabled URL opUrl = discovered.getOPEndpoint(); String opEndpoint = opUrl.toString(); _log.info("Trying to associate with " + opEndpoint + " attempts left: " + maxAttempts); // check if there's an already established association Association a = _associations.load(opEndpoint); if ( a != null && (Association.FAILED_ASSOC_HANDLE.equals(a.getHandle()) || a.getExpiry().getTime() - System.currentTimeMillis() > _preExpiryAssocLockInterval * 1000) ) { _log.info("Found an existing association: " + a.getHandle()); return 0; } String handle = Association.FAILED_ASSOC_HANDLE; // build a list of association types, with the preferred one at the end LinkedHashMap requests = new LinkedHashMap(); if (discovered.isVersion2()) { requests.put(AssociationSessionType.NO_ENCRYPTION_SHA1MAC, null); requests.put(AssociationSessionType.NO_ENCRYPTION_SHA256MAC, null); requests.put(AssociationSessionType.DH_SHA1, null); requests.put(AssociationSessionType.DH_SHA256, null); } else { requests.put(AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC, null); requests.put(AssociationSessionType.DH_COMPAT_SHA1, null); } if (_prefAssocSessEnc.isVersion2() == discovered.isVersion2()) requests.put(_prefAssocSessEnc, null); // build a stack of Association Request objects // and keep only the allowed by the configured preferences // the most-desirable entry is always at the top of the stack Stack reqStack = new Stack(); Iterator iter = requests.keySet().iterator(); while(iter.hasNext()) { AssociationSessionType type = (AssociationSessionType) iter.next(); // create the appropriate Association Request AssociationRequest newReq = createAssociationRequest(type, opUrl); if (newReq != null) reqStack.push(newReq); } // perform the association attempts int attemptsLeft = maxAttempts; LinkedHashMap alreadyTried = new LinkedHashMap(); while (attemptsLeft > 0 && ! reqStack.empty()) { try { attemptsLeft--; AssociationRequest assocReq = (AssociationRequest) reqStack.pop(); if (DEBUG) _log.debug("Trying association type: " + assocReq.getType()); // was this association / session type attempted already? if (alreadyTried.keySet().contains(assocReq.getType())) { if (DEBUG) _log.debug("Already tried."); continue; } // mark the current request type as already tried alreadyTried.put(assocReq.getType(), null); ParameterList respParams = new ParameterList(); int status = call(opEndpoint, assocReq, respParams); // process the response if (status == HttpStatus.SC_OK) // success response { AssociationResponse assocResp; assocResp = AssociationResponse .createAssociationResponse(respParams); // valid association response Association assoc = assocResp.getAssociation(assocReq.getDHSess()); handle = assoc.getHandle(); AssociationSessionType respType = assocResp.getType(); if ( respType.equals(assocReq.getType()) || // v1 OPs may return a success no-encryption resp ( ! discovered.isVersion2() && respType.getHAlgorithm() == null && createAssociationRequest(respType,opUrl) != null)) { // store the association and do no try alternatives _associations.save(opEndpoint, assoc); _log.info("Associated with " + discovered.getOPEndpoint() + " handle: " + assoc.getHandle()); break; } else _log.info("Discarding association response, " + "not matching consumer criteria"); } else if (status == HttpStatus.SC_BAD_REQUEST) // error response { _log.info("Association attempt failed."); // retrieve fallback sess/assoc/encryption params set by OP // and queue a new attempt AssociationError assocErr = AssociationError.createAssociationError(respParams); AssociationSessionType opType = AssociationSessionType.create( assocErr.getSessionType(), assocErr.getAssocType()); if (alreadyTried.keySet().contains(opType)) continue; // create the appropriate Association Request AssociationRequest newReq = createAssociationRequest(opType, opUrl); if (newReq != null) { if (DEBUG) _log.debug("Retrieved association type " + "from the association error: " + newReq.getType()); reqStack.push(newReq); } } } catch (OpenIDException e) { _log.error("Error encountered during association attempt.", e); } } // store OPs with which an association could not be established // so that association attempts are not performed with each auth request if (Association.FAILED_ASSOC_HANDLE.equals(handle) && _failedAssocExpire > 0) _associations.save(opEndpoint, Association.getFailedAssociation(_failedAssocExpire)); return maxAttempts - attemptsLeft; } /** * Constructs an Association Request message of the specified session and * association type, taking into account the user preferences (encryption * level, default Diffie-Hellman parameters). * * @param type The type of the association (session and association) * @param opUrl The OP for which the association request is created * @return An AssociationRequest message ready to be sent back * to the OpenID Provider, or null if an association * of the requested type cannot be built. */ private AssociationRequest createAssociationRequest( AssociationSessionType type, URL opUrl) { try { if (_minAssocSessEnc.isBetter(type)) return null; AssociationRequest assocReq = null; DiffieHellmanSession dhSess; if (type.getHAlgorithm() != null) // DH session { dhSess = DiffieHellmanSession.create(type, _dhParams); if (DiffieHellmanSession.isDhSupported(type) && Association.isHmacSupported(type.getAssociationType())) assocReq = AssociationRequest.createAssociationRequest(type, dhSess); } else if ( opUrl.getProtocol().equals("https") && // no-enc sess Association.isHmacSupported(type.getAssociationType())) assocReq = AssociationRequest.createAssociationRequest(type); if (assocReq == null) _log.warn("Could not create association of type: " + type); return assocReq; } catch (OpenIDException e) { _log.error("Error trying to create association request.", e); return null; } } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. *

* If the discoveries parameter contains more than one entry, it will * iterate over them trying to establish an association. If an association * cannot be established, the first entry is used with stateless mode. * * @see #associate(java.util.List) * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response.
* Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension).
* Must not be null in OpenID 1.x compatibility * mode. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(List discoveries, String returnToUrl) throws ConsumerException, MessageException { return authenticate(discoveries, returnToUrl, returnToUrl); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. *

* If the discoveries parameter contains more than one entry, it will * iterate over them trying to establish an association. If an association * cannot be established, the first entry is used with stateless mode. * * @see #associate(java.util.List) * @param discoveries The DiscoveryInformation list obtained by * performing dicovery on the User-supplied OpenID * identifier. Should be ordered by the priority * of the service endpoints. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response.
* Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension).
* Must not be null in OpenID 1.x compatibility * mode. * @param realm The URL pattern that will be presented to the * user when he/she will be asked to authorize the * authentication transaction. Must be a super-set * of the @returnToUrl. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(List discoveries, String returnToUrl, String realm) throws ConsumerException, MessageException { // try to associate with one OP in the discovered list DiscoveryInformation discovered = associate(discoveries); return authenticate(discovered, returnToUrl, realm); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * * @param discovered A DiscoveryInformation endpoint from the list * obtained by performing dicovery on the * User-supplied OpenID identifier. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response.
* Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension).
* Must not be null in OpenID 1.x compatibility * mode. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(DiscoveryInformation discovered, String returnToUrl) throws MessageException, ConsumerException { return authenticate(discovered, returnToUrl, returnToUrl); } /** * Builds a authentication request message for the user specified in the * discovery information provided as a parameter. * * @param discovered A DiscoveryInformation endpoint from the list * obtained by performing dicovery on the * User-supplied OpenID identifier. * @param returnToUrl The URL on the Consumer site where the OpenID * Provider will return the user after generating * the authentication response.
* Null if the Consumer does not with to for the * End User to be returned to it (something else * useful will have been performed via an * extension).
* Must not be null in OpenID 1.x compatibility * mode. * @param realm The URL pattern that will be presented to the * user when he/she will be asked to authorize the * authentication transaction. Must be a super-set * of the @returnToUrl. * @return Authentication request message to be sent to the * OpenID Provider. */ public AuthRequest authenticate(DiscoveryInformation discovered, String returnToUrl, String realm) throws MessageException, ConsumerException { if (discovered == null) throw new ConsumerException("Authentication cannot continue: " + "no discovery information provided."); Association assoc = _associations.load(discovered.getOPEndpoint().toString()); if (assoc == null) { associate(discovered, _maxAssocAttempts); assoc = _associations.load(discovered.getOPEndpoint().toString()); } String handle = assoc != null ? assoc.getHandle() : Association.FAILED_ASSOC_HANDLE; // get the Claimed ID and Delegate ID (aka OP-specific identifier) String claimedId, delegate; if (discovered.hasClaimedIdentifier()) { claimedId = discovered.getClaimedIdentifier().getIdentifier(); delegate = discovered.hasDelegateIdentifier() ? discovered.getDelegateIdentifier() : claimedId; } else { claimedId = AuthRequest.SELECT_ID; delegate = AuthRequest.SELECT_ID; } // stateless mode disabled ? if ( !_allowStateless && Association.FAILED_ASSOC_HANDLE.equals(handle)) throw new ConsumerException("Authentication cannot be performed: " + "no association available and stateless mode is disabled"); _log.info("Creating authentication request for" + " OP-endpoint: " + discovered.getOPEndpoint() + " claimedID: " + claimedId + " OP-specific ID: " + delegate); if (! discovered.isVersion2()) returnToUrl = insertConsumerNonce(discovered.getOPEndpoint().toString(), returnToUrl); AuthRequest authReq = AuthRequest.createAuthRequest(claimedId, delegate, ! discovered.isVersion2(), returnToUrl, handle, realm, _realmVerifier); authReq.setOPEndpoint(discovered.getOPEndpoint()); // ignore the immediate flag for OP-directed identifier selection if (! AuthRequest.SELECT_ID.equals(claimedId)) authReq.setImmediate(_immediateAuth); return authReq; } /** * Performs verification on the Authentication Response (assertion) * received from the OpenID Provider. *

* Three verification steps are performed: *

* * @param receivingUrl The URL where the Consumer (Relying Party) has * accepted the incoming message. * @param response ParameterList of the authentication response * being verified. * @param discovered Previously discovered information (which can * therefore be trusted) obtained during the discovery * phase; this should be stored and retrieved by the RP * in the user's session. * * @return A VerificationResult, containing a verified * identifier; the verified identifier is null if * the verification failed). */ public VerificationResult verify(String receivingUrl, ParameterList response, DiscoveryInformation discovered) throws MessageException, DiscoveryException, AssociationException { VerificationResult result = new VerificationResult(); _log.info("Verifying authentication response..."); // non-immediate negative response if ( "cancel".equals(response.getParameterValue("openid.mode")) ) { result.setAuthResponse(AuthFailure.createAuthFailure(response)); _log.info("Received auth failure."); return result; } // immediate negative response if ( "setup_needed".equals(response.getParameterValue("openid.mode")) || ("id_res".equals(response.getParameterValue("openid.mode")) && response.hasParameter("openid.user_setup_url") ) ) { AuthImmediateFailure fail = AuthImmediateFailure.createAuthImmediateFailure(response); result.setAuthResponse(fail); result.setOPSetupUrl(fail.getUserSetupUrl()); _log.info("Received auth immediate failure."); return result; } AuthSuccess authResp = AuthSuccess.createAuthSuccess(response); _log.info("Received positive auth response."); authResp.validate(); result.setAuthResponse(authResp); // [1/4] return_to verification if (! verifyReturnTo(receivingUrl, authResp)) { result.setStatusMsg("Return_To URL verification failed."); _log.error("Return_To URL verification failed."); return result; } // [2/4] : discovered info verification discovered = verifyDiscovered(authResp, discovered); if (discovered == null || ! discovered.hasClaimedIdentifier()) { result.setStatusMsg("Discovered information verification failed."); _log.error("Discovered information verification failed."); return result; } // [3/4] : nonce verification if (! verifyNonce(authResp, discovered)) { result.setStatusMsg("Nonce verification failed."); _log.error("Nonce verification failed."); return result; } // [4/4] : signature verification return (verifySignature(authResp, discovered, result)); } /** * Verifies that the URL where the Consumer (Relying Party) received the * authentication response matches the value of the "openid.return_to" * parameter in the authentication response. * * @param receivingUrl The URL where the Consumer received the * authentication response. * @param response The authentication response. * @return True if the two URLs match, false otherwise. */ public boolean verifyReturnTo(String receivingUrl, AuthSuccess response) { if (DEBUG) _log.debug("Verifying return URL; receiving: " + receivingUrl + "\nmessage: " + response.getReturnTo()); URL receiving; URL returnTo; try { receiving = new URL(receivingUrl); returnTo = new URL(response.getReturnTo()); } catch (MalformedURLException e) { _log.error("Invalid return URL.", e); return false; } // [1/2] schema, authority (includes port) and path // deal manually with the trailing slash in the path StringBuffer receivingPath = new StringBuffer(receiving.getPath()); if ( receivingPath.length() > 0 && receivingPath.charAt(receivingPath.length() -1) != '/') receivingPath.append('/'); StringBuffer returnToPath = new StringBuffer(returnTo.getPath()); if ( returnToPath.length() > 0 && returnToPath.charAt(returnToPath.length() -1) != '/') returnToPath.append('/'); if ( ! receiving.getProtocol().equals(returnTo.getProtocol()) || ! receiving.getAuthority().equals(returnTo.getAuthority()) || ! receivingPath.toString().equals(returnToPath.toString()) ) { if (DEBUG) _log.debug("Return URL schema, authority or " + "path verification failed."); return false; } // [2/2] query parameters try { Map returnToParams = extractQueryParams(returnTo); Map receivingParams = extractQueryParams(receiving); if (returnToParams == null) return true; if (receivingParams == null) { if (DEBUG) _log.debug("Return URL query parameters verification failed."); return false; } Iterator iter = returnToParams.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); List receivingValues = (List) receivingParams.get(key); List returnToValues = (List) returnToParams.get(key); if ( receivingValues == null || receivingValues.size() != returnToValues.size() || ! receivingValues.containsAll( returnToValues ) ) { if (DEBUG) _log.debug("Return URL query parameters verification failed."); return false; } } } catch (UnsupportedEncodingException e) { _log.error("Error verifying return URL query parameters.", e); return false; } return true; } /** * Returns a Map(key, List(values)) with the URL's query params, or null if * the URL doesn't have a query string. */ public Map extractQueryParams(URL url) throws UnsupportedEncodingException { if (url.getQuery() == null) return null; Map paramsMap = new HashMap(); List paramList = Arrays.asList(url.getQuery().split("&")); Iterator iter = paramList.iterator(); while (iter.hasNext()) { String keyValue = (String) iter.next(); int equalPos = keyValue.indexOf("="); String key = equalPos > -1 ? URLDecoder.decode(keyValue.substring(0, equalPos), "UTF-8") : URLDecoder.decode(keyValue, "UTF-8"); String value; if (equalPos <= -1) value = null; else if (equalPos + 1 > keyValue.length()) value = ""; else value = URLDecoder.decode(keyValue.substring(equalPos + 1), "UTF-8"); List existingValues = (List) paramsMap.get(key); if (existingValues == null) { List newValues = new ArrayList(); newValues.add(value); paramsMap.put(key, newValues); } else existingValues.add(value); } return paramsMap; } /** * Verifies the nonce in an authentication response. * * @param authResp The authentication response containing the nonce * to be verified. * @param discovered The discovery information associated with the * authentication transaction. * @return True if the nonce is valid, false otherwise. */ public boolean verifyNonce(AuthSuccess authResp, DiscoveryInformation discovered) { String nonce = authResp.getNonce(); if (nonce == null) // compatibility mode nonce = extractConsumerNonce(authResp.getReturnTo(), discovered.getOPEndpoint().toString()); if (nonce == null) return false; // using the same nonce verifier for both server and consumer nonces return (NonceVerifier.OK == _nonceVerifier.seen( discovered.getOPEndpoint().toString(), nonce)); } /** * Inserts a consumer-side nonce as a custom parameter in the return_to * parameter of the authentication request. *

* Needed for preventing replay attack when running compatibility mode. * OpenID 1.1 OpenID Providers do not generate nonces in authentication * responses. * * @param opUrl The endpoint to be used for private association. * @param returnTo The return_to URL to which a custom nonce * parameter will be added. * @return The return_to URL containing the nonce. */ public String insertConsumerNonce(String opUrl, String returnTo) { String nonce = _consumerNonceGenerator.next(); returnTo += (returnTo.indexOf('?') != -1) ? '&' : '?'; Association privateAssoc = _privateAssociations.load(opUrl); if( privateAssoc == null ) { try { if (DEBUG) _log.debug( "Creating private association for opUrl " + opUrl); privateAssoc = Association.generate( getPrefAssocSessEnc().getAssociationType(), "", _failedAssocExpire); _privateAssociations.save( opUrl, privateAssoc ); } catch ( AssociationException e ) { _log.error("Cannot initialize private association.", e); return null; } } try { returnTo += "openid.rpnonce=" + URLEncoder.encode(nonce, "UTF-8"); returnTo += "&openid.rpsig=" + URLEncoder.encode(privateAssoc.sign(returnTo), "UTF-8"); _log.info("Inserted consumer nonce: " + nonce); if (DEBUG) _log.debug("return_to:" + returnTo); } catch (Exception e) { _log.error("Error inserting consumre nonce.", e); return null; } return returnTo; } /** * Extracts the consumer-side nonce from the return_to parameter in * authentication response from a OpenID 1.1 Provider. * * @param returnTo return_to URL from the authentication response * @param opUrl URL for the appropriate OP endpoint * @return The nonce found in the return_to URL, or null if * it wasn't found. */ public String extractConsumerNonce(String returnTo, String opUrl) { if (DEBUG) _log.debug("Extracting consumer nonce..."); String nonce = null; String signature = null; URL returnToUrl; try { returnToUrl = new URL(returnTo); } catch (MalformedURLException e) { _log.error("Invalid return_to: " + returnTo, e); return null; } String query = returnToUrl.getQuery(); String[] params = query.split("&"); for (int i=0; i < params.length; i++) { String keyVal[] = params[i].split("=", 2); try { if (keyVal.length == 2 && "openid.rpnonce".equals(keyVal[0])) { nonce = URLDecoder.decode(keyVal[1], "UTF-8"); if (DEBUG) _log.debug("Extracted consumer nonce: " + nonce); } if (keyVal.length == 2 && "openid.rpsig".equals(keyVal[0])) { signature = URLDecoder.decode(keyVal[1], "UTF-8"); if (DEBUG) _log.debug("Extracted consumer nonce signature: " + signature); } } catch (UnsupportedEncodingException e) { _log.error("Error extracting consumer nonce / signarure.", e); return null; } } // check the signature if (signature == null) { _log.error("Null consumer nonce signature."); return null; } String signed = returnTo.substring(0, returnTo.indexOf("&openid.rpsig=")); if (DEBUG) _log.debug("Consumer signed text:\n" + signed); try { if (DEBUG) _log.debug( "Loading private association for opUrl " + opUrl ); Association privateAssoc = _privateAssociations.load(opUrl); if( privateAssoc == null ) { _log.error("Null private association."); return null; } if (privateAssoc.verifySignature(signed, signature)) { _log.info("Consumer nonce signature verified."); return nonce; } else { _log.error("Consumer nonce signature failed."); return null; } } catch (AssociationException e) { _log.error("Error verifying consumer nonce signature.", e); return null; } } /** * Verifies the dicovery information matches the data received in a * authentication response from an OpenID Provider. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. Stateless operation * is assumed if null. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if (authResp == null || authResp.getIdentity() == null) { _log.info("Assertion is not about an identifier"); return null; } if (authResp.isVersion2()) return verifyDiscovered2(authResp, discovered); else return verifyDiscovered1(authResp, discovered); } /** * Verifies the discovered information associated with a OpenID 1.x * response. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. Stateless operation * is assumed if null. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered1(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if ( authResp == null || authResp.isVersion2() || authResp.getIdentity() == null ) { if (DEBUG) _log.error("Invalid authentication response: " + "cannot verify v1 discovered information"); return null; } // asserted identifier in the AuthResponse String assertId = authResp.getIdentity(); if ( discovered != null && ! discovered.isVersion2() && discovered.getClaimedIdentifier() != null ) { // statefull mode if (DEBUG) _log.debug("Verifying discovered information " + "for OpenID1 assertion about ClaimedID: " + discovered.getClaimedIdentifier().getIdentifier()); String discoveredId = discovered.hasDelegateIdentifier() ? discovered.getDelegateIdentifier() : discovered.getClaimedIdentifier().getIdentifier(); if (assertId.equals(discoveredId)) return discovered; } // stateless, bare response, or the user changed the ID at the OP _log.info("Proceeding with stateless mode / bare response verification..."); DiscoveryInformation firstServiceMatch = null; // assuming openid.identity is the claimedId // (delegation can't work with stateless/bare resp v1 operation) if (DEBUG) _log.debug( "Performing discovery on the ClaimedID in the assertion: " + assertId); List discoveries = _discovery.discover(assertId); Iterator iter = discoveries.iterator(); while (iter.hasNext()) { DiscoveryInformation service = (DiscoveryInformation) iter.next(); if (service.isVersion2() || // only interested in v1 ! service.hasClaimedIdentifier() || // need a claimedId service.hasDelegateIdentifier() || // not allowing delegates ! assertId.equals(service.getClaimedIdentifier().getIdentifier())) continue; if (DEBUG) _log.debug("Found matching service: " + service); // keep the first endpoint that matches if (firstServiceMatch == null) firstServiceMatch = service; Association assoc = _associations.load( service.getOPEndpoint().toString(), authResp.getHandle()); // don't look further if there is an association with this endpoint if (assoc != null) { if (DEBUG) _log.debug("Found existing association for " + service + " Not looking for another service endpoint."); return service; } } if (firstServiceMatch == null) _log.error("No service element found to match " + "the identifier in the assertion."); return firstServiceMatch; } /** * Verifies the discovered information associated with a OpenID 2.0 * response. * * @param authResp The authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage, associated with the * identifier(s) in the request. Stateless operation * is assumed if null. * @return The discovery information associated with the * claimed identifier, that can be used further in * the verification process. Null if the discovery * on the claimed identifier does not match the data * in the assertion. */ private DiscoveryInformation verifyDiscovered2(AuthSuccess authResp, DiscoveryInformation discovered) throws DiscoveryException { if (authResp == null || ! authResp.isVersion2() || authResp.getIdentity() == null || authResp.getClaimed() == null) { if (DEBUG) _log.debug("Discovered information doesn't match " + "auth response / version"); return null; } // asserted identifier in the AuthResponse String assertId = authResp.getIdentity(); // claimed identifier in the AuthResponse Identifier respClaimed = _discovery.parseIdentifier(authResp.getClaimed(), true); // the OP endpoint sent in the response String respEndpoint = authResp.getOpEndpoint(); if (DEBUG) _log.debug("Verifying discovered information for OpenID2 assertion " + "about ClaimedID: " + respClaimed.getIdentifier()); // was the claimed identifier in the assertion previously discovered? if (discovered != null && discovered.hasClaimedIdentifier() && discovered.getClaimedIdentifier().equals(respClaimed) ) { // OP-endpoint, OP-specific ID and protocol version must match String opSpecific = discovered.hasDelegateIdentifier() ? discovered.getDelegateIdentifier() : discovered.getClaimedIdentifier().getIdentifier(); if ( opSpecific.equals(assertId) && discovered.isVersion2() && discovered.getOPEndpoint().toString().equals(respEndpoint)) { if (DEBUG) _log.debug( "ClaimedID in the assertion was previously discovered: " + respClaimed); return discovered; } } // stateless, bare response, or the user changed the ID at the OP DiscoveryInformation firstServiceMatch = null; // perform discovery on the claim identifier in the assertion if(DEBUG) _log.debug( "Performing discovery on the ClaimedID in the assertion: " + respClaimed); List discoveries = _discovery.discover(respClaimed); // find the newly discovered service endpoint that matches the assertion // - OP endpoint, OP-specific ID and protocol version must match // - prefer (first = highest priority) endpoint with an association if (DEBUG) _log.debug("Looking for a service element to match " + "the ClaimedID and OP endpoint in the assertion..."); Iterator iter = discoveries.iterator(); while (iter.hasNext()) { DiscoveryInformation service = (DiscoveryInformation) iter.next(); if (DiscoveryInformation.OPENID2_OP.equals(service.getVersion())) continue; String opSpecific = service.hasDelegateIdentifier() ? service.getDelegateIdentifier() : service.getClaimedIdentifier().getIdentifier(); if ( ! opSpecific.equals(assertId) || ! service.isVersion2() || ! service.getOPEndpoint().toString().equals(respEndpoint) ) continue; // keep the first endpoint that matches if (firstServiceMatch == null) { if (DEBUG) _log.debug("Found matching service: " + service); firstServiceMatch = service; } Association assoc = _associations.load( service.getOPEndpoint().toString(), authResp.getHandle()); // don't look further if there is an association with this endpoint if (assoc != null) { if (DEBUG) _log.debug("Found existing association, " + "not looking for another service endpoint."); return service; } } if (firstServiceMatch == null) _log.error("No service element found to match " + "the ClaimedID / OP-endpoint in the assertion."); return firstServiceMatch; } /** * Verifies the signature in a authentication response message. * * @param authResp Authentication response to be verified. * @param discovered The discovery information obtained earlier during * the discovery stage. * @return True if the verification succeeded, false otherwise. */ private VerificationResult verifySignature(AuthSuccess authResp, DiscoveryInformation discovered, VerificationResult result) throws AssociationException, MessageException, DiscoveryException { if (discovered == null || authResp == null) { _log.error("Can't verify signature: " + "null assertion or discovered information."); result.setStatusMsg("Can't verify signature: " + "null assertion or discovered information."); return result; } Identifier claimedId = discovered.isVersion2() ? _discovery.parseIdentifier(authResp.getClaimed()) : //may have frag discovered.getClaimedIdentifier(); //assert id may be delegate in v1 String handle = authResp.getHandle(); URL op = discovered.getOPEndpoint(); Association assoc = _associations.load(op.toString(), handle); if (assoc != null) // association available, local verification { _log.info("Found association: " + assoc.getHandle() + " verifying signature locally..."); String text = authResp.getSignedText(); String signature = authResp.getSignature(); if (assoc.verifySignature(text, signature)) { result.setVerifiedId(claimedId); if (DEBUG) _log.debug("Local signature verification succeeded."); } else if (DEBUG) { _log.debug("Local signature verification failed."); result.setStatusMsg("Local signature verification failed"); } } else // no association, verify with the OP { _log.info("No association found, " + "contacting the OP for direct verification..."); VerifyRequest vrfy = VerifyRequest.createVerifyRequest(authResp); ParameterList responseParams = new ParameterList(); int respCode = call(op.toString(), vrfy, responseParams); if (HttpStatus.SC_OK == respCode) { VerifyResponse vrfyResp = VerifyResponse.createVerifyResponse(responseParams); vrfyResp.validate(); if (vrfyResp.isSignatureVerified()) { // process the optional invalidate_handle first String invalidateHandle = vrfyResp.getInvalidateHandle(); if (invalidateHandle != null) _associations.remove(op.toString(), invalidateHandle); result.setVerifiedId(claimedId); if (DEBUG) _log.debug("Direct signature verification succeeded " + "with OP: " + op); } else { if (DEBUG) _log.debug("Direct signature verification failed " + "with OP: " + op); result.setStatusMsg("Direct signature verification failed."); } } else { DirectError err = DirectError.createDirectError(responseParams); if (DEBUG) _log.debug("Error verifying signature with the OP: " + op + " error message: " + err.keyValueFormEncoding()); result.setStatusMsg("Error verifying signature with the OP: " + err.getErrorMsg()); } } Identifier verifiedID = result.getVerifiedId(); if (verifiedID != null) _log.info("Verification succeeded for: " + verifiedID); else _log.error("Verification failed for: " + authResp.getClaimed() + " reason: " + result.getStatusMsg()); return result; } /* visible for testing */ HttpFetcher getHttpFetcher() { return _httpFetcher; } } openid4java-0.9.6.662/src/org/openid4java/consumer/JdbcNonceVerifier.java0000644001501200150120000000726111040142265025366 0ustar miguelmiguel package org.openid4java.consumer ; import java.util.Date ; import org.apache.commons.logging.Log ; import org.apache.commons.logging.LogFactory ; import org.springframework.dao.DataIntegrityViolationException ; import org.springframework.jdbc.core.JdbcTemplate ; import org.springframework.jdbc.core.support.JdbcDaoSupport ; /** * * JDBC implementation of a NonceVerifier. *

* The JdbcNonceVerifier requires a a javax.sql.DataSource to be configured * and passed in to it with the setDataSource setter method. The table name * also needs to be specified, either through the constructor, or through the * setTableName setter. *

*

* Since the nonces are constructed on the web server and not on the shared * database server, they may accidentally collide. Also, if the machines * clocks are out of sync, the nonces from the machine that is behind may be * removed prematurely from the database by the other machine. *

*

* The specified table must have the following structure: *

*

* * @author Andrew Evenson, Graff Haley * @created May 19, 2008 */ public class JdbcNonceVerifier extends JdbcDaoSupport implements NonceVerifier { private static Log _log = LogFactory.getLog ( JdbcNonceVerifier.class ) ; private NonceVerifier _verifier ; private String _tableName ; private String _deleteSQL ; private String _insertSQL ; public JdbcNonceVerifier ( int maxAge ) { _verifier = new GenericNonceVerifier ( maxAge ) ; } public JdbcNonceVerifier ( int maxAge, String tableName ) { this ( maxAge ) ; setTableName ( tableName ) ; } public int getMaxAge ( ) { return _verifier.getMaxAge ( ) ; } public void setMaxAge(int ageSeconds) { _verifier.setMaxAge(ageSeconds); } public int seen ( String opUrl, String nonce ) { return _verifier.seen ( opUrl, nonce ) ; } public String getTableName ( ) { return _tableName ; } public void setTableName ( String tableName ) { this._tableName = tableName ; this._deleteSQL = "DELETE FROM " + tableName + " WHERE date>?" ; this._insertSQL = "INSERT INTO " + tableName + " (opurl, nonce, date) VALUES (?,?,?)" ; } private class GenericNonceVerifier extends AbstractNonceVerifier { public GenericNonceVerifier ( int maxAge ) { super ( maxAge ) ; } /** * * Implementation of the abstract nonce verifier. Uses the primary key * integrity constraint to evaluate nonces. This prevents a gap * between check and insert. Also, triggers the cleanup of old nonces. * * @param now * @param opUrl * @param nonce * @return */ protected int seen ( Date now, String opUrl, String nonce ) { cleanupAged ( ) ; JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; try { jdbcTemplate.update ( _insertSQL, new Object[] { opUrl, nonce, now } ) ; return OK ; } catch ( DataIntegrityViolationException e ) { _log.warn ( "Nonce already seen. Possible replay attack!" ) ; } catch ( Exception e ) { _log.error ( "Problem executing database method", e ) ; } return SEEN ; } private void cleanupAged ( ) { try { Date boundary = new Date ( System.currentTimeMillis ( ) - _maxAgeSeconds * 1000 ) ; JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ; int cnt = jdbcTemplate.update ( _deleteSQL, new Object[] { boundary } ) ; if ( _log.isDebugEnabled ( ) ) _log.debug ( "Client nonce cleanup removed " + cnt + " entries" ) ; } catch ( Exception e ) { _log.error ( "Error cleaning up client nonces from table: " + _tableName, e ) ; } } } } openid4java-0.9.6.662/src/org/openid4java/consumer/EhcacheNonceVerifier.java0000644001501200150120000000316011034531517026043 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class EhcacheNonceVerifier extends AbstractNonceVerifier { private static Log _log = LogFactory.getLog(EhcacheNonceVerifier.class); private static final boolean DEBUG = _log.isDebugEnabled(); private Cache _cache; public EhcacheNonceVerifier(int maxAge) { super(maxAge); } public void setCache(Cache cache) { if (cache.getTimeToLiveSeconds() != _maxAgeSeconds) { throw new IllegalArgumentException("Max Age: " + _maxAgeSeconds + ", same expected for cache, but found: " + cache.getTimeToLiveSeconds()); } if (cache.getTimeToLiveSeconds() != cache.getTimeToIdleSeconds()) { throw new IllegalArgumentException("Cache must have same timeToLive (" + cache.getTimeToLiveSeconds() + ") as timeToIdle (" + cache.getTimeToIdleSeconds() + ")"); } _cache = cache; } protected int seen(Date now, String opUrl, String nonce) { String pair = opUrl + '#' + nonce; Element element = new Element(pair, pair); if (_cache.get(pair) != null) { _log.error("Possible replay attack! Already seen nonce: " + nonce); return SEEN; } _cache.put(element); if (DEBUG) _log.debug("Nonce verified: " + nonce); return OK; } } openid4java-0.9.6.662/src/org/openid4java/message/0000755001501200150120000000000011627733442021003 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/message/sreg/0000755001501200150120000000000011627733442021743 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/message/sreg/SRegRequest.java0000644001501200150120000001427011034531512025005 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.sreg; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.message.ParameterList; import java.net.URL; import java.net.MalformedURLException; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Simple Registration fetch requests. * * @see SRegMessage Message * @author Marius Scurtescu, Johnny Bufu */ public class SRegRequest extends SRegMessage { private static Log _log = LogFactory.getLog(SRegRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Constructs a SReg Request with an empty parameter list. */ protected SRegRequest() { if (DEBUG) _log.debug("Created empty SReg request."); } /** * Constructs a SReg Request with an empty parameter list. */ public static SRegRequest createFetchRequest() { return new SRegRequest(); } /** * Constructs a SRegRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected SRegRequest(ParameterList params) { _parameters = params; } /** * Constructs a SRegRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ public static SRegRequest createSRegRequest(ParameterList params) throws MessageException { SRegRequest req = new SRegRequest(params); if (! req.isValid()) throw new MessageException("Invalid parameters for a SReg request"); if (DEBUG) _log.debug("Created SReg request from parameter list:\n" + params); return req; } /** * Adds an attribute to the SReg request. * * @param attr A requested attribute name. * @param required If true, marks the attribute as 'required'; * 'if_available' otherwise. */ public void addAttribute(String attr, boolean required) { String level = required ? "required" : "optional"; Parameter levelParam = _parameters.getParameter(level); Parameter newParam; if (levelParam == null) { newParam = new Parameter(level, multivalEncode(attr)); } else { newParam = new Parameter(level, levelParam.getValue() + "," + multivalEncode(attr)); _parameters.removeParameters(level); } _parameters.set(newParam); if (DEBUG) _log.debug("Added new attribute to SReg request: " + attr + " required: " + required); } /** * Returns a map with the requested attributes. * * @param required If set to true the list of 'required' attributes * is returned, otherwise the list of 'optional' * attributes. * @return List of attribute names. */ public List getAttributes(boolean required) { List attributes = new ArrayList(); String level = required ? "required" : "optional"; Parameter param = _parameters.getParameter(level); if (param != null) { String[] values = param.getValue().split(","); for (int i = 0; i < values.length; i++) { String attr = multivalDecode(values[i]); attributes.add(attr); } } return attributes; } /** * Gets all requested attributes (required and optional). * * @return List of attribute names. */ public List getAttributes() { List attributes = getAttributes(true); attributes.addAll(getAttributes(false)); return attributes; } /** * Sets the optional policy URL. * * @param policyUrl A URL which the Consumer provides to give the * End User a place to read about the how the profile * data will be used. The Identity Provider SHOULD * display this URL to the End User if it is given. */ public void setPolicyUrl(String policyUrl) throws MessageException { try { new URL(policyUrl); } catch (MalformedURLException e) { throw new MessageException("Invalid policy_url: " + policyUrl); } if (DEBUG) _log.debug("Setting SReg request policy_url: " + policyUrl); _parameters.set(new Parameter("policy_url", policyUrl)); } /** * Gets the optional policy URL parameter if available, or null otherwise. */ public String getUpdateUrl() { return _parameters.hasParameter("policy_url") ? _parameters.getParameterValue("policy_url") : null; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ public boolean isValid() { if ( ! _parameters.hasParameter("required") && ! _parameters.hasParameter("optional") ) { _log.warn("One of 'required' or 'optional' parameters must be present."); return false; } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (! paramName.equals("required") && ! paramName.equals("optional") && ! paramName.equals("policy_url")) { _log.warn("Invalid parameter name in SReg request: " + paramName); // return false; } } return true; } } openid4java-0.9.6.662/src/org/openid4java/message/sreg/SRegMessage.java0000644001501200150120000001525711207020752024750 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.sreg; import org.openid4java.message.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Base class for the Simple Registration implementation. *

* Encapsulates: *

* * Considering that: * * * Support for Simple Registration is implemented as follows: * * * @see Message MessageExtension * @author Marius Scurtescu, Johnny Bufu */ public class SRegMessage implements MessageExtension, MessageExtensionFactory { private static Log _log = LogFactory.getLog(SRegMessage.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * The Simple Registration 1.0 namespace URI. */ public static final String OPENID_NS_SREG = "http://openid.net/sreg/1.0"; /** * The Simple Registration 1.1 namespace URI. */ public static final String OPENID_NS_SREG11 = "http://openid.net/extensions/sreg/1.1"; /** * The Simple Registration extension-specific parameters. *

* The openid. prefix is not part of the parameter names */ protected ParameterList _parameters; private String _typeUri = OPENID_NS_SREG; /** * Constructs an empty (no parameters) Simple Registration extension. */ public SRegMessage() { _parameters = new ParameterList(); if (DEBUG) _log.debug("Created empty SRegMessage."); } /** * Constructs an Simple Registration extension with a specified list of * parameters. *

* The parameter names in the list should not contain the * openid.. */ public SRegMessage(ParameterList params) { _parameters = params; if (DEBUG) _log.debug("Created SRegMessage from parameter list:\n" + params); } /** * Gets the Type URI that identifies the Simple Registration extension. */ public String getTypeUri() { return _typeUri; } /** * Sets the SREG type URI. Hack to support both SREG 1.0 and 1.1, * until 1.1 spec gets fixed. */ public void setTypeUri(String typeUri) { _typeUri = typeUri; } /** * Gets ParameterList containing the Simple Registration extension-specific * parameters. *

* The openid. prefix is not part of the parameter names, * as it is handled internally by the Message class. *

* The openid.ns. parameter is also handled by * the Message class. * * @see Message */ public ParameterList getParameters() { return _parameters; } /** * Gets a the value of the parameter with the specified name. * * @param name The name of the parameter, * without the openid. prefix. * @return The parameter value, or null if not found. */ public String getParameterValue(String name) { return _parameters.getParameterValue(name); } /** * Sets the extension's parameters to the supplied list. *

* The parameter names in the list should not contain the * openid. prefix. */ public void setParameters(ParameterList params) { _parameters = params; } /** * Encodes a string value according to the conventions for supporting * multiple values for a parameter (commas and backslashes are escaped). * * @param value String value to be encoded. * @return The encoded value. */ public String multivalEncode(String value) { return value.replaceAll("\\\\", "\\\\\\\\").replaceAll(",","\\\\,"); } /** * Decodes a string value according to the conventions for supporting * multiple values for a parameter (commas and backslashes are escaped). * * @param value String value to be decoded. * @return The dencoded value. */ public String multivalDecode(String value) { return value.replaceAll("\\\\,", ",").replaceAll("\\\\\\\\","\\\\"); } /** * Simple Registration doesn't implement authentication services. * * @return false */ public boolean providesIdentifier() { return false; } /** * Simple registration parameters are REQUIRED to be signed. * * @return true */ public boolean signRequired() { return true; } /** * Instantiates the apropriate Simple Registration object * (request / response) for the supplied parameter list. * * @param parameterList The Simple Registration specific parameters * (without the openid. prefix) * extracted from the openid message. * @param isRequest Indicates whether the parameters were * extracted from an OpenID request (true), * or from an OpenID response. * @return MessageExtension implementation for * the supplied extension parameters. * @throws MessageException If a Simple Registration object could not be * instantiated from the supplied parameter list. */ public MessageExtension getExtension( ParameterList parameterList, boolean isRequest) throws MessageException { if ( parameterList.hasParameter("required") || parameterList.hasParameter("optional")) return SRegRequest.createSRegRequest(parameterList); else return SRegResponse.createSRegResponse(parameterList); } } openid4java-0.9.6.662/src/org/openid4java/message/sreg/SReg11ExtensionFactory.java0000644001501200150120000000432611034531512027024 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.sreg; import org.openid4java.message.MessageExtensionFactory; import org.openid4java.message.MessageExtension; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; /** * Custom Extension Factory for SREG 1.1 messages. Creates SRegMessage * objects, but sets the type URI to http://openid.net/extensions/sreg/1.1 * for SREG 1.1. * * @author Marius Scurtescu, Johnny Bufu */ public class SReg11ExtensionFactory implements MessageExtensionFactory { /** * Gets the Type URI that identifies the Simple Registration 1.1 extension. */ public String getTypeUri() { return SRegMessage.OPENID_NS_SREG11; } /** * Instantiates the apropriate Simple Registration object * (request / response) for the supplied parameter list. * * Similar to SRegMessage.getExtension(), but sets the SREG 1.1 type URI. * * @param parameterList The Simple Registration specific parameters * (without the openid. prefix) * extracted from the openid message. * @param isRequest Indicates whether the parameters were * extracted from an OpenID request (true), * or from an OpenID response. * @return MessageExtension implementation for * the supplied extension parameters. * @throws MessageException If a Simple Registration object could not be * instantiated from the supplied parameter list. */ public MessageExtension getExtension( ParameterList parameterList, boolean isRequest) throws MessageException { SRegMessage sreg; if ( parameterList.hasParameter("required") || parameterList.hasParameter("optional")) sreg = SRegRequest.createSRegRequest(parameterList); else sreg = SRegResponse.createSRegResponse(parameterList); sreg.setTypeUri(SRegMessage.OPENID_NS_SREG11); return sreg; } } openid4java-0.9.6.662/src/org/openid4java/message/sreg/SRegResponse.java0000644001501200150120000001260311034531512025151 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.sreg; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Simple Registration fetch responses. * * @author Marius Scurtescu, Johnny Bufu */ public class SRegResponse extends SRegMessage { private static Log _log = LogFactory.getLog(SRegResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List SREG_FIELDS = Arrays.asList( new String[] { "nickname", "email", "fullname", "dob", "gender", "postcode", "country", "language", "timezone" }); /** * Constructs a SReg Response with an empty parameter list. */ protected SRegResponse() { if (DEBUG) _log.debug("Created empty fetch response."); } /** * Constructs a SReg Response with an empty parameter list. */ public static SRegResponse createFetchResponse() { return new SRegResponse(); } /** * Constructs a SReg Response from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected SRegResponse(ParameterList params) { _parameters = params; } public static SRegResponse createSRegResponse(ParameterList params) throws MessageException { SRegResponse resp = new SRegResponse(params); if (! resp.isValid()) throw new MessageException("Invalid parameters for a SReg response"); if (DEBUG) _log.debug("Created SReg response from parameter list:\n" + params); return resp; } /** * Creates a SRegResponse from a SRegRequest message and the data released * by the user. * * @param req SRegRequest message. * @param userData Map with the * data released by the user. * @return Properly formed SRegResponse. * @throws MessageException if any attribute-name in the userData map does not * correspond to an SREG field-name. */ public static SRegResponse createSRegResponse(SRegRequest req, Map userData) throws MessageException { SRegResponse resp = new SRegResponse(); List attributes = req.getAttributes(); Iterator iter = attributes.iterator(); while (iter.hasNext()) { String attr = (String) iter.next(); String value = (String) userData.get(attr); if (value != null) resp.addAttribute(attr, value); } return resp; } /** * Adds an attribute to the SReg response. The allowed attribute names are * the ones defined in the SReg specification: nickname, email, fullname, * dob, gender, postcode, country, language, timezone. * * @param attr An attribute name. * @param value The value of the attribute. */ public void addAttribute(String attr, String value) throws MessageException { _parameters.set(new Parameter(attr, value)); if (! SREG_FIELDS.contains(attr)) throw new MessageException("Invalid attribute for SReg: " + attr); if (DEBUG) _log.debug("Added new attribute to SReg response: " + attr + " value: " + value); } /** * Returns the value of an attribute. * * @param attr The attribute name. * @return The attribute value. */ public String getAttributeValue(String attr) { return getParameterValue(attr); } /** * Gets a list of attribute names in the SReg response. */ public List getAttributeNames() { List attributes = new ArrayList(); Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { attributes.add(((Parameter) it.next()).getKey()); } return attributes; } /** * Gets a map with attribute names -> values. */ public Map getAttributes() { Map attributes = new HashMap(); Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String attr = ((Parameter) it.next()).getKey(); attributes.put(attr, getAttributeValue(attr)); } return attributes; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ private boolean isValid() { Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (! SREG_FIELDS.contains(paramName)) { _log.warn("Invalid parameter name in SReg response: " + paramName); return false; } } return true; } } openid4java-0.9.6.662/src/org/openid4java/message/AuthImmediateFailure.java0000644001501200150120000000674511034531513025675 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; import java.net.URL; import java.net.MalformedURLException; /** * @author Marius Scurtescu, Johnny Bufu */ public class AuthImmediateFailure extends Message { private static Log _log = LogFactory.getLog(AuthImmediateFailure.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode" }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns", "openid.user_setup_url" }); protected AuthImmediateFailure(String url, String returnTo, boolean compatibility) { if (compatibility) { set("openid.mode", MODE_IDRES); set("openid.user_setup_url", url); } else { set("openid.mode", MODE_SETUP_NEEDED); set("openid.ns", OPENID2_NS); } _destinationUrl = returnTo; } protected AuthImmediateFailure(ParameterList params) { super(params); } public static AuthImmediateFailure createAuthImmediateFailure( String url, String returnTo, boolean compatibility) throws MessageException { AuthImmediateFailure fail = new AuthImmediateFailure(url, returnTo, compatibility); fail.validate(); return fail; } public static AuthImmediateFailure createAuthImmediateFailure(ParameterList params) throws MessageException { AuthImmediateFailure fail = new AuthImmediateFailure(params); fail.validate(); if (DEBUG) _log.debug("Retrieved auth immediate failure from message parameters:\n" + fail.keyValueFormEncoding()); return fail; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } public String getUserSetupUrl() { return getParameterValue("openid.user_setup_url"); } public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); String mode = getParameterValue("openid.mode"); if (compatibility) { try { new URL(getUserSetupUrl()); } catch (MalformedURLException e) { throw new MessageException( "Invalid user_setup_url in auth failure response.", OpenIDException.AUTH_ERROR, e); } if (! MODE_IDRES.equals(mode)) throw new MessageException( "Invalid openid.mode in auth failure response; " + "expected " + MODE_IDRES + " found: " + mode, OpenIDException.AUTH_ERROR); } else if (! MODE_SETUP_NEEDED.equals(mode)) throw new MessageException( "Invalid openid.mode in auth failure response; " + "expected " + MODE_SETUP_NEEDED + "found: " + mode, OpenIDException.AUTH_ERROR); } } openid4java-0.9.6.662/src/org/openid4java/message/pape/0000755001501200150120000000000011627733442021730 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/message/pape/PapeRequest.java0000644001501200150120000001375011202136552025023 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.pape; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.message.ParameterList; import org.openid4java.OpenIDException; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for OpenID Provider Authentication Policy requests. * * @see PapeMessage Message * @author Marius Scurtescu, Johnny Bufu */ public class PapeRequest extends PapeMessage { private static Log _log = LogFactory.getLog(PapeRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List PAPE_FIELDS = Arrays.asList( new String[] { "preferred_auth_policies", "preferred_auth_level_types", "max_auth_age" }); /** * Constructs a Pape Request with an empty parameter list. */ protected PapeRequest() { set("preferred_auth_policies", ""); if (DEBUG) _log.debug("Created empty Pape request."); } /** * Constructs a Pape Request with an empty parameter list. */ public static PapeRequest createPapeRequest() { return new PapeRequest(); } /** * Constructs a PapeRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected PapeRequest(ParameterList params) { super(params); } /** * Constructs a PapeRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ public static PapeRequest createPapeRequest(ParameterList params) throws MessageException { PapeRequest req = new PapeRequest(params); req.validate(); if (DEBUG) _log.debug("Created PAPE request from parameter list:\n" + params); return req; } /** * Gets the preferred_auth_policies parameter value. */ public String getPreferredAuthPolicies() { return getParameterValue("preferred_auth_policies"); } /** * Sets a new value for the preferred_auth_policies parameter. * * The previous value of the parameter will be owerwritten. * * @param policyUris Space separated list of authentication policy * URIs to be set. * @see #addPreferredAuthPolicy(String) */ public void setPreferredAuthPolicies(String policyUris) { // todo: enforce that policyUri is a valid URI? set("preferred_auth_policies", policyUris); } /** * Adds an authentication policy URI to the preferred_auth_policies * parameter. * * @param policyUri The authentication policy URI to be set. * @see #setPreferredAuthPolicies(String) */ public void addPreferredAuthPolicy(String policyUri) { // todo: check that policyUri isn't already in the list? String policies = getPreferredAuthPolicies(); if (policies == null || policies.length() == 0) setPreferredAuthPolicies(policyUri); else setPreferredAuthPolicies(policies + " " + policyUri); } /** * Gets a list with the preferred_auth_policies. An empty list is * returned if no authentication policies exist. * */ public List getPreferredAuthPoliciesList() { String policies = getParameterValue("preferred_auth_policies"); if (policies != null) return Arrays.asList(policies.split(" ")); else return new ArrayList(); } /** * Sets the max_auth_age parameter. * * @param seconds The number of seconds within which the OP is * requested to have actively authenticated the user. */ public void setMaxAuthAge(int seconds) { set("max_auth_age", Integer.toString(seconds)); } /** * Gets the max_auth_age parameter. * * @return The number of seconds within which the OP is * requested to have actively authenticated the user, * or -1 if max_auth_age is not present in the request. */ public int getMaxAuthAge() { String maxAuthAge = getParameterValue("max_auth_age"); if (maxAuthAge != null) return Integer.parseInt(maxAuthAge); else return -1; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @throws MessageException if the PapeRequest is not valid. */ public void validate() throws MessageException { if (! _parameters.hasParameter("preferred_auth_policies")) { throw new MessageException( "preferred_auth_policies is required in a PAPE request.", OpenIDException.PAPE_ERROR); } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (! PAPE_FIELDS.contains(paramName) && ! paramName.startsWith(PapeMessage.AUTH_LEVEL_NS_PREFIX)) { throw new MessageException( "Invalid parameter name in PAPE request: " + paramName, OpenIDException.PAPE_ERROR); } } } public void addPreferredCustomAuthLevel(String authLevelTypeUri) { String alias = addAuthLevelExtension(authLevelTypeUri); String preferred = getParameterValue("preferred_auth_level_types"); set("preferred_auth_level_types", preferred == null ? alias : preferred + " " + alias); } } openid4java-0.9.6.662/src/org/openid4java/message/pape/PapeResponse.java0000644001501200150120000001676111202137743025201 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.pape; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.util.InternetDateFormat; import org.openid4java.OpenIDException; import java.util.*; import java.text.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for OpenID Provider Authentication Policy responses. * * @author Marius Scurtescu, Johnny Bufu */ public class PapeResponse extends PapeMessage { private static Log _log = LogFactory.getLog(PapeResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List PAPE_FIELDS = Arrays.asList( new String[] { "auth_policies", "auth_time", }); private static final String AUTH_POLICY_NONE = "http://schemas.openid.net/pape/policies/2007/06/none"; private static InternetDateFormat _dateFormat = new InternetDateFormat(); /** * Constructs a Pape Response with an empty parameter list. */ protected PapeResponse() { set("auth_policies", AUTH_POLICY_NONE); if (DEBUG) _log.debug("Created empty PAPE response."); } /** * Constructs a Pape Response with an empty parameter list. */ public static PapeResponse createPapeResponse() { return new PapeResponse(); } /** * Constructs a Pape Response from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected PapeResponse(ParameterList params) { super(params); } public static PapeResponse createPapeResponse(ParameterList params) throws MessageException { PapeResponse resp = new PapeResponse(params); resp.validate(); if (DEBUG) _log.debug("Created PAPE response from parameter list:\n" + params); return resp; } /** * Gets the auth_policies parameter value. */ public String getAuthPolicies() { return getParameterValue("auth_policies"); } /** * Sets a new value for the auth_policies parameter. * * The previous value of the parameter will be owerwritten. * * @param policyUris Space separated list of authentication policy * URIs to be set. * @see #addAuthPolicy(String) */ public void setAuthPolicies(String policyUris) { // todo: enforce that policyUri is a valid URI? set("auth_policies", policyUris); } /** * Adds an authentication policy URI to the auth_policies * parameter. * * @param policyUri The authentication policy URI to be set. * @see #setAuthPolicies(String) */ public void addAuthPolicy(String policyUri) { // todo: check that policyUri isn't already in the list? String policies = getAuthPolicies(); if (policies == null || AUTH_POLICY_NONE.equals(policies)) // should never be null setAuthPolicies(policyUri); else setAuthPolicies(policies + " " + policyUri); } /** * Gets a list with the auth_policies. An empty list is * returned if no authentication policies exist. */ public List getAuthPoliciesList() { String policies = getParameterValue("auth_policies"); if (policies == null || AUTH_POLICY_NONE.equals(policies)) // should never be null return new ArrayList(); else return Arrays.asList(policies.split(" ")); } /** * Sets the auth_time parameter. * * @param timestamp The most recent timestamp when the End User has * actively authenticated to the OP in a manner * fitting the asserted policies. */ public void setAuthTime(Date timestamp) { set("auth_time", _dateFormat.format(timestamp)); } /** * Gets the timestamp when the End User has most recentnly authenticated * to the OpenID Provider in a manner fitting the asserted policies. * * @return The verbatim value of the auth_time parameter. * Null is returned if the parameter is not present * in the PapeResponse. * * @see #getAuthDate() */ public String getAuthTime() { return getParameterValue("auth_time"); } /** * Gets the timestamp when the End User has most recentnly authenticated * to the OpenID Provider in a manner fitting the asserted policies. * * @return The value of the auth_time parameter parsed into * a java.util.Date. Null is returned if the parameter * is not present in the PapeResponse, or if the * parameter value is invalid. * * @see #getAuthTime() */ public Date getAuthDate() { String authTime = getParameterValue("auth_time"); if (authTime != null) { try { return _dateFormat.parse(authTime); } catch (ParseException e) { _log.warn("Invalid auth_time: " + authTime + "; returning null."); } } return null; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @throws MessageException if the PapeResponse is not valid. */ private void validate() throws MessageException { if (! _parameters.hasParameter("auth_policies")) { throw new MessageException( "auth_policies is required in a PAPE response.", OpenIDException.PAPE_ERROR); } String authTime = getAuthTime(); if (authTime != null) { try { _dateFormat.parse(authTime); } catch (ParseException e) { throw new MessageException( "Invalid auth_time in PAPE response: " + authTime, OpenIDException.PAPE_ERROR, e); } } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (PAPE_FIELDS.contains(paramName) || paramName.startsWith(PapeMessage.AUTH_LEVEL_NS_PREFIX)) continue; if ( paramName.startsWith(AUTH_LEVEL_PREFIX) && (authLevelAliases.values().contains(paramName.substring(AUTH_LEVEL_PREFIX.length())))) continue; throw new MessageException( "Invalid parameter in PAPE response: " + paramName, OpenIDException.PAPE_ERROR); } } public void setCustomAuthLevel(String authLevelTypeUri, String level) { String alias = addAuthLevelExtension(authLevelTypeUri); set(AUTH_LEVEL_PREFIX + alias, level); } public String getCustomAuthLevel(String authLevelTypeUri) { if (hasCustomAuthLevel(authLevelTypeUri)) return getParameterValue(AUTH_LEVEL_PREFIX + getCustomAuthLevelAlias(authLevelTypeUri)); else return null; } } openid4java-0.9.6.662/src/org/openid4java/message/pape/PapeMessage.java0000644001501200150120000002122111202137743024752 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.pape; import org.openid4java.message.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Map; import java.util.HashMap; import java.util.Iterator; /** * Base class for the OpenID Provider Authentication Policy extension * implementation. *

* Encapsulates: *

* * @see Message MessageExtension * @author Marius Scurtescu, Johnny Bufu */ public class PapeMessage implements MessageExtension, MessageExtensionFactory { private static Log _log = LogFactory.getLog(PapeMessage.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String PAPE_POLICY_PHISHING_RESISTANT = "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant"; public static final String PAPE_POLICY_MULTI_FACTOR = "http://schemas.openid.net/pape/policies/2007/06/multi-factor"; public static final String PAPE_POLICY_MULTI_FACTOR_PHYSICAL = "http://schemas.openid.net/pape/policies/2007/06/multi-factor-physical"; protected static final String AUTH_LEVEL_PREFIX = "auth_level."; protected static final String AUTH_LEVEL_NS_PREFIX = "auth_level.ns."; private static final String AUTH_LEVEL_ALIAS_PREFIX = "papeauthlevel"; protected Map authLevelAliases = new HashMap(); // auth level URL -> alias private int authLevelAliasCounter = 0; /** * The OpenID Provider Authentication Policy extension URI. */ public static final String OPENID_NS_PAPE = "http://specs.openid.net/extensions/pape/1.0"; /** * The OpenID Provider Authentication Policy extension-specific parameters. *

* The openid. prefix is not part of the parameter names */ protected ParameterList _parameters; /** * Constructs an empty (no parameters) OpenID Provider Authentication * Policy extension. */ public PapeMessage() { _parameters = new ParameterList(); if (DEBUG) _log.debug("Created empty PapeMessage."); } /** * Constructs an OpenID Provider Authentication Policy extension * with a specified list of parameters. *

* The parameter names in the list should not contain the * openid.. */ public PapeMessage(ParameterList params) { setParameters(params); if (DEBUG) _log.debug("Created PapeMessage from parameter list:\n" + params); } /** * Gets the Type URI that identifies the OpenID Provider Authentication * Policy extension. */ public String getTypeUri() { return OPENID_NS_PAPE; } /** * Gets ParameterList containing the OpenID Provider Authentication * Policy extension-specific parameters. *

* The openid. prefix is not part of the parameter names, * as it is handled internally by the Message class. *

* The openid.ns. parameter is also handled by * the Message class. * * @see Message */ public ParameterList getParameters() { return _parameters; } /** * Sets the extension's parameters to the supplied list. *

* The parameter names in the list should not contain the * openid. prefix. */ public void setParameters(ParameterList params) { _parameters = params; Iterator iter = params.getParameters().iterator(); while(iter.hasNext()) checkAddAuthLevelExtension((Parameter) iter.next()); } /** * Checks if the extension contains a parameter. * * @param name The name of the parameter, * without the openid. prefix. * @return True if a parameter with the specified name exists, * false otherwise. */ public boolean hasParameter(String name) { return _parameters.hasParameter(name); } /** * Sets the value for the parameter with the specified name. * * @param name The name of the parameter, * without the openid. prefix. */ protected void set(String name, String value) { Parameter param = new Parameter(name, value); _parameters.set(param); checkAddAuthLevelExtension(param); } private void checkAddAuthLevelExtension(Parameter param) { String key = param == null ? null : param.getKey(); String value = param == null ? null : param.getValue(); if (key != null && key.startsWith(AUTH_LEVEL_NS_PREFIX)) addAuthLevelExtension(value, key.substring(AUTH_LEVEL_NS_PREFIX.length())); } private synchronized String newAuthLevelAlias() { return AUTH_LEVEL_ALIAS_PREFIX + ++authLevelAliasCounter; } protected String addAuthLevelExtension(String authLevelTypeUri) { return addAuthLevelExtension(authLevelTypeUri, null); } private String addAuthLevelExtension(String authLevelTypeUri, String alias) { if (!authLevelAliases.containsKey(authLevelTypeUri)) { String authLevelAlias = alias == null ? newAuthLevelAlias() : alias; authLevelAliases.put(authLevelTypeUri, authLevelAlias); } return (String) authLevelAliases.get(authLevelTypeUri); } public boolean hasCustomAuthLevel(String authLevelTypeUri) { return authLevelAliases.containsKey(authLevelTypeUri); } protected String getCustomAuthLevelAlias(String authLevelTypeUri) { return (String) authLevelAliases.get(authLevelTypeUri); } /** * Gets a the value of the parameter with the specified name. * * @param name The name of the parameter, * without the openid. prefix. * @return The parameter value, or null if not found. */ protected Parameter getParameter(String name) { return _parameters.getParameter(name); } /** * Gets a the value of the parameter with the specified name. * * @param name The name of the parameter, * without the openid. prefix. * @return The parameter value, or null if not found. */ public String getParameterValue(String name) { return _parameters.getParameterValue(name); } /** * OpenID Provider Authentication Policy extension doesn't implement * authentication services. * * @return false */ public boolean providesIdentifier() { return false; } /** * PAPE parameters are REQUIRED to be signed. * * @return */ public boolean signRequired() { return true; } /** * Instantiates the apropriate OpenID Provider Authentication Policy * extension object (request / response) for the supplied parameter * list. * * @param parameterList The OpenID Provider Authentication Policy * extension specific parameters * (without the openid. prefix) * extracted from the openid message. * @param isRequest Indicates whether the parameters were * extracted from an OpenID request (true), * or from an OpenID response. * @return MessageExtension implementation for * the supplied extension parameters. * @throws MessageException If a OpenID Provider Authentication Policy * extension object could not be * instantiated from the supplied parameter list. */ public MessageExtension getExtension( ParameterList parameterList, boolean isRequest) throws MessageException { if ( parameterList.hasParameter("preferred_auth_policies") || parameterList.hasParameter("max_auth_age")) return PapeRequest.createPapeRequest(parameterList); else if ( parameterList.hasParameter("auth_policies") || parameterList.hasParameter("auth_time")) return PapeResponse.createPapeResponse(parameterList); else throw new MessageException("Invalid parameters for a PAPE message."); } } openid4java-0.9.6.662/src/org/openid4java/message/DirectError.java0000644001501200150120000000735211034531513024064 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; /** * @author Marius Scurtescu, Johnny Bufu */ public class DirectError extends Message { private static Log _log = LogFactory.getLog(DirectError.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "error" }); protected final static List optionalFields = Arrays.asList( new String[] { "ns", "contact", "reference" }); // exception that generated the error, if any private OpenIDException _exception; protected DirectError(String msg) { this(msg, false); } protected DirectError(String msg, boolean compatibility) { this(null, msg, compatibility); } protected DirectError(OpenIDException e, boolean compatibility) { this(e, e.getMessage(), compatibility); } protected DirectError(OpenIDException e, String msg, boolean compatibility) { set("error", msg); _exception = e; if ( ! compatibility ) set("ns", OPENID2_NS); } protected DirectError(ParameterList params) { super(params); } public static DirectError createDirectError(OpenIDException e) { return createDirectError(e, false); } public static DirectError createDirectError(String msg) { return createDirectError(null, msg, false); } public static DirectError createDirectError(String msg, boolean compatibility) { return createDirectError(null, msg, compatibility); } public static DirectError createDirectError(OpenIDException e, boolean compatibility) { return createDirectError(e, e.getMessage(), compatibility); } public static DirectError createDirectError(OpenIDException e, String msg, boolean compatibility) { DirectError err = new DirectError(e, msg, compatibility); try { err.validate(); } catch (MessageException ex) { _log.error("Invalid " + (compatibility? "OpenID1" : "OpenID2") + " direct error message created for message: " + msg); } _log.debug("Created direct error message:\n" + err.keyValueFormEncoding()); return err; } public static DirectError createDirectError(ParameterList params) { DirectError err = new DirectError(params); try { err.validate(); } catch (MessageException e) { _log.error("Invalid direct error message created: " + err.keyValueFormEncoding() ); } _log.debug("Created direct error message:\n" + err.keyValueFormEncoding()); return err; } public OpenIDException getException() { return _exception; } public void setException(OpenIDException e) { this._exception = e; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("ns") && OPENID2_NS.equals(getParameterValue("ns")); } public void setErrorMsg(String msg) { set("error", msg); } public String getErrorMsg() { return getParameterValue("error"); } public void setContact(String contact) { set("contact", contact); } public void setReference(String reference) { set("reference", reference); } } openid4java-0.9.6.662/src/org/openid4java/message/ParameterList.java0000644001501200150120000001542011250064010024400 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.List; import java.net.URLDecoder; /** * A list of parameters that are part of an OpenID message. Please note that you can have multiple parameters with * the same name. * * @author Marius Scurtescu, Johnny Bufu */ public class ParameterList implements Serializable { private static Log _log = LogFactory.getLog(ParameterList.class); private static final boolean DEBUG = _log.isDebugEnabled(); Map _parameterMap; public ParameterList() { _parameterMap = new LinkedHashMap(); if (DEBUG) _log.debug("Created empty parameter list."); } public ParameterList(ParameterList that) { if (DEBUG) _log.debug("Cloning parameter list:\n" + that); this._parameterMap = new LinkedHashMap(that._parameterMap); } /** * Constructs a ParameterList from a Map of parameters, ideally obtained * with ServletRequest.getParameterMap(). The parameter keys and values * must be in URL-decoded format. * * @param parameterMap Map or Map */ public ParameterList(Map parameterMap) { _parameterMap = new LinkedHashMap(); Iterator keysIter = parameterMap.keySet().iterator(); while (keysIter.hasNext()) { String name = (String) keysIter.next(); Object v = parameterMap.get(name); String value; if (v instanceof String[]) { String[] values = (String[]) v; if (values.length > 1 && name.startsWith("openid.")) throw new IllegalArgumentException( "Multiple parameters with the same name: " + values); value = values.length > 0 ? values[0] : null; } else if (v instanceof String) { value = (String) v; } else { value=""; _log.error("Can extract parameter value; unexpected type: " + v.getClass().getName()); } set(new Parameter(name, value)); } if (DEBUG) _log.debug("Creating parameter list:\n" + this); } public void copyOf(ParameterList that) { if (DEBUG) _log.debug("Copying parameter list:\n" + that); this._parameterMap = new LinkedHashMap(that._parameterMap); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; final ParameterList that = (ParameterList) obj; return _parameterMap.equals(that._parameterMap); } public int hashCode() { return _parameterMap.hashCode(); } public void set(Parameter parameter) { _parameterMap.put(parameter.getKey(), parameter); } public void addParams(ParameterList params) { Iterator iter = params.getParameters().iterator(); while (iter.hasNext()) set((Parameter) iter.next()); } public Parameter getParameter(String name) { return (Parameter) _parameterMap.get(name); } public String getParameterValue(String name) { Parameter param = getParameter(name); return param != null ? param.getValue() : null; } public List getParameters() { return new ArrayList(_parameterMap.values()); } public void removeParameters(String name) { _parameterMap.remove(name); } public boolean hasParameter(String name) { return _parameterMap.containsKey(name); } public boolean hasParameterPrefix(String prefix) { Iterator keysIter = _parameterMap.keySet().iterator(); while (keysIter.hasNext()) { if (((String)keysIter.next()).startsWith(prefix)) return true; } return false; } /** * Create a parameter list based on a URL encoded HTTP query string. */ public static ParameterList createFromQueryString(String queryString) throws MessageException { if (DEBUG) _log.debug("Creating parameter list from query string: " + queryString); ParameterList parameterList = new ParameterList(); StringTokenizer tokenizer = new StringTokenizer(queryString, "&"); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); int posEqual = keyValue.indexOf('='); if (posEqual == -1) throw new MessageException("Invalid query parameter, = missing: " + keyValue); try { String key = URLDecoder.decode(keyValue.substring(0, posEqual), "UTF-8"); String value = URLDecoder.decode(keyValue.substring(posEqual + 1), "UTF-8"); parameterList.set(new Parameter(key, value)); } catch (UnsupportedEncodingException e) { throw new MessageException("Cannot URL decode query parameter: " + keyValue, e); } } return parameterList; } public static ParameterList createFromKeyValueForm(String keyValueForm) throws MessageException { if (DEBUG) _log.debug("Creating parameter list from key-value form:\n" + keyValueForm); ParameterList parameterList = new ParameterList(); StringTokenizer tokenizer = new StringTokenizer(keyValueForm, "\n"); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); int posColon = keyValue.indexOf(':'); if (posColon == -1) throw new MessageException("Invalid Key-Value form, colon missing: " + keyValue); String key = keyValue.substring(0, posColon); String value = keyValue.substring(posColon + 1); parameterList.set(new Parameter(key, value)); } return parameterList; } /** * @return The key-value form encoding of for this ParameterList. */ public String toString() { StringBuffer allParams = new StringBuffer(""); List parameters = getParameters(); Iterator iterator = parameters.iterator(); while (iterator.hasNext()) { Parameter parameter = (Parameter) iterator.next(); allParams.append(parameter.getKey()); allParams.append(':'); allParams.append(parameter.getValue()); allParams.append('\n'); } return allParams.toString(); } } openid4java-0.9.6.662/src/org/openid4java/message/Message.java0000644001501200150120000004144111275165042023230 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.sreg.SRegMessage; import org.openid4java.message.sreg.SReg11ExtensionFactory; import org.openid4java.message.pape.PapeMessage; import java.io.UnsupportedEncodingException; import java.util.*; import java.net.URLEncoder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class Message { private static Log _log = LogFactory.getLog(Message.class); private static final boolean DEBUG = _log.isDebugEnabled(); // message constants public static final String MODE_IDRES = "id_res"; public static final String MODE_CANCEL = "cancel"; public static final String MODE_SETUP_NEEDED = "setup_needed"; public static final String OPENID2_NS = "http://specs.openid.net/auth/2.0"; private ParameterList _params; private int _extCounter; // extention type URI -> extension alias : extension present in the message private Map _extAliases; // extension type URI -> MessageExtensions : extracted extension objects private Map _extesion; // the URL where this message should be sent, where applicable // should remain null for received messages (created from param lists) protected String _destinationUrl; // type URI -> message extension factory : supported extensions private static Map _extensionFactories = new HashMap(); static { _extensionFactories.put(AxMessage.OPENID_NS_AX, AxMessage.class); _extensionFactories.put(SRegMessage.OPENID_NS_SREG, SRegMessage.class); _extensionFactories.put(SRegMessage.OPENID_NS_SREG11, SReg11ExtensionFactory.class); _extensionFactories.put(PapeMessage.OPENID_NS_PAPE, PapeMessage.class); } protected Message() { _params = new ParameterList(); _extCounter = 0; _extAliases = new HashMap(); _extesion = new HashMap(); } protected Message (ParameterList params) { this(); this._params = params; //build the extension list when creating a message from a param list Iterator iter = _params.getParameters().iterator(); // simple registration is a special case; we support only: // SREG1.0 (no namespace, "sreg" alias hardcoded) in : // - OpenID1 messages // - OpenID2 messages (against the 2.0 spec), // to accomodate Yahoo's non-2.0-compliant implementation // SREG1.1 (namespace, any possible alias) in OpenID2 messages boolean hasOpenidDotSreg = false; while (iter.hasNext()) { String key = ((Parameter) iter.next()).getKey(); if (key.startsWith("openid.ns.") && key.length() > 10) _extAliases.put(_params.getParameter(key).getValue(), key.substring(10)); if (key.startsWith("openid.sreg.")) hasOpenidDotSreg = true; } // only do the workaround for OpenID1 messages if ( hasOpenidDotSreg && ! _extAliases.values().contains("sreg") /*! todo: revert this: hasParameter("openid.ns")*/ ) _extAliases.put(SRegMessage.OPENID_NS_SREG, "sreg"); _extCounter = _extAliases.size(); } public static Message createMessage() throws MessageException { Message message = new Message(); message.validate(); if (DEBUG) _log.debug("Created message:\n" + message.keyValueFormEncoding()); return message; } public static Message createMessage(ParameterList params) throws MessageException { Message message = new Message(params); message.validate(); if (DEBUG) _log.debug("Created message from parameter list:\n" + message.keyValueFormEncoding()); return message; } protected Parameter getParameter(String name) { return _params.getParameter(name); } public String getParameterValue(String name) { return _params.getParameterValue(name); } public boolean hasParameter(String name) { return _params.hasParameter(name); } protected void set(String name, String value) { _params.set(new Parameter(name, value)); } protected List getParameters() { return _params.getParameters(); } public Map getParameterMap() { Map params = new LinkedHashMap(); Iterator iter = _params.getParameters().iterator(); while (iter.hasNext()) { Parameter p = (Parameter) iter.next(); params.put( p.getKey(), p.getValue() ); } return params; } /** * Checks that all required parameters are present */ public void validate() throws MessageException { List requiredFields = getRequiredFields(); Iterator paramIter = _params.getParameters().iterator(); while (paramIter.hasNext()) { Parameter param = (Parameter) paramIter.next(); if (!param.isValid()) throw new MessageException("Invalid parameter: " + param); } if (requiredFields == null) return; Iterator reqIter = requiredFields.iterator(); while(reqIter.hasNext()) { String required = (String) reqIter.next(); if (! hasParameter(required)) throw new MessageException( "Required parameter missing: " + required); } } public List getRequiredFields() { return null; } public String keyValueFormEncoding() { return _params.toString(); } public String wwwFormEncoding() { StringBuffer allParams = new StringBuffer(""); List parameters = _params.getParameters(); Iterator iterator = parameters.iterator(); while (iterator.hasNext()) { Parameter parameter = (Parameter) iterator.next(); // All of the keys in the request message MUST be prefixed with "openid." if ( ! parameter.getKey().startsWith("openid.")) allParams.append("openid."); try { allParams.append(URLEncoder.encode(parameter.getKey(), "UTF-8")); allParams.append('='); allParams.append(URLEncoder.encode(parameter.getValue(), "UTF-8")); allParams.append('&'); } catch (UnsupportedEncodingException e) { return null; } } // remove the trailing '&' if (allParams.length() > 0) allParams.deleteCharAt(allParams.length() -1); return allParams.toString(); } /** * Gets the URL where the message should be sent, where applicable. * Null for received messages. * * @param httpGet If true, the wwwFormEncoding() is appended to the * destination URL; the return value should be used * with a GET-redirect. * If false, the verbatim destination URL is returned, * which should be used with a FORM POST redirect. * * @see #wwwFormEncoding() */ public String getDestinationUrl(boolean httpGet) { if (_destinationUrl == null) throw new IllegalStateException("Destination URL not set; " + "is this a received message?"); if (httpGet) // append wwwFormEncoding to the destination URL { boolean hasQuery = _destinationUrl.indexOf("?") > 0; String initialChar = hasQuery ? "&" : "?"; return _destinationUrl + initialChar + wwwFormEncoding(); } else // should send the keyValueFormEncoding in POST data return _destinationUrl; } // ------------ extensions implementation ------------ /** * Adds a new extension factory. * * @param clazz The implementation class for the extension factory, * must implement {@link MessageExtensionFactory}. */ public static void addExtensionFactory(Class clazz) throws MessageException { try { MessageExtensionFactory extensionFactory = (MessageExtensionFactory) clazz.newInstance(); if (DEBUG) _log.debug("Adding extension factory for " + extensionFactory.getTypeUri()); _extensionFactories.put(extensionFactory.getTypeUri(), clazz); } catch (Exception e) { throw new MessageException( "Cannot instantiante message extension factory class: " + clazz.getName()); } } /** * Returns true if there is an extension factory available for extension * identified by the specified Type URI, or false otherwise. * * @param typeUri The Type URI that identifies an extension. */ public static boolean hasExtensionFactory(String typeUri) { return _extensionFactories.containsKey(typeUri); } /** * Gets a MessageExtensionFactory for the specified Type URI * if an implementation is available, or null otherwise. * * @param typeUri The Type URI that identifies a extension. * @see MessageExtensionFactory Message */ public static MessageExtensionFactory getExtensionFactory(String typeUri) { if (! hasExtensionFactory(typeUri)) return null; MessageExtensionFactory extensionFactory; try { Class extensionClass = (Class) _extensionFactories.get(typeUri); extensionFactory = (MessageExtensionFactory) extensionClass.newInstance(); } catch (Exception e) { _log.error("Error getting extension factory for " + typeUri); return null; } return extensionFactory; } /** * Returns true if the message has parameters for the specified * extension type URI. * * @param typeUri The URI that identifies the extension. */ public boolean hasExtension(String typeUri) { return _extAliases.containsKey(typeUri); } /** * Gets a set of extension Type URIs that are present in the message. */ public Set getExtensions() { return _extAliases.keySet(); } /** * Retrieves the extension alias that will be used for the extension * identified by the supplied extension type URI. *

* If the message contains no parameters for the specified extension, * null will be returned. * * @param extensionTypeUri The URI that identifies the extension * @return The extension alias associated with the * extension specifid by the Type URI */ public String getExtensionAlias(String extensionTypeUri) { return (_extAliases.get(extensionTypeUri) != null) ? (String) _extAliases.get(extensionTypeUri) : null; } /** * Adds a set of extension-specific parameters to a message. *

* The parameter names must NOT contain the "openid." * prefix; it will be generated dynamically, ensuring there are no conflicts * between extensions. * * @param extension A MessageExtension containing parameters * to be added to the message */ public void addExtension(MessageExtension extension) throws MessageException { String typeUri = extension.getTypeUri(); if (hasExtension(typeUri)) throw new MessageException("Extension already present: " + typeUri); String alias = "ext" + Integer.toString(++ _extCounter); // use the hardcoded "sreg" alias for SREG, for seamless interoperation // between SREG10/OpenID1 and SREG11/OpenID2 if (SRegMessage.OPENID_NS_SREG.equals(typeUri)) alias = "sreg"; _extAliases.put(typeUri, alias); if (DEBUG) _log.debug("Adding extension; type URI: " + typeUri + " alias: " +alias); set("openid.ns." + alias, typeUri); Iterator iter = extension.getParameters().getParameters().iterator(); while (iter.hasNext()) { Parameter param = (Parameter) iter.next(); String paramName = param.getKey().length() > 0 ? "openid." + alias + "." + param.getKey() : "openid." + alias; set(paramName, param.getValue()); } if (this instanceof AuthSuccess) { if (extension.signRequired()) ((AuthSuccess)this).addSignExtension(typeUri); if ( ((AuthSuccess)this).getSignExtensions().contains(typeUri) ) ((AuthSuccess)this).buildSignedList(); } } /** * Retrieves the parameters associated with a protocol extension, * specified by the given extension type URI. *

* The "openid.ns." parameter is NOT included in the * returned list. Also, the returned parameter names will have the * "openid.." prefix removed. * * @param extensionTypeUri The type URI that identifies the extension * @return A ParameterList with all parameters * associated with the specified extension */ private ParameterList getExtensionParams(String extensionTypeUri) { ParameterList extension = new ParameterList(); if (hasExtension(extensionTypeUri)) { String extensionAlias = getExtensionAlias(extensionTypeUri); Iterator iter = getParameters().iterator(); while (iter.hasNext()) { Parameter param = (Parameter) iter.next(); String paramName = null; if (param.getKey().startsWith("openid." + extensionAlias + ".")) paramName = param.getKey() .substring(8 + extensionAlias.length()); if (param.getKey().equals("openid." + extensionAlias)) paramName = ""; if (paramName != null) extension.set(new Parameter(paramName, param.getValue())); } } return extension; } /** * Gets a MessageExtension for the specified Type URI if an implementation * is available, or null otherwise. *

* The returned object will contain the parameters from the message * belonging to the specified extension. * * @param typeUri The Type URI that identifies a extension. */ public MessageExtension getExtension(String typeUri) throws MessageException { if (!_extesion.containsKey(typeUri)) { if (hasExtensionFactory(typeUri)) { MessageExtensionFactory extensionFactory = getExtensionFactory(typeUri); String mode = getParameterValue("openid.mode"); MessageExtension extension = extensionFactory.getExtension( getExtensionParams(typeUri), mode.startsWith("checkid_")); if (this instanceof AuthSuccess && extension.signRequired()) { List signedParams = Arrays.asList( ((AuthSuccess)this).getSignList().split(",") ); String alias = getExtensionAlias(typeUri); if (! signedParams.contains("ns." + alias)) throw new MessageException("Namespace declaration for extension " + typeUri + " MUST be signed"); Iterator iter = extension.getParameters().getParameters().iterator(); while (iter.hasNext()) { Parameter param = (Parameter) iter.next(); if (! signedParams.contains(alias + "." + param.getKey())) { throw new MessageException( "Extension " + typeUri + " MUST be signed; " + "field " + param.getKey() + " is NOT signed."); } } } _extesion.put(typeUri, extension); } else throw new MessageException("Cannot instantiate extension: " + typeUri); } if (DEBUG) _log.debug("Extracting " + typeUri +" extension from message..."); return (MessageExtension) _extesion.get(typeUri); } } openid4java-0.9.6.662/src/org/openid4java/message/MessageExtension.java0000644001501200150120000000373711034531513025124 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; /** * Interface for building OpenID extensions. *

* Classes that implement this interface should provide a default constructor * and register their Type URIs with the MessageExtensionFactory. * * @see MessageExtensionFactory Message * @author Marius Scurtescu, Johnny Bufu */ public interface MessageExtension { /** * Gets the TypeURI that identifies a extension to the OpenID protocol. */ public String getTypeUri(); /** * Gets the extension-specific parameters. *

* Implementations MUST NOT prefix the parameter names with * "openid.". The alias is managed internally by the Message class, * when a extension is attached to an OpenID messaage. * * @see Message */ public ParameterList getParameters(); /** * Sets the extension-specific parameters. *

* Implementations MUST NOT prefix the parameter names with * "openid.". The alias is managed internally by the Message class, * when a extension is attached to an OpenID messaage. * @param params * @see Message */ public void setParameters(ParameterList params); /** * Used by the core OpenID authentication implementation to learn whether * an extension provies authentication services. *

* If the extension provides authentication services, * the 'openid.identity' and 'openid.signed' parameters are optional. * * @return True if the extension provides authentication services, * false otherwise. */ public boolean providesIdentifier(); /** * Flag for indicating that an extension must be signed. * * @return True if all the extension's parameters MUST be signed * in positive assertions, or false if there isn't such a * requirement. */ public boolean signRequired(); } openid4java-0.9.6.662/src/org/openid4java/message/AuthRequest.java0000644001501200150120000002467411102646027024123 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.association.Association; import org.openid4java.server.RealmVerifier; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; import java.util.Iterator; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class AuthRequest extends Message { private static Log _log = LogFactory.getLog(AuthRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String MODE_SETUP = "checkid_setup"; public static final String MODE_IMMEDIATE = "checkid_immediate"; public static final String SELECT_ID = "http://specs.openid.net/auth/2.0/identifier_select"; protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode" }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns", "openid.claimed_id", "openid.identity", "openid.assoc_handle", "openid.realm", "openid.trust_root", "openid.return_to" }); private RealmVerifier _realmVerifier; protected AuthRequest(String claimedId, String delegate, boolean compatibility, String returnToUrl, String handle, RealmVerifier verifier) { this(claimedId, delegate, compatibility, returnToUrl, handle, returnToUrl, verifier); } protected AuthRequest(String claimedId, String delegate, boolean compatibility, String returnToUrl, String handle, String realm, RealmVerifier verifier) { if (! compatibility) { set("openid.ns", OPENID2_NS); setClaimed(claimedId); } setIdentity(delegate); if ( returnToUrl != null ) setReturnTo(returnToUrl); if ( realm != null ) setRealm(realm); if (! Association.FAILED_ASSOC_HANDLE.equals(handle)) setHandle(handle); setImmediate(false); _realmVerifier = verifier; } protected AuthRequest(ParameterList params) { super(params); } public static AuthRequest createAuthRequest(String claimedId, String delegate, boolean compatibility, String returnToUrl, String handle, RealmVerifier verifier) throws MessageException { return createAuthRequest(claimedId, delegate, compatibility, returnToUrl, handle, returnToUrl, verifier); } public static AuthRequest createAuthRequest(String claimedId, String delegate, boolean compatibility, String returnToUrl, String handle, String realm, RealmVerifier verifier) throws MessageException { AuthRequest req = new AuthRequest(claimedId, delegate, compatibility, returnToUrl, handle, realm, verifier); req.validate(); if (DEBUG) _log.debug("Created auth request:\n" + req.keyValueFormEncoding()); return req; } public static AuthRequest createAuthRequest(ParameterList params, RealmVerifier realmVerifier) throws MessageException { AuthRequest req = new AuthRequest(params); req.setRealmVerifier(realmVerifier); req.validate(); if (DEBUG) _log.debug("Created auth request:\n" + req.keyValueFormEncoding()); return req; } public List getRequiredFields() { return requiredFields; } public void setOPEndpoint(URL opEndpoint) { if (opEndpoint != null) _destinationUrl = opEndpoint.toString(); } public String getOPEndpoint() { return _destinationUrl; } public void setImmediate(boolean immediate) { set("openid.mode", immediate ? MODE_IMMEDIATE : MODE_SETUP); if (DEBUG && immediate) _log.debug("Setting checkid_immediate auth request."); } public boolean isImmediate() { return MODE_IMMEDIATE.equals(getParameterValue("openid.mode")); } public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } public void setIdentity(String id) { set("openid.identity", id); } public String getIdentity() { return getParameterValue("openid.identity"); } public void setClaimed(String claimed) { set("openid.claimed_id", claimed); } public String getClaimed() { return getParameterValue("openid.claimed_id"); } public void setHandle(String handle) { set("openid.assoc_handle", handle); } public String getHandle() { return getParameterValue("openid.assoc_handle"); } public void setReturnTo(String returnTo) { set("openid.return_to", returnTo); } public String getReturnTo() { return getParameterValue("openid.return_to"); } public void setRealm(String realm) { set(isVersion2() ? "openid.realm" : "openid.trust_root", realm); } public String getRealm() { if (isVersion2()) return getParameterValue("openid.realm"); else return getParameterValue("openid.trust_root"); } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); if ( compatibility && hasParameter("openid.identity") && SELECT_ID.equals(getParameterValue("openid.identity"))) { throw new MessageException(SELECT_ID + " not supported in OpenID1", OpenIDException.AUTH_ERROR); } if ( hasParameter("openid.mode") && ! MODE_SETUP.equals(getParameterValue("openid.mode")) && ! MODE_IMMEDIATE.equals(getParameterValue("openid.mode"))) { throw new MessageException( "Invalid openid.mode value in auth request: " + getParameterValue("openid.mode"), OpenIDException.AUTH_ERROR); } // return_to must be a valid URL, if present try { if (getReturnTo() != null) new URL(getReturnTo()); } catch (MalformedURLException e) { throw new MessageException( "Error verifying return URL in auth request.", OpenIDException.AUTH_ERROR, e); } if ( ! hasParameter("openid.return_to") ) { if (compatibility) { throw new MessageException( "openid.return_to is mandatory in OpenID1 auth requests", OpenIDException.AUTH_ERROR); } else if ( ! hasParameter("openid.realm") ) { throw new MessageException( "openid.realm is mandatory if return_to is absent.", OpenIDException.AUTH_REALM_ERROR); } } if ( compatibility && hasParameter("openid.realm") ) { _log.warn("openid.realm should not be present in OpenID1 auth requests"); } if ( !compatibility && hasParameter("openid.trust_root") ) { _log.warn("openid.trust_root should not be present in OpenID2 auth requests."); } // figure out if 'claimed_id' and 'identity' are optional if ( ! hasParameter("openid.identity") ) { // not optional in v1 if (compatibility) { throw new MessageException( "openid.identity is required in OpenID1 auth requests", OpenIDException.AUTH_ERROR); } boolean hasAuthProvider = false; Iterator iter = getExtensions().iterator(); while (iter.hasNext()) { String typeUri = iter.next().toString(); try { MessageExtension extension = getExtension(typeUri); if (extension.providesIdentifier()) { hasAuthProvider = true; break; } } catch (MessageException ignore) { // do nothing } } // no extension provides authentication sevices - invalid message if ( !hasAuthProvider ) { throw new MessageException( "no identifier specified in auth request", OpenIDException.AUTH_ERROR); } // claimed_id must be present if and only if identity is present if ( hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.claimed_id must be present if and only if " + "openid.identity is present.", OpenIDException.AUTH_ERROR); } } else if ( ! compatibility && ! hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.clamied_id must be present in OpenID2 auth requests", OpenIDException.AUTH_ERROR); } if (getRealm() != null) { int validation = _realmVerifier.validate( getRealm(), getReturnTo(), compatibility); if ( RealmVerifier.OK != validation ) { throw new MessageException("Realm verification failed (" + validation + ") for: " + getRealm(), OpenIDException.AUTH_REALM_ERROR); } } } } openid4java-0.9.6.662/src/org/openid4java/message/AuthFailure.java0000644001501200150120000000372611034531513024052 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; /** * @author Marius Scurtescu, Johnny Bufu */ public class AuthFailure extends Message { private static Log _log = LogFactory.getLog(AuthFailure.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode" }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns" }); public AuthFailure(boolean compatibility, String returnTo) { set("openid.mode", MODE_CANCEL); if (! compatibility) set("openid.ns", OPENID2_NS); _destinationUrl = returnTo; } protected AuthFailure(ParameterList params) { super(params); } public static AuthFailure createAuthFailure(ParameterList params) throws MessageException { AuthFailure fail = new AuthFailure(params); fail.validate(); if (DEBUG) _log.debug("Retrieved auth failure from message parameters:\n" + fail.keyValueFormEncoding()); return fail; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } public void validate() throws MessageException { super.validate(); String mode = getParameterValue("openid.mode"); if (! MODE_CANCEL.equals(mode)) throw new MessageException( "Invalid openid.mode; expected " + MODE_CANCEL + " found: " + mode, OpenIDException.AUTH_ERROR); } } openid4java-0.9.6.662/src/org/openid4java/message/MessageExtensionFactory.java0000644001501200150120000000264311034531513026447 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; /** * Factory interface for creating message extension objects for a specific * message extension type URI. * * @see MessageExtension * @see Message * @author Marius Scurtescu, Johnny Bufu */ public interface MessageExtensionFactory { /** * Gets the extension type URI of the extension factory. */ public String getTypeUri(); /** * Builds a MessageExtension from a parameter list containing the * extension-specific parameters. *

* The parameters MUST NOT contain the openid. prefix. * * @param parameterList The extension parameters with the * openid. prefix removed. * @param isRequest Indicates whether the parameters were extracted * from an openid request (true), or from an openid * response (false). This may assist the factory * implementation in determining what object type * to instantiate. * @return MessageExtension implementation for the supplied * extension parameters. */ public MessageExtension getExtension( ParameterList parameterList, boolean isRequest) throws MessageException; } openid4java-0.9.6.662/src/org/openid4java/message/AssociationError.java0000644001501200150120000000575211220543150025125 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.association.AssociationSessionType; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class AssociationError extends DirectError { private static Log _log = LogFactory.getLog(AssociationError.class); public static final String ASSOC_ERR = "unsupported-type"; protected final static List requiredFields = Arrays.asList( new String[] { "ns", "error_code", "error", }); protected final static List optionalFields = Arrays.asList( new String[] { "assoc_type", "session_type" }); protected AssociationError(String msg, AssociationSessionType type) { super(msg); set("ns", OPENID2_NS); set("error_code", ASSOC_ERR); set("session_type", type.getSessionType()); set("assoc_type", type.getAssociationType()); } protected AssociationError(ParameterList params) { super(params); } public static AssociationError createAssociationError( String msg, AssociationSessionType type) { AssociationError err = new AssociationError(msg, type); try { err.validate(); } catch (MessageException e) { _log.error("Invalid association error message created, " + "type: " + type + " message: " + msg, e); } return err; } public static AssociationError createAssociationError(ParameterList params) { AssociationError err = new AssociationError(params); try { err.validate(); } catch (MessageException e) { _log.error("Invalid association error message created: " + err.keyValueFormEncoding(), e ); } return err; } public List getRequiredFields() { return requiredFields; } public void setAssociationSessionType(AssociationSessionType type) { set("session_type", type.getSessionType()); set("assoc_type", type.getAssociationType()); } public String getSessionType() { return getParameterValue("session_type"); } public String getAssocType() { return getParameterValue("assoc_type"); } private String getErrorCode() { return getParameterValue("error_code"); } public void validate() throws MessageException { super.validate(); if ( ! (ASSOC_ERR.equals(getErrorCode()) && OPENID2_NS.equals(getParameterValue("ns")) ) ) throw new MessageException("Invalid Association Error: " + "invalid error_code or missing ns param.", OpenIDException.ASSOC_ERROR); } } openid4java-0.9.6.662/src/org/openid4java/message/Parameter.java0000644001501200150120000000375611034531513023564 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import java.io.Serializable; /** * A key / value pair which is part of an OpenID message. * * @author Marius Scurtescu, Johnny Bufu * @see ParameterList */ public class Parameter implements Comparable, Serializable { private String _key; private String _value; public Parameter(String key, String value) { _key = key; _value = value; } public boolean isValid() { return !((_key != null && _key.indexOf(':') > -1) || (_key != null && _key.indexOf('\n') > -1) || (_value != null && _value.indexOf('\n') > -1)); //throw new IllegalArgumentException( // "Invalid characters (colon or newline) found in the " + // "key and/or value: \nkey=" + _key + "\nvalue=" + _value ); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; final Parameter that = (Parameter) obj; if (this._key == null ? that._key != null : !this._key.equals(that._key)) return false; return (this._value == null ? that._value == null : this._value.equals(that._value)); } public int hashCode() { int hash; hash = (_key != null ? _key.hashCode() : 0); hash = 29 * hash + (_value != null ? _value.hashCode() : 0); return hash; } public String getKey() { return _key; } public String getValue() { return _value; } public int compareTo(Object obj) { Parameter that = (Parameter) obj; int keyComp = this._key.compareTo(that._key); if (keyComp == 0) { return this._value.compareTo(that._value); } else { return keyComp; } } public String toString() { return _key + ":" + _value; } } openid4java-0.9.6.662/src/org/openid4java/message/ax/0000755001501200150120000000000011627733442021413 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/message/ax/FetchRequest.java0000644001501200150120000002626111130536343024655 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.ax; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.message.ParameterList; import java.net.URL; import java.net.MalformedURLException; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Attribute Exchange fetch requests. * * @see AxMessage Message * @author Marius Scurtescu, Johnny Bufu */ public class FetchRequest extends AxMessage { private static Log _log = LogFactory.getLog(FetchRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); private int _aliasCounter = 0; /** * Constructs a Fetch Request with an empty parameter list. */ protected FetchRequest() { _parameters.set(new Parameter("mode", "fetch_request")); if (DEBUG) _log.debug("Created empty fetch request."); } /** * Constructs a Fetch Request with an empty parameter list. */ public static FetchRequest createFetchRequest() { return new FetchRequest(); } /** * Constructs a FetchRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected FetchRequest(ParameterList params) { _parameters = params; } /** * Constructs a FetchRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ public static FetchRequest createFetchRequest(ParameterList params) throws MessageException { FetchRequest req = new FetchRequest(params); if (! req.isValid()) throw new MessageException("Invalid parameters for a fetch request"); if (DEBUG) _log.debug("Created fetch request from parameter list:\n" + params); return req; } /** * Adds an attribute to the fetch request. * * @param alias The attribute alias that will be associated * with the attribute type URI * @param typeUri The attribute type URI * @param required If true, marks the attribute as 'required'; * 'if_available' otherwise. * @param count The number of attribute values requested. * 0 for the special value "unlimited". */ public void addAttribute(String alias, String typeUri, boolean required, int count) throws MessageException { if ( alias.indexOf(',') > -1 || alias.indexOf('.') > -1 || alias.indexOf(':') > -1 || alias.indexOf('\n') > -1 ) throw new MessageException( "Characters [.,:\\n] are not allowed in attribute aliases: " + alias); _parameters.set(new Parameter("type." + alias, typeUri)); String level = required ? "required" : "if_available"; Parameter levelParam = _parameters.getParameter(level); Parameter newParam; if (levelParam == null) { newParam = new Parameter(level, alias); } else { newParam = new Parameter(level, levelParam.getValue() + "," + alias); _parameters.removeParameters(level); } _parameters.set(newParam); setCount(alias, count); if (DEBUG) _log.debug("Added new attribute to fetch request; type: " + typeUri + " alias: " + alias + " count: " + count + " required: " + required); } /** * Adds an attribute to the fetch request, with a default value-count of 1. * * @see #addAttribute(String, String, boolean, int) */ public void addAttribute(String alias, String typeUri, boolean required) throws MessageException { addAttribute(alias, typeUri, required, 1); } /** * Adds an attribute to the fetch request, with a default value-count of 1. * An alias is generated for the provided type URI. * * @see #addAttribute(String, String, boolean, int) */ public String addAttribute(String typeUri, boolean required) throws MessageException { String alias = generateAlias(); addAttribute(alias, typeUri, required, 1); return alias; } /** * Sets the desired number of attribute vaules requested for the specified * attribute alias. Special value 0 means "unlimited". * * @param alias The attribute alias. */ public void setCount(String alias, int count) { if (count == 0) _parameters.set(new Parameter("count." + alias, "unlimited")); else if (count > 1) _parameters.set( new Parameter("count." + alias, Integer.toString(count))); } /** * Returns the number of values requested for the specified attribute alias. * 1 (the default number) is returned if the count parameter is absent. * 0 is returned if the special value "unlimited" was requested. * * @param alias The attribute alias. */ public int getCount(String alias) { if ("unlimited".equals(_parameters.getParameterValue("count." + alias))) return 0; else if (_parameters.hasParameter("count." + alias)) return Integer.parseInt(_parameters.getParameterValue("count." + alias)); else return 1; } /** * Sets the optional 'update_url' parameter where the OP can later re-post * fetch-response updates to the values of the requested attributes. * * @param updateUrl The URL where the RP accepts later updates * to the requested attributes. */ public void setUpdateUrl(String updateUrl) throws MessageException { try { new URL(updateUrl); } catch (MalformedURLException e) { throw new MessageException("Invalid update_url: " + updateUrl); } if (DEBUG) _log.debug("Setting fetch request update_url: " + updateUrl); _parameters.set(new Parameter("update_url", updateUrl)); } /** * Gets the optional 'update_url' parameter if available, or null otherwise. */ public String getUpdateUrl() { return _parameters.hasParameter("update_url") ? _parameters.getParameterValue("update_url") : null; } /** * Returns a map with the requested attributes. * * @param required If set to true the list of 'required' attributes * is returned, otherwise the list of 'if_available' * attributes. * @return Map of attribute aliases -> attribute type URIs. */ public Map getAttributes(boolean required) { HashMap attributes = new LinkedHashMap(); String level = required ? "required" : "if_available"; Parameter param = _parameters.getParameter(level); if (param != null) { String[] values = param.getValue().split(","); for (int i = 0; i < values.length; i++) { String alias = values[i]; attributes.put(alias, _parameters.getParameterValue("type." + alias)); } } return attributes; } /** * Gets all requested attributes (required and optional). * * @return Map of attribute aliases -> attribute type URIs. */ public Map getAttributes() { Map attributes = getAttributes(true); attributes.putAll(getAttributes(false)); return attributes; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ public boolean isValid() { if ( ! _parameters.hasParameter("required") && ! _parameters.hasParameter("if_available") ) { _log.warn("One of 'required' or 'if_available' parameters must be present."); return false; } if ( ! _parameters.hasParameter("mode") || ! "fetch_request".equals(_parameters.getParameterValue("mode"))) { _log.warn("Invalid mode value in fetch_request: " + _parameters.getParameterValue("mode")); return false; } if (_parameters.hasParameter("required")) { String[] aliases = _parameters.getParameterValue("required").split(","); for (int i = 0; i < aliases.length; i++) { String alias = aliases[i]; if ( ! _parameters.hasParameter("type." + alias) ) { _log.warn("Type missing for attribute alias: " + alias); return false; } if (! checkCount(alias)) return false; } } if ( _parameters.hasParameter("if_available")) { String[] aliases = _parameters.getParameterValue("if_available").split(","); for (int i = 0; i < aliases.length; i++) { String alias = aliases[i]; if ( ! _parameters.hasParameter("type." + alias) ) { _log.warn("Type missing for attribute alias: " + alias); return false; } if (! checkCount(alias)) return false; } } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (! paramName.equals("mode") && ! paramName.startsWith("type.") && ! paramName.startsWith("count.") && ! paramName.equals("required") && ! paramName.equals("if_available") && ! paramName.equals("update_url")) { _log.warn("Invalid parameter name in fetch request: " + paramName); //return false; } } return true; } private boolean checkCount(String alias) { int count = getCount(alias); if ( count < 0 || ( count == 0 && ! "unlimited".equals(_parameters.getParameterValue("count." + alias))) ) { _log.warn("Invalid value for count." + alias + ": " + _parameters.getParameterValue("count." + alias)); return false; } return true; } private synchronized String generateAlias() { return "attr" + Integer.toString(++ _aliasCounter); } } openid4java-0.9.6.662/src/org/openid4java/message/ax/StoreRequest.java0000644001501200150120000000522211130536343024712 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.ax; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.openid4java.message.ParameterList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Attribute Exchange store requests. * * @author Marius Scurtescu, Johnny Bufu */ public class StoreRequest extends AxPayload { private static Log _log = LogFactory.getLog(StoreRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Constructs a Store Request with an empty parameter list. */ protected StoreRequest() { _parameters.set(new Parameter("mode", "store_request")); if (DEBUG) _log.debug("Created empty store request."); } /** * Constructs a Store Request with an empty parameter list. */ public static StoreRequest createStoreRequest() { return new StoreRequest(); } /** * Constructs a StoreRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected StoreRequest(ParameterList params) { _parameters = params; } /** * Constructs a StoreRequest from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ public static StoreRequest createStoreRequest(ParameterList params) throws MessageException { StoreRequest req = new StoreRequest(params); if (! req.isValid()) throw new MessageException("Invalid parameters for a store request"); if (DEBUG) _log.debug("Created store request from parameter list:\n" + params); return req; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ public boolean isValid() { if ( ! _parameters.hasParameter("mode") || ! "store_request".equals(_parameters.getParameterValue("mode"))) { _log.warn("Invalid mode value in store_request: " + _parameters.getParameterValue("mode")); return false; } return super.isValid(); } } openid4java-0.9.6.662/src/org/openid4java/message/ax/StoreResponse.java0000644001501200150120000001031611102646027025060 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.ax; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Attribute Exchange store responses. * * @author Marius Scurtescu, Johnny Bufu */ public class StoreResponse extends AxMessage { private static Log _log = LogFactory.getLog(StoreResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Constructs a Store Response with an empty parameter list. */ protected StoreResponse() { _parameters.set(new Parameter("mode", "store_response_success")); if (DEBUG) _log.debug("Created empty store request."); } /** * Constructs a Store Response with an empty parameter list. */ public static StoreResponse createStoreResponse() { return new StoreResponse(); } /** * Constructs a StoreResponse from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected StoreResponse(ParameterList params) { super(params); } /** * Constructs a StoreResponse from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ public static StoreResponse createStoreResponse(ParameterList params) throws MessageException { StoreResponse resp = new StoreResponse(params); if (! resp.isValid()) throw new MessageException("Invalid parameters for a store response"); if (DEBUG) _log.debug("Created store response from parameter list:\n" + params); return resp; } /** * Marks the Store Response as a failure, by setting the appropirate * parameters. * * @param description Describes the error condition leading to * the failure response */ public void setFailure(String description) { _parameters.set(new Parameter("mode", "store_response_failure")); if (description != null) _parameters.set(new Parameter("error", description)); } /** * Returns true if the Store Response is a failure message, true if it is * a success response. */ public boolean hasFailed() { return "store_response_failure".equals( _parameters.getParameterValue("mode") ); } /** * Gets the status of the Store Response if the 'status' parameter is part * of the response, or null otherwise. */ public String getErrorDescription() { return _parameters.getParameterValue("error"); } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ private boolean isValid() { if ( ! _parameters.hasParameter("mode") || ( ! "store_response_success".equals(_parameters.getParameterValue("mode")) && ! "store_response_failure".equals(_parameters.getParameterValue("mode")) ) ) { _log.warn("Invalid mode value in store response: " + _parameters.getParameterValue("mode")); return false; } Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { Parameter param = (Parameter) it.next(); String paramName = param.getKey(); if (! paramName.equals("mode") && ! paramName.equals("error")) { _log.warn("Invalid parameter name in store response: " + paramName); return false; } } return true; } } openid4java-0.9.6.662/src/org/openid4java/message/ax/AxPayload.java0000644001501200150120000002626111250064010024123 0ustar miguelmiguelpackage org.openid4java.message.ax; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.*; /** * @author jbufu */ public abstract class AxPayload extends AxMessage { private static Log _log = LogFactory.getLog(AxPayload.class); private static final boolean DEBUG = _log.isDebugEnabled(); private int _attrAliasCounter = 0; private synchronized String generateAlias() { return "attr" + Integer.toString(++ _attrAliasCounter); } /** * Adds an attribute to the attribute payload. * * @param alias The alias identifier that will be associated * with the attribute type URI. * @param typeUri The attribute type URI. * @param value The value of the attribute. */ public void addAttribute(String alias, String typeUri, String value) throws MessageException { if ( alias.indexOf(',') > -1 || alias.indexOf('.') > -1 || alias.indexOf(':') > -1 || alias.indexOf('\n') > -1 ) throw new MessageException( "Characters [.,:\\n] are not allowed in attribute aliases: " + alias); int count = getCount(alias); String index = ""; switch(count) { case 0: _parameters.set(new Parameter("type." + alias, typeUri)); break; case 1: // rename the existing one _parameters.set(new Parameter("value." + alias + ".1", getParameterValue("value." + alias))); _parameters.removeParameters("value." + alias); index = ".2"; break; default: index = "." +Integer.toString(count + 1); } _parameters.set(new Parameter("value." + alias + index, value)); setCount(alias, ++count); if (DEBUG) _log.debug("Added new attribute to AX payload; type: " + typeUri + " alias: " + alias + " count: " + count); } /** * Adds an attribute to the attribute payload, without the caller having to * specify an alias. An alias in the form "attrNN" will be automatically * generated. * * @param typeUri The attribute type URI. * @param value The attribute value. * @return The generated attribute alias. */ public String addAttribute(String typeUri, String value) { String alias = generateAlias(); // not calling the other addAttribute - extra overhead in checks there _parameters.set(new Parameter("type." + alias, typeUri)); _parameters.set(new Parameter("value." + alias, value)); if (DEBUG) _log.debug("Added new attribute to the AX payload; type: " + typeUri + " alias: " + alias); return alias; } /** * Adds the attributes in the supplied Map to the attribute payload. * A requested count of 1 is assumed for each attribute in the map. * * @param attributes Map. */ public void addAttributes(Map attributes) { String typeUri; Iterator iter = attributes.keySet().iterator(); while (iter.hasNext()) { typeUri = (String) iter.next(); addAttribute(typeUri, (String) attributes.get(typeUri)); } } /** * Returns a list with the attribute value(s) associated for the specified * attribute alias. * * @param alias The attribute alias. * @return List of attribute values. */ public List getAttributeValues(String alias) { List values = new ArrayList(); if (! _parameters.hasParameter("count." + alias)) values.add(getParameterValue("value." + alias)); else for (int i = 1; i <= getCount(alias); i++) values.add(getParameterValue("value." + alias + "." + Integer.toString(i))); return values; } /** * Get typeURI value for the specified attribute alias. */ public String getAttributeTypeUri(String alias) { return _parameters.getParameterValue("type." + alias); } /** * Gets the alias for an attribute type URI, if present. * * @param typeUri the attribyte type URI for which the alias is looked up * @return the attribute alias if present in the message, or null otherwise */ public String getAttributeAlias(String typeUri) { if (typeUri == null) return null; Parameter param; Iterator it = _parameters.getParameters().iterator(); while(it.hasNext()) { param = (Parameter) it.next(); if (param.getKey().startsWith("type.") && typeUri.equals(param.getValue())) return param.getKey().substring(5); } return null; } /** * Gets the (first) value for the specified attribute type URI. * * @param typeUri * @return */ public String getAttributeValueByTypeUri(String typeUri) { return getAttributeValue(getAttributeAlias(typeUri)); } /** * Returns a list with the attribute value(s) associated for the specified * attribute type URI. * * @param typeUri The attribute type URI. * @return List of attribute values. */ public List getAttributeValuesByTypeUri(String typeUri) { return getAttributeValues(getAttributeAlias(typeUri)); } /** * Gets the (first) value for the specified attribute alias. */ public String getAttributeValue(String alias) { return (_parameters.hasParameter("count." + alias) && getCount(alias) > 0) ? getParameterValue("value." + alias + ".1") : getParameterValue("value." + alias); } /** * Gets a list of attribute aliases. */ public List getAttributeAliases() { List aliases = new ArrayList(); Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (paramName.startsWith("type.")) { String alias = paramName.substring(5); if ( ! aliases.contains(alias) ) aliases.add(alias); } } return aliases; } /** * Gets a map with attribute aliases -> list of values. */ public Map getAttributes() { Map attributes = new HashMap(); Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (paramName.startsWith("type.")) { String alias = paramName.substring(5); if ( ! attributes.containsKey(alias) ) attributes.put(alias, getAttributeValues(alias)); } } return attributes; } /** * Gets a map with attribute aliases -> attribute type URI. */ public Map getAttributeTypes() { Map typeUris = new HashMap(); Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { Parameter param = (Parameter) it.next(); String paramName = param.getKey(); String paramType = param.getValue(); if (paramName.startsWith("type.")) { String alias = paramName.substring(5); if ( ! typeUris.containsKey(alias) ) typeUris.put(alias, paramType); } } return typeUris; } /** * Gets the number of values provided in the attribute payload for the * specified attribute alias. * * @param alias The attribute alias. */ public int getCount(String alias) { if (_parameters.hasParameter("count." + alias)) return Integer.parseInt(_parameters.getParameterValue("count." + alias)); else if (_parameters.hasParameter("value." + alias)) return 1; else return 0; } /** * Sets the number of values provided in the attribute payload for the * specified attribute alias. The value must be greater than 1. * * @param alias The attribute alias. * @param count The number of values. */ private void setCount(String alias, int count) { if (count > 1) _parameters.set( new Parameter("count." + alias, Integer.toString(count))); } protected boolean isValid() { Iterator it = _parameters.getParameters().iterator(); while (it.hasNext()) { String paramName = ((Parameter) it.next()).getKey(); if (! paramName.equals("mode") && ! paramName.startsWith("type.") && ! paramName.startsWith("count.") && ! paramName.startsWith("value.") && ! paramName.equals("update_url")) { _log.warn("Invalid parameter name in AX payload: " + paramName); //return false; } } return checkAttributes(); } private boolean checkAttributes() { List aliases = getAttributeAliases(); Iterator it = aliases.iterator(); while (it.hasNext()) { String alias = (String) it.next(); if (! _parameters.hasParameter("type." + alias)) { _log.warn("Type missing for attribute alias: " + alias); return false; } if ( ! _parameters.hasParameter("count." + alias) ) { if (_parameters.hasParameterPrefix("value." + alias + ".")) { _log.warn("Count parameter not present for alias: " + alias + "; value." + alias + ".[index] format is not allowed."); return false; } } else // count.alias present { if (_parameters.hasParameter("value." + alias)) { _log.warn("Count parameter present for alias: " + alias + "; should use value." + alias + ".[index] format."); return false; } int count = getCount(alias); if (count < 0) { _log.warn("Invalid value for count." + alias + ": " + count); return false; } for (int i = 1; i <= count; i++) { if (! _parameters.hasParameter("value." + alias + "." + Integer.toString(i))) { _log.warn("Value missing for alias: " + alias + "." + Integer.toString(i)); return false; } } } } return true; } } openid4java-0.9.6.662/src/org/openid4java/message/ax/FetchResponse.java0000644001501200150120000001363111130536343025020 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.ax; import org.openid4java.message.ParameterList; import org.openid4java.message.MessageException; import org.openid4java.message.Parameter; import java.net.URL; import java.net.MalformedURLException; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implements the extension for Attribute Exchange fetch responses. * * @author Marius Scurtescu, Johnny Bufu */ public class FetchResponse extends AxPayload { private static Log _log = LogFactory.getLog(FetchResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Constructs a Fetch Response with an empty parameter list. */ protected FetchResponse() { _parameters.set(new Parameter("mode", "fetch_response")); if (DEBUG) _log.debug("Created empty fetch response."); } /** * Constructs a Fetch Response with an empty parameter list. */ public static FetchResponse createFetchResponse() { return new FetchResponse(); } /** * Constructs a FetchResponse from a parameter list. *

* The parameter list can be extracted from a received message with the * getExtensionParams method of the Message class, and MUST NOT contain * the "openid.." prefix. */ protected FetchResponse(ParameterList params) { _parameters = params; } public static FetchResponse createFetchResponse(ParameterList params) throws MessageException { FetchResponse resp = new FetchResponse(params); if (! resp.isValid()) throw new MessageException("Invalid parameters for a fetch response"); if (DEBUG) _log.debug("Created fetch response from parameter list:\n" + params); return resp; } /** * Creates a FetchResponse from a FetchRequest message and the data released * by the user. * * @param req FetchRequest message. * @param userData The userData may be a Map * or a Map values>. The attribute values * are provided by the calling application. If a list of values is * specified per attribute, at most n will be sent, where n is the * number of attribute values requested in the FetchRequest. * @return Properly formed FetchResponse. */ public static FetchResponse createFetchResponse(FetchRequest req, Map userData) throws MessageException { FetchResponse resp = new FetchResponse(); // go through each requested attribute Map attributes = req.getAttributes(); for (Iterator i = attributes.keySet().iterator(); i.hasNext(); ) { String alias = (String) i.next(); // find attribute in userData Object value = userData.get(alias); // if the value isn't there, skip over it if (value == null) { continue; } // if the value is a string, add the single attribute to the response if (value instanceof String) { resp.addAttribute(alias, (String) attributes.get(alias), (String)value); } // if the value is a list (of string) iteratively add each attribute to the response else if (value instanceof List) { Iterator values = ((List)value).iterator(); // only send up the the maximum requested number int max = req.getCount(alias); int count; for (count = 0; count < max && values.hasNext(); count++) { // don't add null values to the response String val = (String)values.next(); if (val == null) { count--; // disregard this as a value as we are skipping over it continue; } resp.addAttribute(alias, (String) attributes.get(alias), val); } } } return resp; } /** * Sets the optional 'update_url' parameter where the OP can later re-post * fetch-response updates for the values of the requested attributes. * * @param updateUrl The URL where the RP accepts later updates * for the requested attributes. */ public void setUpdateUrl(String updateUrl) throws MessageException { try { new URL(updateUrl); } catch (MalformedURLException e) { throw new MessageException("Invalid update_url: " + updateUrl); } if (DEBUG) _log.debug("Setting fetch response update_url: " + updateUrl); _parameters.set(new Parameter("update_url", updateUrl)); } /** * Gets the optional 'update_url' parameter if available, or null otherwise. */ public String getUpdateUrl() { return _parameters.hasParameter("update_url") ? _parameters.getParameterValue("update_url") : null; } /** * Checks the validity of the extension. *

* Used when constructing a extension from a parameter list. * * @return True if the extension is valid, false otherwise. */ protected boolean isValid() { if ( ! _parameters.hasParameter("mode") || ! "fetch_response".equals(_parameters.getParameterValue("mode"))) { _log.warn("Invalid mode value in fetch_reponse: " + _parameters.getParameterValue("mode")); return false; } return super.isValid(); } } openid4java-0.9.6.662/src/org/openid4java/message/ax/AxMessage.java0000644001501200150120000001250511553420466024133 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message.ax; import org.openid4java.message.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Base class for the Attribute Exchange implementation. *

* Encapsulates: *

* * @see Message MessageExtension * @author Marius Scurtescu, Johnny Bufu */ public class AxMessage implements MessageExtension, MessageExtensionFactory { private static Log _log = LogFactory.getLog(AxMessage.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * The Attribute Exchange Type URI. */ public static final String OPENID_NS_AX = "http://openid.net/srv/ax/1.0"; /** * The Attribute Exchange extension-specific parameters. *

* The openid. prefix is not part of the parameter names */ protected ParameterList _parameters; /** * Constructs an empty (no parameters) Attribute Exchange extension. */ public AxMessage() { _parameters = new ParameterList(); if (DEBUG) _log.debug("Created empty AXMessage."); } /** * Constructs an Attribute Exchange extension with a specified list of * parameters. *

* The parameter names in the list should not contain the * openid.. */ public AxMessage(ParameterList params) { _parameters = params; if (DEBUG) _log.debug("Created AXMessage from parameter list:\n" + params); } /** * Gets the Type URI that identifies the Attribute Exchange extension. */ public String getTypeUri() { return OPENID_NS_AX; } /** * Gets ParameterList containing the Attribute Exchange extension-specific * parameters. *

* The openid. prefix is not part of the parameter names, * as it is handled internally by the Message class. *

* The openid.ns. parameter is also handled by * the Message class. * * @see Message */ public ParameterList getParameters() { return _parameters; } /** * Gets a the value of the parameter with the specified name. * * @param name The name of the parameter, * without the openid. prefix. * @return The parameter value, or null if not found. */ public String getParameterValue(String name) { return _parameters.getParameterValue(name); } /** * Sets the extension's parameters to the supplied list. *

* The parameter names in the list should not contain the * openid. prefix. */ public void setParameters(ParameterList params) { _parameters = params; } /** * Attribute exchange doesn't implement authentication services. * * @return false */ public boolean providesIdentifier() { return false; } /** * Attribute exchange parameters are required to be signed. * * @return true */ public boolean signRequired() { return true; } /** * Instantiates the apropriate Attribute Exchange object (fetch / store - * request / response) for the supplied parameter list. * * @param parameterList The Attribute Exchange specific parameters * (without the openid. prefix) * extracted from the openid message. * @param isRequest Indicates whether the parameters were * extracted from an OpenID request (true), * or from an OpenID response. * @return MessageExtension implementation for * the supplied extension parameters. * @throws MessageException If a Attribute Exchange object could not be * instantiated from the supplied parameter list. */ public MessageExtension getExtension( ParameterList parameterList, boolean isRequest) throws MessageException { String axMode = null; if (parameterList.hasParameter("mode")) { axMode = parameterList.getParameterValue("mode"); if ("fetch_request".equals(axMode)) return FetchRequest.createFetchRequest(parameterList); else if ("fetch_response".equals(axMode)) return FetchResponse.createFetchResponse(parameterList); else if ("store_request".equals(axMode)) return StoreRequest.createStoreRequest(parameterList); else if ("store_response_success".equals(axMode) || "store_response_failure".equals(axMode)) return StoreResponse.createStoreResponse(parameterList); } throw new MessageException("Invalid value for attribute exchange mode: " + axMode); } } openid4java-0.9.6.662/src/org/openid4java/message/IndirectError.java0000644001501200150120000000761711034531513024417 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class IndirectError extends Message { private static Log _log = LogFactory.getLog(IndirectError.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected IndirectError(String msg, String returnTo) { this(msg, returnTo, false); } protected IndirectError(String msg, String returnTo, boolean compatibility) { this(null, msg, returnTo, compatibility); } protected IndirectError(OpenIDException e, String msg, String returnTo, boolean compatibility) { set("openid.mode", "error"); set("openid.error", msg); _destinationUrl = returnTo; _exception = e; if (! compatibility) set("openid.ns", OPENID2_NS); } // exception that generated the error, if any private OpenIDException _exception; protected IndirectError(ParameterList params) { super(params); } public static IndirectError createIndirectError(OpenIDException e, String returnTo) { return createIndirectError(e, returnTo, false); } public static IndirectError createIndirectError(String msg, String returnTo) { return createIndirectError(msg, returnTo, false); } public static IndirectError createIndirectError(OpenIDException e, String returnTo, boolean compatibility) { return createIndirectError(e, e.getMessage(), returnTo, compatibility); } public static IndirectError createIndirectError(String msg, String returnTo, boolean compatibility) { return createIndirectError(null, msg, returnTo, compatibility); } public static IndirectError createIndirectError(OpenIDException e, String msg, String returnTo, boolean compatibility) { IndirectError err = new IndirectError(e, msg, returnTo, compatibility); try { err.validate(); } catch (MessageException ex) { _log.error("Invalid " + (compatibility? "OpenID1" : "OpenID2") + " indirect error message created for message: " + msg); } _log.debug("Created indirect error message:\n" + err.keyValueFormEncoding()); return err; } public static IndirectError createIndirectError(ParameterList params) { IndirectError err = new IndirectError(params); try { err.validate(); } catch (MessageException e) { _log.error("Invalid direct error message created: " + err.keyValueFormEncoding() ); } _log.debug("Created indirect error message:\n" + err.keyValueFormEncoding()); return err; } public OpenIDException getException() { return _exception; } public void setException(OpenIDException e) { this._exception = e; } public void setErrorMsg(String msg) { set("openid.error", msg); } public String getErrorMsg() { return getParameterValue("openid.error"); } public void setContact(String contact) { set("openid.contact", contact); } public String getContact() { return getParameterValue("openid.contact"); } public void setReference(String reference) { set("openid.reference", reference); } public String getReference() { return getParameterValue("openid.reference"); } } openid4java-0.9.6.662/src/org/openid4java/message/VerifyResponse.java0000644001501200150120000000554211034531513024622 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; /** * @author Marius Scurtescu, Johnny Bufu */ public class VerifyResponse extends Message { private static Log _log = LogFactory.getLog(VerifyResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList(new String[] { "is_valid" }); protected final static List optionalFields = Arrays.asList(new String[] { "ns", "invalidate_handle" }); protected VerifyResponse(boolean compatibility) { setSignatureVerified(false); if (! compatibility) set("ns", OPENID2_NS); } protected VerifyResponse(ParameterList params) { super(params); } public static VerifyResponse createVerifyResponse(boolean compatibility) throws MessageException { VerifyResponse resp = new VerifyResponse(compatibility); resp.validate(); if (DEBUG) _log.debug("Created verification response:\n" + resp.keyValueFormEncoding()); return resp; } public static VerifyResponse createVerifyResponse(ParameterList params) throws MessageException { VerifyResponse resp = new VerifyResponse(params); resp.validate(); if (DEBUG) _log.debug("Created verification response:\n" + resp.keyValueFormEncoding()); return resp; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("ns") && OPENID2_NS.equals(getParameterValue("ns")); } public void setSignatureVerified(boolean verified) { if (DEBUG) _log.debug("Setting is_valid to: " + verified); set("is_valid", verified ? "true" : "false"); } public boolean isSignatureVerified() { return "true".equals(getParameterValue("is_valid")); } public void setInvalidateHandle(String handle) { set("invalidate_handle", handle); } public String getInvalidateHandle() { return getParameterValue("invalidate_handle"); } public void validate() throws MessageException { super.validate(); if (! "true".equals(getParameterValue("is_valid")) && ! "false".equals(getParameterValue("is_valid")) ) { throw new MessageException( "Invalid is_valid value in verification response: " + getParameterValue("is_valid"), OpenIDException.VERIFY_ERROR); } } } openid4java-0.9.6.662/src/org/openid4java/message/AssociationRequest.java0000644001501200150120000002241711034531513025464 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.association.AssociationSessionType; import org.openid4java.association.AssociationException; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The OpenID Association Request message. *

* Handles OpenID 2.0 and OpenID 1.x messages. * * @see AssociationSessionType * @author Marius Scurtescu, Johnny Bufu */ public class AssociationRequest extends Message { private static Log _log = LogFactory.getLog(AssociationRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String MODE_ASSOC = "associate"; protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode", "openid.session_type", }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns", // not in v1 messages "openid.assoc_type", // can be missing in v1 "openid.dh_modulus", "openid.dh_gen", "openid.dh_consumer_public" }); /** * The Diffie-Hellman session containing the cryptografic data needed for * encrypting the MAC key exchange. *

* Null for no-encryption sessions. */ private DiffieHellmanSession _dhSess; /** * Creates an Association Request message with the * specified association type and "no-encryption" session. *

* The supplied type must be one of the "no-encryption" types, otherwise * a DiffieHellman session is required. * * @see #AssociationRequest(AssociationSessionType, DiffieHellmanSession) */ protected AssociationRequest(AssociationSessionType type) { this(type, null); } /** * Constructs an AssociationRequest message with the * specified association type and Diffie-Hellman session. * * @param dhSess Diffie-Hellman session to be used for this association; * if null, a "no-encryption" session is created. */ protected AssociationRequest(AssociationSessionType type, DiffieHellmanSession dhSess) { if (DEBUG) _log.debug("Creating association request, type: " + type + "DH session: " + dhSess); if (type.isVersion2()) set("openid.ns", OPENID2_NS); set("openid.mode", MODE_ASSOC); set("openid.session_type", type.getSessionType()); set("openid.assoc_type", type.getAssociationType()); _dhSess = dhSess; if (dhSess != null ) { set("openid.dh_consumer_public", _dhSess.getPublicKey()); // send both diffie-hellman generator and modulus if either are not the default values // (this meets v1.1 spec and is compatible with v2.0 spec) if (!DiffieHellmanSession.DEFAULT_GENERATOR_BASE64.equals(_dhSess.getGenerator()) || !DiffieHellmanSession.DEFAULT_MODULUS_BASE64.equals(_dhSess.getModulus())) { set("openid.dh_gen", _dhSess.getGenerator()); set("openid.dh_modulus", _dhSess.getModulus()); } } } /** * Constructs an AssociationRequest message from a parameter list. *

* Useful for processing incoming messages. */ protected AssociationRequest(ParameterList params) { super(params); } public static AssociationRequest createAssociationRequest( AssociationSessionType type) throws MessageException { return createAssociationRequest(type, null); } public static AssociationRequest createAssociationRequest( AssociationSessionType type, DiffieHellmanSession dhSess) throws MessageException { AssociationRequest req = new AssociationRequest(type, dhSess); // make sure the association / session type matches the dhSess if ( type == null || (dhSess == null && type.getHAlgorithm() != null) || (dhSess != null && ! dhSess.getType().equals(type) ) ) throw new MessageException( "Invalid association / session combination specified: " + type + "DH session: " + dhSess); req.validate(); if (DEBUG) _log.debug("Created association request:\n" + req.keyValueFormEncoding()); return req; } public static AssociationRequest createAssociationRequest( ParameterList params) throws MessageException { AssociationRequest req = new AssociationRequest(params); req.validate(); if (DEBUG) _log.debug("Created association request from message parameters:\n" + req.keyValueFormEncoding()); return req; } public List getRequiredFields() { return requiredFields; } /** * Returns true for OpenID 2.0 messages, false otherwise. */ public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } /** * Gets the association type parameter of the message. */ private String getAssociationType() { return getParameterValue("openid.assoc_type"); } /** * Gets the session type parameter of the message. */ private String getSessionType() { return getParameterValue("openid.session_type"); } /** * Gets the association / session type of the association request. * * @throws AssociationException */ public AssociationSessionType getType() throws AssociationException { return AssociationSessionType.create( getSessionType(), getAssociationType(), ! isVersion2() ); } /** * Gets the Diffie-Hellman session * Null for no-encryption association requests. */ public DiffieHellmanSession getDHSess() { return _dhSess; } /** * Gets the Diffie-Hellman modulus parameter of the message, or null for * messages with no-encryption sessions. */ public String getDhModulus() { String modulus = getParameterValue("openid.dh_modulus"); return modulus != null ? modulus : hasParameter("openid.dh_consumer_public") ? DiffieHellmanSession.DEFAULT_MODULUS_BASE64 : null; } /** * Gets the Diffie-Hellman generator parameter of the message, or null for * messages with no-encryption sessions. */ public String getDhGen() { String gen = getParameterValue("openid.dh_gen"); return gen != null ? gen : hasParameter("openid.dh_consumer_public") ? DiffieHellmanSession.DEFAULT_GENERATOR_BASE64 : null; } /** * Gets the Relying Party's (consumer) Diffie-Hellman public key, or null * for messages with no-encryption sessions. */ public String getDhPublicKey() { return getParameterValue("openid.dh_consumer_public"); } /** * Checks if the message is a valid OpenID Association Request. * * @throws MessageException if message validation failed. */ public void validate() throws MessageException { // basic checks super.validate(); // association / session type checks // (includes most of the compatibility stuff) AssociationSessionType type; try { // throws exception for invalid session / association types type = getType(); // make sure compatibility mode is the same for type and message if (type.isVersion2() != isVersion2()) { throw new MessageException("Protocol verison mismatch " + "between association session type: " + type + " and AssociationRequest message type.", OpenIDException.ASSOC_ERROR); } } catch (AssociationException e) { throw new MessageException( "Error verifying association request validity.", OpenIDException.ASSOC_ERROR, e); } // additional compatibility checks if (! isVersion2() && getSessionType() == null) { throw new MessageException( "sess_type cannot be omitted in OpenID1 association requests", OpenIDException.ASSOC_ERROR); } // DH seesion parameters if ( type.getHAlgorithm() != null && getDhPublicKey() == null) { throw new MessageException("DH consumer public key not specified.", OpenIDException.ASSOC_ERROR); } // no-enc session if (type.getHAlgorithm() == null && (getDhGen() != null || getDhModulus() != null || getDhPublicKey() != null) ) { throw new MessageException( "No-encryption session, but DH parameters specified.", OpenIDException.ASSOC_ERROR); } } } openid4java-0.9.6.662/src/org/openid4java/message/AuthSuccess.java0000644001501200150120000004337211551247205024102 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.discovery.DiscoveryException; import org.openid4java.util.InternetDateFormat; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import org.openid4java.OpenIDException; import java.util.*; import java.text.ParseException; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class AuthSuccess extends Message { private static Log _log = LogFactory.getLog(AuthSuccess.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode", "openid.return_to", "openid.assoc_handle", "openid.signed", "openid.sig" }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns", "openid.op_endpoint", "openid.claimed_id", "openid.identity", "openid.response_nonce", "openid.invalidate_handle" }); // required signed list in OpenID 1.x protected final static String signRequired1 = "return_to,identity"; // required signed list in OpenID 2.0 with claimed identifier protected final static String signRequired2 = "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle"; // required signed list in OpenID 2.0 with no claimed identifier protected final static String signRequired3 = "op_endpoint,return_to,response_nonce,assoc_handle"; protected List _signFields = new ArrayList(); protected List _signExtensions = new ArrayList(); protected AuthSuccess(String opEndpoint, String claimedId, String delegate, boolean compatibility, String returnTo, String nonce, String invalidateHandle, Association assoc, boolean signNow) throws AssociationException { if (! compatibility) { set("openid.ns", OPENID2_NS); setOpEndpoint(opEndpoint); setClaimed(claimedId); setNonce(nonce); } set("openid.mode", MODE_IDRES); setIdentity(delegate); setReturnTo(returnTo); if (invalidateHandle != null) setInvalidateHandle(invalidateHandle); setHandle(assoc.getHandle()); buildSignedList(); setSignature(signNow ? assoc.sign(getSignedText()) : ""); } protected AuthSuccess(ParameterList params) { super(params); } public static AuthSuccess createAuthSuccess( String opEndpoint, String claimedId, String delegate, boolean compatibility, String returnTo, String nonce, String invalidateHandle, Association assoc, boolean signNow) throws MessageException, AssociationException { AuthSuccess resp = new AuthSuccess(opEndpoint, claimedId, delegate, compatibility, returnTo, nonce, invalidateHandle, assoc, signNow); resp.validate(); if (DEBUG) _log.debug("Created positive auth response:\n" + resp.keyValueFormEncoding()); return resp; } public static AuthSuccess createAuthSuccess(ParameterList params) throws MessageException { AuthSuccess resp = new AuthSuccess(params); resp.validate(); if (DEBUG) _log.debug("Created positive auth response:\n" + resp.keyValueFormEncoding()); return resp; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } public void setMode(String mode) throws MessageException { if (! mode.equals(MODE_IDRES) && ! mode.equals(MODE_CANCEL)) throw new MessageException("Unknown authentication mode: " + mode); set("openid.mode", mode); } public String getMode() { return getParameterValue("openid.mode"); } public void setOpEndpoint(String opEndpoint) { set("openid.op_endpoint", opEndpoint); } public String getOpEndpoint() { return getParameterValue("openid.op_endpoint"); } public void setIdentity(String id) { set("openid.identity", id); } public String getIdentity() throws DiscoveryException { return getParameterValue("openid.identity"); } public void setClaimed(String claimed) { set("openid.claimed_id", claimed); } public String getClaimed() { return getParameterValue("openid.claimed_id"); } public void setReturnTo(String returnTo) { set("openid.return_to", returnTo); _destinationUrl = returnTo; } public String getReturnTo() { return getParameterValue("openid.return_to"); } public void setNonce(String nonce) { set("openid.response_nonce", nonce); } public String getNonce() { return getParameterValue("openid.response_nonce"); } public void setInvalidateHandle(String handle) { set("openid.invalidate_handle", handle); } public String getInvalidateHandle() { return getParameterValue("openid.invalidate_handle"); } public void setHandle(String handle) { set("openid.assoc_handle", handle); } public String getHandle() { return getParameterValue("openid.assoc_handle"); } /** * Builds the list of fields that will be signed. Three input sources are * considered for this: *

*

* This method should be called after any field additions/deletions to/from * the message. */ public void buildSignedList() { StringBuffer toSign = ! isVersion2() ? new StringBuffer(signRequired1) : hasParameter("openid.identity") ? new StringBuffer(signRequired2) : new StringBuffer(signRequired3); List signList = new ArrayList(Arrays.asList(toSign.toString().split(","))); Iterator iter = _signFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); if ( ! signList.contains(field) ) { toSign.append(",").append(field); signList.add(field); } } // build list of field prefixes belonging to extensions List extensionPrefixes = new ArrayList(); iter = _signExtensions.iterator(); while(iter.hasNext()) { String alias = getExtensionAlias((String) iter.next()); if (alias != null) { // openid.ns. needs to be signed String nsSign = "ns." + alias; toSign.append(",").append(nsSign); signList.add(nsSign); extensionPrefixes.add(alias); } } // add exension fields to the signed list iter = getParameters().iterator(); while(iter.hasNext()) { String paramName = ((Parameter) iter.next()).getKey(); if (! paramName.startsWith("openid.")) continue; String signName = paramName.substring(7); int dotIndex = signName.indexOf("."); if (dotIndex > 0 && extensionPrefixes.contains(signName.substring(0,dotIndex)) && ! signList.contains(signName) ) { toSign.append(",").append(signName); signList.add(signName); } } if (DEBUG) _log.debug("Setting fields to be signed: " + toSign); set("openid.signed", toSign.toString()); //todo: if signature is alread set, recompute it } /** * Sets the messages fields that will be signed, in addition to the ones * required by the protocol to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * * @param userSuppliedList Comma-separated list of fields to be signed, * without the "openid." prefix * @see #setSignExtensions(String[]) */ public void setSignFields(String userSuppliedList) { if (userSuppliedList != null) { _signFields = Arrays.asList(userSuppliedList.split(",")); buildSignedList(); } } /** * Sets the list of messages fields that will be signed, in addition to * the ones required by the protocol to be signed and any additional * fields already configured to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * Should be called after all relevant extension fields have been * added to the message. * * @param extensions Array of extension namespace URIs to be signed. * @see #setSignFields(String) #setSignExtension */ public void setSignExtensions(String[] extensions) { if (extensions != null) { _signExtensions = new ArrayList(Arrays.asList(extensions)); buildSignedList(); } } /** * Adds the list of messages fields that will be signed, in addition to * the ones required by the protocol to be signed and any additional * fields already configured to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * Should be called after all relevant extension fields have been * added to the message. * * @param extensionNamespace Extension namespace URI to be signed. * @see #setSignFields(String) #setSignExtensions */ public void addSignExtension(String extensionNamespace) { if (! _signExtensions.contains(extensionNamespace)) { _signExtensions.add(extensionNamespace); buildSignedList(); } } public List getSignExtensions() { return _signExtensions; } public void setSignature(String sig) { set("openid.sig", sig); if(DEBUG) _log.debug("Added signature: " + sig); } public String getSignature() { return getParameterValue("openid.sig"); } public String getSignList() { return getParameterValue("openid.signed"); } /** * Return the text on which the signature is applied. */ public String getSignedText() { StringBuffer signedText = new StringBuffer(""); String[] signedParams = getParameterValue("openid.signed").split(","); for (int i = 0; i < signedParams.length; i++) { signedText.append(signedParams[i]); signedText.append(':'); String value = getParameterValue("openid." + signedParams[i]); if (value != null) signedText.append(value); signedText.append('\n'); } return signedText.toString(); } public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); if ( ! compatibility && ! hasParameter("openid.op_endpoint")) { throw new MessageException( "openid.op_endpoint is required in OpenID auth responses", OpenIDException.AUTH_ERROR); } try { // return_to must be a valid URL, if present if (getReturnTo() != null) new URL(getReturnTo()); } catch (MalformedURLException e) { throw new MessageException( "Invalid return_to: " + getReturnTo(), OpenIDException.AUTH_ERROR, e); } try { // op_endpoint must be a valid URL, if present if (isVersion2() && getOpEndpoint() != null) new URL(getOpEndpoint()); } catch (MalformedURLException e) { throw new MessageException( "Invalid op_endpoint: " + getOpEndpoint(), OpenIDException.AUTH_ERROR, e); } if (! MODE_IDRES.equals(getMode())) { throw new MessageException( "Invalid openid.mode value in auth response: " + getMode(), OpenIDException.AUTH_ERROR); } // figure out if 'identity' is optional if ( ! hasParameter("openid.identity") ) { // not optional in v1 if (compatibility) { throw new MessageException( "openid.identity is required in OpenID1 auth responses", OpenIDException.AUTH_ERROR); } boolean hasAuthExt = false; Iterator iter = getExtensions().iterator(); while (iter.hasNext()) { String typeUri = iter.next().toString(); try { MessageExtension extension = getExtension(typeUri); if (extension.providesIdentifier()) { hasAuthExt = true; break; } } catch (MessageException ignore) { // do nothing } } if (! hasAuthExt) { // no extension provides authentication sevices, invalid message throw new MessageException( "no identifier specified in auth request", OpenIDException.AUTH_ERROR); } // claimed_id must be present if and only if identity is present if ( hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.claimed_id must be present if and only if " + "openid.identity is present.", OpenIDException.AUTH_ERROR); } } else if ( ! compatibility && ! hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.clamied_id must be present in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce optional or not? String nonce = getNonce(); if ( !compatibility ) { if (nonce == null) { throw new MessageException( "openid.response_nonce is required in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce format InternetDateFormat _dateFormat = new InternetDateFormat(); try { _dateFormat.parse(nonce.substring(0, 20)); } catch (ParseException e) { throw new MessageException( "Error parsing nonce in auth response.", OpenIDException.AUTH_ERROR, e); } if (nonce.length() >255) { throw new MessageException( "nonce length must not exceed 255 characters", OpenIDException.AUTH_ERROR); } } else if (nonce != null) { _log.warn("openid.response_nonce present in OpenID1 auth response"); // return false; } List signedFields = Arrays.asList( getParameterValue("openid.signed").split(",")); // return_to must be signed if (!signedFields.contains("return_to")) { throw new MessageException("return_to must be signed", OpenIDException.AUTH_ERROR); } // either compatibility mode or nonce signed if ( compatibility == signedFields.contains("response_nonce") ) { _log.warn("response_nonce must be present and signed only in OpenID2 auth responses"); // return false; } // either compatibility mode or op_endpoint signed if ( compatibility == signedFields.contains("op_endpoint") ) { _log.warn("op_endpoint must be present and signed only in OpenID2 auth responses"); // return false; } // assoc_handle must be signed in v2 if ( ! compatibility && ! signedFields.contains("assoc_handle") ) { throw new MessageException( "assoc_handle must be signed in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // 'identity' and 'claimed_id' must be signed if present if (hasParameter("openid.identity") && ! signedFields.contains("identity")) { throw new MessageException( "openid.identity must be signed if present", OpenIDException.AUTH_ERROR); } if (hasParameter("openid.claimed_id") && ! signedFields.contains("claimed_id")) { throw new MessageException( "openid.claimed_id must be signed if present", OpenIDException.AUTH_ERROR); } } } openid4java-0.9.6.662/src/org/openid4java/message/VerifyRequest.java0000644001501200150120000000507411034531513024454 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; /** * VerifyRequest is a AuthSuccess with the openid.mode * switched to check_authentication. * * @author Marius Scurtescu, Johnny Bufu */ public class VerifyRequest extends AuthSuccess { private static Log _log = LogFactory.getLog(VerifyRequest.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String MODE_CHKAUTH = "check_authentication"; protected VerifyRequest(AuthSuccess authResp) { super(convertAuthSuccessParams(authResp)); } private static ParameterList convertAuthSuccessParams(AuthSuccess authResp) { ParameterList params = new ParameterList(authResp.getParameterMap()); params.set(new Parameter("openid.mode", MODE_CHKAUTH)); return params; } protected VerifyRequest(ParameterList params) { super(params); } public static VerifyRequest createVerifyRequest(AuthSuccess authResp) throws MessageException { VerifyRequest req = new VerifyRequest(authResp); req.validate(); if (DEBUG) _log.debug("Created verification request " + "from a positive auth response:\n" + req.keyValueFormEncoding()); return req; } public static VerifyRequest createVerifyRequest(ParameterList params) throws MessageException { VerifyRequest req = new VerifyRequest(params); req.validate(); if (DEBUG) _log.debug("Created verification request:\n" + req.keyValueFormEncoding()); return req; } public String getHandle() { return getParameterValue("openid.assoc_handle"); } public String getInvalidateHandle() { return getParameterValue("openid.invalidate_handle"); } public void validate() throws MessageException { if (! MODE_CHKAUTH.equals(getParameterValue("openid.mode"))) { throw new MessageException( "Invalid openid.mode in verification request: " + getParameterValue("openid.mode"), OpenIDException.VERIFY_ERROR); } set("openid.mode", MODE_IDRES); if (DEBUG) _log.debug("Delegating verification request validity check " + "to auth response..."); super.validate(); set("openid.mode", MODE_CHKAUTH); } } openid4java-0.9.6.662/src/org/openid4java/message/AssociationResponse.java0000644001501200150120000002545311034531513025635 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.association.Association; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.association.AssociationException; import org.openid4java.association.AssociationSessionType; import org.openid4java.OpenIDException; import java.util.List; import java.util.Arrays; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The OpenID Association Response message. *

* Handles OpenID 2.0 and OpenID 1.x messages. * * @see AssociationSessionType * @author Marius Scurtescu, Johnny Bufu */ public class AssociationResponse extends Message { private static Log _log = LogFactory.getLog(AssociationResponse.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "assoc_type", "assoc_handle", "expires_in" }); protected final static List optionalFields = Arrays.asList( new String[] { "ns", // not in v1 messages "session_type", // can be missing in v1 "mac_key", "enc_mac_key", "dh_server_public" }); /** * Constructs an AssociationResponse for a given association request. * * @param assocReq The association request that needs to be responded. * @param assoc The association which will be used to sign * authentication responses. */ protected AssociationResponse(AssociationRequest assocReq, Association assoc) throws AssociationException { if (DEBUG) _log.debug("Creating association response, type: " + assocReq.getType() + " association handle: " + assoc.getHandle()); if (assocReq.isVersion2()) set("ns", OPENID2_NS); AssociationSessionType type = assocReq.getType(); setType(type); setAssocHandle(assoc.getHandle()); Long expiryIn = new Long( ( assoc.getExpiry().getTime() - System.currentTimeMillis() ) / 1000 ); setExpire(expiryIn); if (type.getHAlgorithm() != null) // DH session, encrypt the MAC key { DiffieHellmanSession dhSess = DiffieHellmanSession.create( type, assocReq.getDhModulus(), assocReq.getDhGen() ); setPublicKey(dhSess.getPublicKey()); setMacKeyEnc(dhSess.encryptMacKey( assoc.getMacKey().getEncoded(), assocReq.getDhPublicKey() )); } else // no-encryption session, unecrypted MAC key { setMacKey(new String( Base64.encodeBase64(assoc.getMacKey().getEncoded()))); } } /** * Constructs an AssociationResponse message from a parameter list. *

* Useful for processing incoming messages. */ protected AssociationResponse(ParameterList params) { super(params); } public static AssociationResponse createAssociationResponse( AssociationRequest assocReq, Association assoc) throws MessageException, AssociationException { AssociationResponse resp = new AssociationResponse(assocReq, assoc); resp.validate(); if (DEBUG) _log.debug("Created association response:\n" + resp.keyValueFormEncoding()); return resp; } public static AssociationResponse createAssociationResponse(ParameterList params) throws MessageException { AssociationResponse resp = new AssociationResponse(params); resp.validate(); if (DEBUG) _log.debug("Created association response from message parameters:\n" + resp.keyValueFormEncoding() ); return resp; } public List getRequiredFields() { return requiredFields; } /** * Returns true for OpenID 2.0 messages, false otherwise. */ public boolean isVersion2() { return hasParameter("ns") && OPENID2_NS.equals(getParameterValue("ns")); } /** * Gets the association type parameter of the message. */ private String getAssociationType() { return getParameterValue("assoc_type"); } /** * Gets the session type parameter of the message. */ private String getSessionType() { return getParameterValue("session_type"); } /** * Sets the association / session type for the association response. */ public void setType(AssociationSessionType type) { set("session_type", type.getSessionType()); set("assoc_type", type.getAssociationType()); } /** * Gets the association / session type of the association response. * * @throws AssociationException */ public AssociationSessionType getType() throws AssociationException { return AssociationSessionType.create( getSessionType(), getAssociationType(), ! isVersion2() ); } /** * Sets the handle of the association. */ public void setAssocHandle(String handle) { set("assoc_handle", handle); } /** * Sets the lifetime, in seconds, of the association. */ public void setExpire(Long seconds) { set("expires_in", seconds.toString()); } /** * Sets the unecrtypted MAC key of the association. *

* Should be called only for association responses using no-encryption * sessions. * * @param key The unencrypted MAC key. */ public void setMacKey(String key) { set("mac_key", key); } /** * Sets the OP's (server's) public key for the association. * * @param key The server's public key for the association. */ public void setPublicKey(String key) { set("dh_server_public", key); } /** * Sets the encrypted MAC key of the association. *

* Should be called only for association responses using Diffie-Hellman * sessions. * * @param key The encrypted MAC key. */ public void setMacKeyEnc(String key) { set("enc_mac_key", key); } /** * Checks if the message is a valid OpenID Association Response.. * * @throws MessageException if message validation failed. */ public void validate() throws MessageException { // basic checks super.validate(); // association / session type checks // (includes most of the compatibility stuff) AssociationSessionType type; try { // throws exception for invalid session / association types type = getType(); // make sure compatibility mode is the same for type and message if (type.isVersion2() ^ isVersion2()) { throw new MessageException( "Protocol verison mismatch between association " + "session type: " + type + " and AssociationResponse message type.", OpenIDException.ASSOC_ERROR); } } catch (AssociationException e) { throw new MessageException( "Error verifying association response validity.", OpenIDException.ASSOC_ERROR, e); } // additional compatibility checks if (! isVersion2() && getAssociationType() == null) { throw new MessageException( "assoc_type cannot be omitted in OpenID1 responses", OpenIDException.ASSOC_ERROR); } String macKey; if (type.getHAlgorithm() != null) // DH session { if ( ! hasParameter("dh_server_public") || ! hasParameter("enc_mac_key") ) { throw new MessageException( "DH public key or encrypted MAC key missing.", OpenIDException.ASSOC_ERROR); } else macKey = getParameterValue("enc_mac_key"); } else // no-enc session { if ( !hasParameter("mac_key") ) { throw new MessageException("Missing MAC key.", OpenIDException.ASSOC_ERROR); } else macKey = getParameterValue("mac_key"); } // mac key size int macSize = Base64.decodeBase64(macKey.getBytes()).length * 8; if ( macSize != type.getKeySize()) { throw new MessageException("MAC key size: " + macSize + " doesn't match the association/session type: " + type, OpenIDException.ASSOC_ERROR); } } /** * Generates an Association object from an Association Response. * * @param dhSess The Diffie-Helman session containing the private key * used to encrypt / decrypt the MAC key exchange. * Should be null for no-encryption sessions. */ public Association getAssociation(DiffieHellmanSession dhSess) throws AssociationException { if (DEBUG) _log.debug("Retrieving MAC key from association response..."); String handle = getParameterValue("assoc_handle"); int expiresIn = Integer.parseInt( getParameterValue("expires_in") ); // get (and decrypt) the MAC key byte[] macKey; AssociationSessionType type = getType(); if ( type.getHAlgorithm() != null ) { macKey = dhSess.decryptMacKey( getParameterValue("enc_mac_key"), getParameterValue("dh_server_public") ); if (DEBUG) _log.debug("Decrypted MAC key (base64): " + new String(Base64.encodeBase64(macKey))); } else { macKey = Base64.decodeBase64( getParameterValue("mac_key").getBytes() ); if (DEBUG) _log.debug("Unencrypted MAC key (base64): " + getParameterValue("mac_key")); } Association assoc; if (Association.TYPE_HMAC_SHA1.equals(type.getAssociationType())) assoc = Association.createHmacSha1(handle, macKey, expiresIn); else if (Association.TYPE_HMAC_SHA256.equals(type.getAssociationType())) assoc = Association.createHmacSha256(handle, macKey, expiresIn); else throw new AssociationException("Unknown association type: " + type); if (DEBUG) _log.debug("Created association for handle: " + handle); return assoc; } } openid4java-0.9.6.662/src/org/openid4java/message/MessageException.java0000644001501200150120000000153711034531513025102 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class MessageException extends OpenIDException { public MessageException(String message) { super(message, MESSAGE_ERROR); } public MessageException(String message, int code) { super(message, code); } public MessageException(Throwable cause) { super(MESSAGE_ERROR, cause); } public MessageException(int code, Throwable cause) { super(code, cause); } public MessageException(String message, Throwable cause) { super(message, MESSAGE_ERROR, cause); } public MessageException(String message, int code, Throwable cause) { super(message, code, cause); } } openid4java-0.9.6.662/src/org/openid4java/discovery/0000755001501200150120000000000011627733442021366 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/discovery/DiscoveryInformation.java0000644001501200150120000001062011200624345026371 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import java.net.URL; import java.io.Serializable; import java.util.Set; import java.util.HashSet; /** * @author Marius Scurtescu, Johnny Bufu */ public class DiscoveryInformation implements Serializable { /** * The OP endpoint URL. */ URL _opEndpoint; /** * The claimed identifier, i.e. the user's identity key. */ Identifier _claimedIdentifier; /** * The delegate, or OP-Local identifier. * The key through which the OP remembers the user's account. */ String _delegate; /** * The OpenID protocol version, or target service type discovered through Yadis. */ String _version; /** * All service types discovered for the endpoint. */ Set _types; public final static String OPENID10 = "http://openid.net/signon/1.0"; public final static String OPENID11 = "http://openid.net/signon/1.1"; public final static String OPENID2 = "http://specs.openid.net/auth/2.0/signon"; public final static String OPENID2_OP = "http://specs.openid.net/auth/2.0/server"; public final static String OPENID2_RP = "http://specs.openid.net/auth/2.0/return_to"; public static final Set OPENID1_SIGNON_TYPES = new HashSet() {{ add(DiscoveryInformation.OPENID10); add(DiscoveryInformation.OPENID11); }}; public static final Set OPENID_SIGNON_TYPES = new HashSet() {{ addAll(DiscoveryInformation.OPENID1_SIGNON_TYPES); add(DiscoveryInformation.OPENID2); }}; public static final Set OPENID_OP_TYPES = new HashSet() {{ addAll(OPENID_SIGNON_TYPES); add(DiscoveryInformation.OPENID2_OP); }}; public static final Set OPENID_TYPES = new HashSet() {{ addAll(OPENID_OP_TYPES); add(DiscoveryInformation.OPENID2_RP); }}; public static boolean isOpenIDType(String type) { return OPENID_TYPES.contains(type); } public DiscoveryInformation(URL opEndpoint) throws DiscoveryException { this(opEndpoint, null, OPENID2_OP); } public DiscoveryInformation(URL opEndpoint, Identifier claimedIdentifier) throws DiscoveryException { this(opEndpoint, claimedIdentifier, OPENID2); } public DiscoveryInformation(URL opEndpoint, Identifier claimedIdentifier, String version) throws DiscoveryException { this(opEndpoint, claimedIdentifier, null, version); } public DiscoveryInformation(URL opEndpoint, Identifier claimedIdentifier, String delegate, String version) throws DiscoveryException { this(opEndpoint, claimedIdentifier, delegate, version, null); } public DiscoveryInformation(URL opEndpoint, Identifier claimedIdentifier, String delegate, String version, Set types) throws DiscoveryException { if (opEndpoint == null) throw new DiscoveryException("Null OpenID Provider endpoint."); _opEndpoint = opEndpoint; _claimedIdentifier = claimedIdentifier; _delegate = delegate; _version = version; _types = types; } public boolean hasClaimedIdentifier() { return _claimedIdentifier != null; } public boolean hasDelegateIdentifier() { return _delegate != null; } public URL getOPEndpoint() { return _opEndpoint; } public Identifier getClaimedIdentifier() { return _claimedIdentifier; } public String getDelegateIdentifier() { return _delegate; } public String getVersion() { return _version; } public void setVersion(String version) { this._version = version; } public boolean isVersion2() { return OPENID2.equals(_version) || OPENID2_OP.equals(_version); } public Set getTypes() { return _types; } public void setTypes(Set types) { this._types = types; } public boolean hasType(String type) { return _types != null && _types.contains(type); } public String toString() { return (isVersion2() ? "OpenID2" : "OpenID1") + "\nOP-endpoint:" + _opEndpoint + "\nClaimedID:" + _claimedIdentifier + "\nDelegate:" + _delegate; } } openid4java-0.9.6.662/src/org/openid4java/discovery/UrlIdentifier.java0000644001501200150120000001131611034531516024766 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.net.*; import java.util.Set; import java.util.HashSet; import java.io.UnsupportedEncodingException; /** * @author Marius Scurtescu, Johnny Bufu */ public class UrlIdentifier implements Identifier { private static Log _log = LogFactory.getLog(UrlIdentifier.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static final Set UNRESERVED_CHARACTERS = new HashSet(); static { for (char c = 'a'; c <= 'z'; c++) UNRESERVED_CHARACTERS.add(new Character(c)); for (char c = 'A'; c <= 'Z'; c++) UNRESERVED_CHARACTERS.add(new Character(c)); for (char c = '0'; c <= '9'; c++) UNRESERVED_CHARACTERS.add(new Character(c)); UNRESERVED_CHARACTERS.add(new Character('-')); UNRESERVED_CHARACTERS.add(new Character('.')); UNRESERVED_CHARACTERS.add(new Character('_')); UNRESERVED_CHARACTERS.add(new Character('~')); } private URL _urlIdentifier; public UrlIdentifier(String identifier) throws DiscoveryException { this(identifier, false); } public UrlIdentifier(String identifier, boolean removeFragment) throws DiscoveryException { _urlIdentifier = normalize(identifier, removeFragment); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final UrlIdentifier that = (UrlIdentifier) o; return _urlIdentifier.equals(that._urlIdentifier); } public int hashCode() { return _urlIdentifier.hashCode(); } public String getIdentifier() { return _urlIdentifier.toExternalForm(); } public String toString() { return _urlIdentifier.toExternalForm(); } public URL getUrl() { return _urlIdentifier; } public static URL normalize(String text) throws DiscoveryException { return normalize(text, false); } public static URL normalize(String text, boolean removeFragment) throws DiscoveryException { try { URI uri = new URI(text); URL url = uri.normalize().toURL(); String protocol = url.getProtocol().toLowerCase(); String host = url.getHost().toLowerCase(); int port = url.getPort(); String path = normalizeUrlEncoding(url.getPath()); String query = normalizeUrlEncoding(url.getQuery()); String fragment = normalizeUrlEncoding(url.getRef()); if (port == url.getDefaultPort()) port = -1; // start building the 'file' part for the URL constructor... String file = path; if ("".equals(file)) file = "/"; if (query != null) file = file + "?" + query; if (fragment != null && ! removeFragment) file = file + "#" + fragment; URL normalized = new URL(protocol, host, port, file); if (DEBUG) _log.debug("Normalized: " + text + " to: " + normalized); return normalized; } catch (MalformedURLException e) { throw new DiscoveryException("Invalid URL identifier", e); } catch (URISyntaxException e) { throw new DiscoveryException("Invalid URL identifier", e); } } private static String normalizeUrlEncoding(String text) { if (text == null) return null; int len = text.length(); StringBuffer normalized = new StringBuffer(len); for (int i = 0; i < len; i++) { char current = text.charAt(i); if (current == '%' && i < len - 2) { String percentCode = text.substring(i, i + 3).toUpperCase(); try { String str = URLDecoder.decode(percentCode, "ISO-8859-1"); char chr = str.charAt(0); if (UNRESERVED_CHARACTERS.contains(new Character(chr))) normalized.append(chr); else normalized.append(percentCode); } catch (UnsupportedEncodingException e) { normalized.append(percentCode); } i += 2; } else { normalized.append(current); } } return normalized.toString(); } } openid4java-0.9.6.662/src/org/openid4java/discovery/xri/0000755001501200150120000000000011627733442022170 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/discovery/xri/XriDotNetProxyResolver.java0000644001501200150120000001124011352263621027465 0ustar miguelmiguelpackage org.openid4java.discovery.xri; import com.google.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpStatus; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.XriIdentifier; import org.openid4java.discovery.xrds.XrdsParser; import org.openid4java.discovery.xrds.XrdsServiceEndpoint; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.HttpResponse; import org.openid4java.util.OpenID4JavaUtils; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; /** * @author jbufu */ public class XriDotNetProxyResolver implements XriResolver { private static Log _log = LogFactory.getLog(XriDotNetProxyResolver.class); private static final boolean DEBUG = _log.isDebugEnabled(); private final HttpFetcher _httpFetcher; private final static String PROXY_URL = "https://xri.net/"; private static final String XRDS_QUERY = "_xrd_r=application/xrds+xml"; private static final String XRDS_PARSER_CLASS_NAME_KEY = "discovery.xrds.parser"; private static final XrdsParser XRDS_PARSER; static { String className = OpenID4JavaUtils.getProperty(XRDS_PARSER_CLASS_NAME_KEY); if (DEBUG) _log.debug(XRDS_PARSER_CLASS_NAME_KEY + ":" + className); try { XRDS_PARSER = (XrdsParser) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } /** * Constructor for Guice installations. The default implementation * of the {@link HttpFetcherFactory} returns {@link HttpCache}s. */ @Inject public XriDotNetProxyResolver(HttpFetcherFactory httpFetcherfactory) { _httpFetcher = httpFetcherfactory.createFetcher( HttpRequestOptions.getDefaultOptionsForDiscovery()); } /** * Public constructor for non-guice installations. In this case, * we use the {@link HttpCache}-creating {@link HttpFetcherFactory}. */ public XriDotNetProxyResolver() { this(new HttpFetcherFactory()); } public List discover(XriIdentifier xri) throws DiscoveryException { String hxri = PROXY_URL + xri.getIdentifier() + "?" + XRDS_QUERY; _log.info("Performing discovery on HXRI: " + hxri); try { HttpResponse resp = _httpFetcher.get(hxri); if (resp == null || HttpStatus.SC_OK != resp.getStatusCode()) throw new DiscoveryException("Error retrieving HXRI: " + hxri); Set targetTypes = DiscoveryInformation.OPENID_OP_TYPES; List endpoints = XRDS_PARSER.parseXrds(resp.getBody(), targetTypes); List results = new ArrayList(); Iterator endpointIter = endpoints.iterator(); while (endpointIter.hasNext()) { XrdsServiceEndpoint endpoint = (XrdsServiceEndpoint) endpointIter.next(); Iterator typesIter = endpoint.getTypes().iterator(); while (typesIter.hasNext()) { String type = (String) typesIter.next(); if (!targetTypes.contains(type)) continue; try { results.add(new DiscoveryInformation( new URL(endpoint.getUri()), parseIdentifier(endpoint.getCanonicalId()), DiscoveryInformation.OPENID2.equals(type) ? endpoint.getLocalId() : DiscoveryInformation.OPENID1_SIGNON_TYPES.contains(type) ? endpoint.getDelegate() : null, type)); } catch (MalformedURLException e) { throw new DiscoveryException("Invalid endpoint URL discovered: " + endpoint.getUri()); } } } return results; } catch (IOException e) { throw new DiscoveryException("Error performing discovery on HXRI: " + hxri); } } public XriIdentifier parseIdentifier(String identifier) throws DiscoveryException { // todo: http://code.google.com/p/openid4java/issues/detail?id=63 _log.warn("Creating XRI identifier with the friendly XRI identifier as the IRI/URI normal forms."); return new XriIdentifier(identifier, identifier, identifier); } } openid4java-0.9.6.662/src/org/openid4java/discovery/xri/LocalXriResolver.java0000644001501200150120000002142511215306470026264 0ustar miguelmiguelpackage org.openid4java.discovery.xri; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.discovery.XriIdentifier; import org.openxri.XRI; import org.openxri.resolve.Resolver; import org.openxri.resolve.ResolverFlags; import org.openxri.resolve.ResolverState; import org.openxri.resolve.exception.PartialResolutionException; import org.openxri.xml.CanonicalID; import org.openxri.xml.SEPUri; import org.openxri.xml.Service; import org.openxri.xml.Status; import org.openxri.xml.XRD; import org.openxri.xml.XRDS; public class LocalXriResolver implements XriResolver { private static Log _log = LogFactory.getLog(LocalXriResolver.class); private static final boolean DEBUG = _log.isDebugEnabled(); private Resolver _openXriResolver; public LocalXriResolver() { if (DEBUG) _log.debug("Initializing local XRI resolver..."); try { _openXriResolver = new Resolver(null); } catch (Exception e) { throw new RuntimeException("Cannot initialize OpenXRI Resolver: " + e.getMessage(), e); } } public Resolver getResolver() { return _openXriResolver; } public List discover(XriIdentifier xri) throws DiscoveryException { try { ResolverFlags flags = new ResolverFlags(); flags.setCid(true); flags.setRefs(true); ResolverState state = new ResolverState(); XRDS xrds = _openXriResolver.resolveAuthToXRDS( new XRI(xri.getIdentifier()), flags, state); if (DEBUG) _log.debug("Retrieved XRDS:\n" + xrds.dump()); XRD xrd = xrds.getFinalXRD(); if (! xrd.getStatus().getCID().equals(Status.CID_VERIFIED)) { _log.error("Unverified CanonicalID: " + xrd.getCanonicalID() + " of: " + xri.getIdentifier()); throw new RuntimeException("Unverified CanonicalID: " + xrd.getCanonicalID() + " of: " + xri.getIdentifier()); } CanonicalID canonical = xrd.getCanonicalID(); if (canonical == null) throw new RuntimeException("Missing CanonicalID of: " + xri.getIdentifier()); _log.info("XRI resolution succeeded on " + xri.toString()); return extractDiscoveryInformation(xrds, xri, _openXriResolver); } catch (Exception e) { throw new DiscoveryException( "Cannot resolve XRI: " + xri, e); } } public XriIdentifier parseIdentifier(String identifier) throws DiscoveryException { XRI xri = new XRI(identifier); return new XriIdentifier(identifier, xri.toIRINormalForm(), xri.toURINormalForm()); } // --- XRI discovery patch from William Tan --- /** * Extracts OpenID discovery endpoints from a XRDS discovery result * for XRI identifiers. * * @param xrds The discovered XRDS document. * @param identifier The identifier on which discovery was performed. * @param xriResolver The XRI resolver to use for extraction of OpenID * service endpoints. * @return A list of DiscoveryInformation endpoints. * @throws DiscoveryException when invalid information is discovered. */ protected List extractDiscoveryInformation(XRDS xrds, XriIdentifier identifier, Resolver xriResolver) throws DiscoveryException { ArrayList endpoints = new ArrayList(); XRD xrd = xrds.getFinalXRD(); // try OP Identifier extractDiscoveryInformationOpenID( xriResolver, endpoints, xrd, identifier, DiscoveryInformation.OPENID2_OP, false // no CID ); // OpenID 2 signon extractDiscoveryInformationOpenID( xriResolver, endpoints, xrd, identifier, DiscoveryInformation.OPENID2, // sepType true // want CID ); // OpenID 1.x extractDiscoveryInformationOpenID( xriResolver, endpoints, xrd, identifier, DiscoveryInformation.OPENID11, true // wantCID ); extractDiscoveryInformationOpenID( xriResolver, endpoints, xrd, identifier, DiscoveryInformation.OPENID10, true // wantCID ); if (endpoints.size() == 0) _log.info("No OpenID service types found in the XRDS."); return endpoints; } protected boolean extractDiscoveryInformationOpenID( Resolver xriResolver, ArrayList out, XRD baseXRD, XriIdentifier identifier, String srvType, boolean wantCID) { try { ResolverFlags flags = new ResolverFlags(); flags.setCid(true); flags.setRefs(true); flags.setNoDefaultT(srvType != null); // we don't want default SEPs, only ones that really have the service type we are looking for ResolverState state = new ResolverState(); List services = xriResolver.selectServiceFromXRD( new XRDS(), baseXRD, new XRI(identifier.getIdentifier()), srvType, null, // sepMediaType flags, state ); Identifier claimedIdentifier = null; URL opEndpointUrl; CanonicalID canonID; if (! baseXRD.getStatus().getCID().equals(Status.CID_VERIFIED)) { _log.error("Unverified CanonicalID: " + baseXRD.getCanonicalID() + " of:" + identifier.getIdentifier()); return false; } if (wantCID) { canonID = baseXRD.getCanonicalID(); if (canonID == null) { _log.error("No CanonicalID found for " + srvType + " after XRI resolution of: " + identifier.getIdentifier()); return false; } claimedIdentifier = parseIdentifier(canonID.getValue()); _log.info("Using canonicalID as claimedID: " + claimedIdentifier.getIdentifier() + " for " + srvType); } Iterator it = services.iterator(); while (it.hasNext()) { Service srv = (Service)it.next(); Iterator itURI = srv.getPrioritizedURIs().iterator(); SEPUri sepURI; while (itURI.hasNext()) { sepURI = (SEPUri) itURI.next(); try { String urlString = xriResolver.constructURI( sepURI.getURI(), sepURI.getAppend(), new XRI(identifier.toString())); opEndpointUrl = new URL(urlString); DiscoveryInformation extracted = new DiscoveryInformation( opEndpointUrl, wantCID ? claimedIdentifier : null, null, srvType); _log.info("Added " + srvType + " endpoint: " + opEndpointUrl); out.add(extracted); } catch (MalformedURLException mue) { _log.warn("Ignoring malformed OP endpoint URL in XRDS file: " + sepURI.toString(), mue); } catch (IllegalArgumentException ee) { _log.warn("Ignoring invalid OP endpoint URL in XRDS file: " + sepURI.toString(), ee); } } } return true; } catch (PartialResolutionException e) { _log.error("XRI resolution failed for " + srvType, e); } catch (DiscoveryException de) { _log.error("XRDS discovery failed for " + srvType, de); } return false; } // --- end XRI discovery patch from William Tan --- } openid4java-0.9.6.662/src/org/openid4java/discovery/xri/XriResolver.java0000644001501200150120000000140111352263621025303 0ustar miguelmiguelpackage org.openid4java.discovery.xri; import com.google.inject.ImplementedBy; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.XriIdentifier; import org.openid4java.discovery.Identifier; import java.util.List; @ImplementedBy(XriDotNetProxyResolver.class) public interface XriResolver { /** * Performs OpenID discovery on the supplied XRI identifier. * * @param xri The XRI identifier * @return A list of DiscoveryInformation, ordered the discovered * priority. * @throws DiscoveryException if discovery failed. */ public List discover(XriIdentifier xri) throws DiscoveryException; XriIdentifier parseIdentifier(String identifier) throws DiscoveryException; } openid4java-0.9.6.662/src/org/openid4java/discovery/html/0000755001501200150120000000000011627733442022332 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/discovery/html/CyberNekoDOMHtmlParser.java0000644001501200150120000001275511140116773027422 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.html.dom.HTMLDocumentImpl; import org.openid4java.OpenIDException; import org.openid4java.util.OpenID4JavaDOMParser; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.html.HtmlParser; import org.openid4java.discovery.html.HtmlResult; import org.w3c.dom.NodeList; import org.w3c.dom.html.HTMLHeadElement; import org.w3c.dom.html.HTMLLinkElement; /** * A {@link HtmlParser} implementation using the DOMParser of CyberNeko HTML. * * @author Sutra Zhou * @since 0.9.4 * @see org.openid4java.util.OpenID4JavaDOMParser */ public class CyberNekoDOMHtmlParser implements HtmlParser { private static final Log _log = LogFactory.getLog(CyberNekoDOMHtmlParser.class); private static final boolean DEBUG = _log.isDebugEnabled(); /* * (non-Javadoc) * * @see org.openid4java.discovery.html.HtmlParser#parse(java.lang.String, * org.openid4java.discovery.html.HtmlResult) */ public void parseHtml(String htmlData, HtmlResult result) throws DiscoveryException { if (DEBUG) _log.debug("Parsing HTML data:\n" + htmlData); HTMLDocumentImpl doc = this.parseDocument(htmlData); NodeList heads = doc.getElementsByTagName("head"); if (heads.getLength() != 1) throw new DiscoveryException( "HTML response must have exactly one HEAD element, " + "found " + heads.getLength() + " : " + heads.toString(), OpenIDException.DISCOVERY_HTML_PARSE_ERROR); HTMLHeadElement head = (HTMLHeadElement) doc.getHead(); NodeList linkElements = head.getElementsByTagName("LINK"); for (int i = 0, len = linkElements.getLength(); i < len; i++) { HTMLLinkElement linkElement = (HTMLLinkElement) linkElements.item(i); setResult(linkElement.getRel(), linkElement.getHref(), result); } if (DEBUG) _log.debug("HTML discovery result:\n" + result); } private HTMLDocumentImpl parseDocument(String htmlData) throws DiscoveryException { OpenID4JavaDOMParser parser = new OpenID4JavaDOMParser(); try { parser.parse(OpenID4JavaDOMParser.createInputSource(htmlData)); } catch (Exception e) { throw new DiscoveryException("Error parsing HTML message", OpenIDException.DISCOVERY_HTML_PARSE_ERROR, e); } if (parser.isIgnoredHeadStartElement()) { throw new DiscoveryException( "HTML response must have exactly one HEAD element.", OpenIDException.DISCOVERY_HTML_PARSE_ERROR); } return (HTMLDocumentImpl) parser.getDocument(); } /** * Set the result from rel and href that * parsed from node link. * * @param rel * the rel * @param href * the href * @param result * the result to set * @throws DiscoveryException * if the value has been setted yet, that is to say, find more * than one entries with the same name(attribute value of * rel). */ private void setResult(String rel, String href, HtmlResult result) throws DiscoveryException { List relations = Arrays.asList(rel.split(" ")); // openid.server if (relations.contains("openid.server")) { if (result.getOP1Endpoint() != null) throw new DiscoveryException( "More than one openid.server entries found", OpenIDException.DISCOVERY_HTML_PARSE_ERROR); if (DEBUG) _log.debug("Found OpenID1 endpoint: " + href); result.setEndpoint1(href); } // openid.delegate if (relations.contains("openid.delegate")) { if (result.getDelegate1() != null) throw new DiscoveryException( "More than one openid.delegate entries found", OpenIDException.DISCOVERY_HTML_PARSE_ERROR); if (DEBUG) _log.debug("Found OpenID1 delegate: " + href); result.setDelegate1(href); } // openid2.provider if (relations.contains("openid2.provider")) { if (result.getOP2Endpoint() != null) throw new DiscoveryException( "More than one openid.server entries found", OpenIDException.DISCOVERY_HTML_PARSE_ERROR); if (DEBUG) _log.debug("Found OpenID2 endpoint: " + href); result.setEndpoint2(href); } // openid2.local_id if (relations.contains("openid2.local_id")) { if (result.getDelegate2() != null) throw new DiscoveryException( "More than one openid2.local_id entries found", OpenIDException.DISCOVERY_HTML_PARSE_ERROR); if (DEBUG) _log.debug("Found OpenID2 localID: " + href); result.setDelegate2(href); } } } openid4java-0.9.6.662/src/org/openid4java/discovery/html/HtmlResult.java0000644001501200150120000000515511034531515025273 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import org.openid4java.discovery.UrlIdentifier; import org.openid4java.discovery.DiscoveryException; import java.net.URL; import java.net.MalformedURLException; /** * Holds information obtained by performing HTML discovery on an URL. */ public class HtmlResult { private UrlIdentifier _claimedId; private URL _op1Endpoint; private String _delegate1; private URL _op2Endpoint; private String _delegate2; /** * Constructs an empty HtmlResult object. */ public HtmlResult() { } /** * Sets the claimed identifier. */ public void setClaimed(UrlIdentifier claimed) { _claimedId = claimed; } /** * Gets the claimed identifier. */ public UrlIdentifier getClaimedId() { return _claimedId; } public void setEndpoint1(String op1Endpoint) throws DiscoveryException { URL url; try { url = new URL(op1Endpoint); _op1Endpoint = url; } catch (MalformedURLException e) { throw new DiscoveryException( "Invalid openid.server URL: " + op1Endpoint); } } public URL getOP1Endpoint() { return _op1Endpoint; } public void setDelegate1(String delegate1) { _delegate1 = delegate1; } public String getDelegate1() { return _delegate1; } public void setEndpoint2(String op2Endpoint) throws DiscoveryException { URL url; try { url = new URL(op2Endpoint); _op2Endpoint = url; } catch (MalformedURLException e) { throw new DiscoveryException( "Invalid openid2.provider URL: " + op2Endpoint); } } public URL getOP2Endpoint() { return _op2Endpoint; } public void setDelegate2(String delegate2) { _delegate2 = delegate2; } public String getDelegate2() { return _delegate2; } public String toString() { return "ClaimedID:" + _claimedId + (_op2Endpoint != null ? "\nOpenID2-endpoint:" + _op2Endpoint.toString() : "") + (_delegate2 != null ? "\nOpenID2-localID:" + _delegate2 : "") + (_op1Endpoint != null ? "\nOpenID1-endpoint:" + _op1Endpoint.toString() : "") + (_delegate1 != null ? "\nOpenID1-delegate:" + _delegate1 : ""); } } openid4java-0.9.6.662/src/org/openid4java/discovery/html/HtmlParser.java0000644001501200150120000000123111102646027025241 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import org.openid4java.discovery.DiscoveryException; /** * Html parser. * * @author Sutra Zhou * @since 0.9.4 * @see #parseHtml(String, HtmlResult) */ public interface HtmlParser { /** * Parses the HTML data and stores in the result the discovered openid * information. * * @param htmlData * HTML data obtained from the URL identifier. * @param result * The HTML result. * @throws DiscoveryException */ void parseHtml(String htmlData, HtmlResult result) throws DiscoveryException; } openid4java-0.9.6.662/src/org/openid4java/discovery/html/HtmlResolver.java0000644001501200150120000001364411517704450025626 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import com.google.inject.Inject; import org.apache.http.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.List; import java.util.ArrayList; import org.openid4java.discovery.UrlIdentifier; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.HttpResponse; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.OpenID4JavaUtils; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu, Sutra Zhou */ public class HtmlResolver { private static Log _log = LogFactory.getLog(HtmlResolver.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static final String HTML_PARSER_CLASS_NAME_KEY = "discovery.html.parser"; private static final HtmlParser HTML_PARSER; private final HttpFetcher _httpFetcher; static { String className = OpenID4JavaUtils.getProperty(HTML_PARSER_CLASS_NAME_KEY); if (DEBUG) _log.debug(HTML_PARSER_CLASS_NAME_KEY + ":" + className); try { HTML_PARSER = (HtmlParser) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } @Inject public HtmlResolver(HttpFetcherFactory httpFetcherFactory) { _httpFetcher = httpFetcherFactory.createFetcher( HttpRequestOptions.getDefaultOptionsForDiscovery()); } /** * Maximum number of redirects to be followed for the HTTP calls. */ private int _maxRedirects = 10; /** * Gets the internal limit configured for the maximum number of redirects * to be followed for the HTTP calls. */ public int getMaxRedirects() { return _maxRedirects; } /** * Sets the maximum number of redirects to be followed for the HTTP calls. */ public void setMaxRedirects(int maxRedirects) { this._maxRedirects = maxRedirects; } /** * Performs HTML discovery on the supplied URL identifier. * * @param identifier The URL identifier. * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. */ public List discoverHtml(UrlIdentifier identifier) throws DiscoveryException { return discoverHtml(identifier, _httpFetcher); } /** * Performs HTML discovery on the supplied URL identifier. * * @param identifier The URL identifier. * @param httpFetcher {@link HttpFetcher} object to use for placing the call. * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. */ public List discoverHtml(UrlIdentifier identifier, HttpFetcher httpFetcher) throws DiscoveryException { // initialize the results of the HTML discovery HtmlResult result = new HtmlResult(); HttpRequestOptions requestOptions = httpFetcher.getRequestOptions(); requestOptions.setContentType("text/html"); try { HttpResponse resp = httpFetcher.get(identifier.toString(), requestOptions); if (HttpStatus.SC_OK != resp.getStatusCode()) throw new DiscoveryException( "GET failed on " + identifier.toString() + " Received status code: " + resp.getStatusCode(), OpenIDException.DISCOVERY_HTML_GET_ERROR); result.setClaimed( new UrlIdentifier(resp.getFinalUri()) ); if (resp.getBody() == null) throw new DiscoveryException( "No HTML data read from " + identifier.toString(), OpenIDException.DISCOVERY_HTML_NODATA_ERROR); HTML_PARSER.parseHtml(resp.getBody(), result); } catch (IOException e) { throw new DiscoveryException("Fatal transport error: ", OpenIDException.DISCOVERY_HTML_GET_ERROR, e); } _log.info("HTML discovery completed on: " + identifier); return extractDiscoveryInformation(result); } /** * Extracts OpenID discovery endpoints from a HTML discovery result. * * @param htmlResult HTML discovery result. * @return List of DiscoveryInformation endpoints. * @throws DiscoveryException when invalid information is discovered. */ private List extractDiscoveryInformation(HtmlResult htmlResult) throws DiscoveryException { ArrayList htmlList = new ArrayList(); if (htmlResult.getOP2Endpoint() != null) { DiscoveryInformation extracted = new DiscoveryInformation( htmlResult.getOP2Endpoint(), htmlResult.getClaimedId(), htmlResult.getDelegate2(), DiscoveryInformation.OPENID2); if (DEBUG) _log.debug("OpenID2-signon HTML discovery endpoint: " + extracted); htmlList.add(extracted); } if (htmlResult.getOP1Endpoint() != null) { DiscoveryInformation extracted = new DiscoveryInformation( htmlResult.getOP1Endpoint(), htmlResult.getClaimedId(), htmlResult.getDelegate1(), DiscoveryInformation.OPENID11); if (DEBUG) _log.debug("OpenID1-signon HTML discovery endpoint: " + extracted); htmlList.add(extracted); } return htmlList; } } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/0000755001501200150120000000000011627733442022477 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/discovery/yadis/YadisException.java0000644001501200150120000000154311034531516026263 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import org.openid4java.discovery.DiscoveryException; /** * @author Marius Scurtescu, Johnny Bufu */ public class YadisException extends DiscoveryException { public YadisException(String message) { super(message, YADIS_ERROR); } public YadisException(String message, int code) { super(message, code); } public YadisException(Throwable cause) { super(YADIS_ERROR, cause); } public YadisException(int code, Throwable cause) { super(code, cause); } public YadisException(String message, Throwable cause) { super(message, YADIS_ERROR, cause); } public YadisException(String message, int code, Throwable cause) { super(message, code, cause); } } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/YadisUrl.java0000644001501200150120000000662411102646027025074 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import java.net.URL; import java.net.MalformedURLException; import org.openid4java.OpenIDException; import org.openid4java.discovery.XriIdentifier; /** * Wrapper class for various identifiers that are resolvable to URLs * and can be used as YadisURLs with the Yadis protocol. * * @author Marius Scurtescu, Johnny Bufu */ public class YadisUrl { /** * A YadisURL is a regular URL, with a couple restrictions. */ private URL _yadisUrl; /** * Constructs a URL object from a string; * needed by the YadisURL(String) constructor * * @param urlString URL-type identifier in string format * @return URL object * @throws YadisException if the provided string is not a valid URL */ private static URL urlFromString(String urlString) throws YadisException { URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new YadisException("Invalid URL: " + urlString, OpenIDException.YADIS_INVALID_URL, e); } return url; } /** * Contructs a YadisURL from a string; * assumes the string to be a URL-type identifier * * @param urlString URL-type identifier in string format * @throws YadisException if the provided string cannot be a YadisUrl */ public YadisUrl(String urlString) throws YadisException { this(urlFromString(urlString)); if (! isValid(this._yadisUrl)) throw new YadisException( "The scheme name of a Yadis URL must be 'http' or 'https'", OpenIDException.YADIS_INVALID_SCHEME); } /** * Constructs a YadisURL from a URL object; * insures the schema is HTTP or HTTPS * * @param urlId URL identifier * @throws YadisException tf the URL identifier is not a valid YadisURL */ public YadisUrl(URL urlId) throws YadisException { if (isValid(urlId)) _yadisUrl = urlId; else throw new YadisException( "The scheme name of a Yadis URL must be 'http' or 'https'", OpenIDException.YADIS_INVALID_SCHEME); } /** * Validates a URL against the requirements for a YadisUrl. *

* The URL must be absolute (the schema must be specified), * and the schema must be HTTP or HTTPS. * * @param url the URL to be validated * @return true if the URL is a valid YadisUrl, * or false otherwise */ private boolean isValid(URL url) { return url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https"); } /** * Constructs a YadisURL from an XRI identifier. * * @param xriId The XRI identifier */ public YadisUrl(XriIdentifier xriId) throws YadisException { this(urlFromString(xriId.toURINormalForm())); } /** * Gets the URL to be used in Yadis transactions. */ public URL getUrl() { return _yadisUrl; } /** * Gets a string representation of the YadisURL. */ public String toString() { return _yadisUrl.toString(); } } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/YadisResult.java0000644001501200150120000002026011200624345025576 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.UrlIdentifier; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.xrds.XrdsServiceEndpoint; import org.openid4java.OpenIDException; import java.net.URL; import java.net.MalformedURLException; import java.util.*; /** * The results of Yadis discovery performed on a YadisURL, * represented through a stripped-down XRDS model, * containing only the those discovery information pieces * that are relevant for OpenID. *

* The payload is represented by the XRDS document. Along with it other * meta-information is contained, which can be useful while consuming * the results of Yadis discoveries. * * @author Marius Scurtescu, Johnny Bufu */ public class YadisResult { private static Log _log = LogFactory.getLog(YadisResult.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * XRDS endpoints obtained by performing Yadis discovery on the YadisURL. */ private List _endpoints; /** * The content-type of the XRDS response. */ private String _contentType; /** * The YadisURL on which discovery was performed. */ private YadisUrl _yadisUrl; /** * The result of following redirects from the request_uri */ private String _normalizedUrl; /** * The URL from where the XRDS document was retrieved. */ private URL _xrdsLocation; /** * The throwable or exception that caused the failure, if available. */ private Throwable _failureCause; /** * Sets the YadisURL on which discovery will be performed. */ public void setYadisUrl(YadisUrl url) { _yadisUrl = url; } /** * Gets the YadisUrl on which discovery is to be performed. */ public YadisUrl getYadisUrl() { return _yadisUrl; } /** * Sets the Yadis Resource Descriptor (XRDS) location * found during discovery. *

* The XRDS location can be the same as the YadisUrl, or different if * redirects are followed during discovery, or if delegation is used. * * @param xrdsLocation The Resource Descriptor URL * from where the XRDS is downloaded * @param onFailError The error code which will be set in the result * if the XRDS location is not valid */ public void setXrdsLocation(String xrdsLocation, int onFailError) throws YadisException { URL xrdsUrl = null; boolean validXrdsUrl = true; try { xrdsUrl = new URL(xrdsLocation); } catch (MalformedURLException e) { validXrdsUrl = false; } // perform the required checks on the discovered URL if (xrdsUrl == null || ! validXrdsUrl || ( ! xrdsUrl.getProtocol().equals("http") && ! xrdsUrl.getProtocol().equals("https")) ) throw new YadisException("A Yadis Resource Descriptor URL" + " MUST be an absolute URL and " + "it must be HTTP or HTTPS; found: " + xrdsLocation, onFailError); if (DEBUG) _log.debug("Setting X-XRDS-Location for yadis result: " + xrdsLocation); _xrdsLocation = xrdsUrl; } /** * Gets the Yadis Resource Descriptor (XRDS) location */ public URL getXrdsLocation() { return _xrdsLocation; } /** * Sets the OpenID XRDS endpoints discovered from an identifier. */ public void setEndpoints(List endpoints) { _endpoints = endpoints; } /** * Gets the OpenID XRDS endpoints discovered from an identifier. */ public List getEndpoints() { return _endpoints; } public int getEndpointCount() { return _endpoints == null ? 0 : _endpoints.size(); } public List getDiscoveredInformation(Set targetTypes) throws DiscoveryException { List result = new ArrayList(); if (hasEndpoints()) { XrdsServiceEndpoint endpoint; Iterator endpointsIter = _endpoints.iterator(); while (endpointsIter.hasNext()) { endpoint = (XrdsServiceEndpoint) endpointsIter.next(); Iterator typesIter = endpoint.getTypes().iterator(); while (typesIter.hasNext()) { String type = (String) typesIter.next(); if (!targetTypes.contains(type)) continue; try { result.add(new DiscoveryInformation( new URL(endpoint.getUri()), DiscoveryInformation.OPENID_SIGNON_TYPES.contains(type) ? new UrlIdentifier(_normalizedUrl) : null, DiscoveryInformation.OPENID2.equals(type) ? endpoint.getLocalId() : DiscoveryInformation.OPENID1_SIGNON_TYPES.contains(type) ? endpoint.getDelegate() : null, type, endpoint.getTypes())); } catch (MalformedURLException e) { throw new YadisException("Invalid endpoint URL discovered: " + endpoint.getUri(), OpenIDException.YADIS_INVALID_URL); } } } } return result; } /** * @return true if the YadisResult has at least one XRDS endpoint, * false otherwise. */ public boolean hasEndpoints() { return _endpoints != null && ! _endpoints.isEmpty(); } /** * Gets the result of following redirects on the YadisURL */ public String getNormalizedUrl() { return _normalizedUrl; } /** * Sets the result of following redirects on the YadisURL */ public void setNormalizedUrl(String _normalizedUrl) { this._normalizedUrl = _normalizedUrl; } /** * Sets the content-type of the response from which the XRDS was extracted. * * @param type The content-type of the HTTP response * that contained the XRDS document */ public void setContentType(String type) { _contentType = type; } /** * Gets the content-type of the response from which the XRDS was extracted. * * @return The content-type of the HTTP response * that contained the XRDS document */ public String getContentType() { return _contentType; } /** * Sets the throwable or exception that caused the failure of the Yadis * discovery, if one was thrown and intercepted */ public void setFailureCause(Throwable e) { this._failureCause = e; } /** * Gets the throwable (or exception) that caused the failure of the Yadis * discovery, if one was thrown and intercepted */ public Throwable getFailureCause() { return _failureCause; } public String dump() { StringBuffer dump = new StringBuffer(); dump.append("YadisURL:").append(_yadisUrl); dump.append("\nNormalizedURL:").append(_normalizedUrl); dump.append("\nX-XRDS-Location:").append(_xrdsLocation); dump.append("\nContent-type:").append(_contentType); if (_endpoints != null) { dump.append("\nXRDS:"); XrdsServiceEndpoint endpoint; Iterator iter = _endpoints.iterator(); while(iter.hasNext()) { endpoint = (XrdsServiceEndpoint) iter.next(); dump.append("\n\tType: ").append(endpoint.getTypes().toArray()); dump.append("\n\tServicePriority: ").append(endpoint.getServicePriority()); dump.append("\n\tUriPriority: ").append(endpoint.getUriPriority()); dump.append("\n\tURI: ").append(endpoint.getUri()); } } return dump.toString(); } } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/YadisHtmlParser.java0000644001501200150120000000120311130536343026377 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; /** * Yadis parser. * * @author Sutra Zhou * @since 0.9.4 * @see #getHtmlMeta(String) */ public interface YadisHtmlParser { /** * Parses the HTML input stream and scans for the Yadis XRDS location in the * HTML HEAD Meta tags. * * @param input * input data stream * @return String the XRDS location URL, or null if not found * @throws YadisException * on parsing errors or Yadis protocal violations */ String getHtmlMeta(String input) throws YadisException; } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/CyberNekoDOMYadisHtmlParser.java0000644001501200150120000001032511155267317030557 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import javax.xml.transform.TransformerException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.html.dom.HTMLDocumentImpl; import org.openid4java.OpenIDException; import org.openid4java.util.OpenID4JavaDOMParser; import org.openid4java.discovery.yadis.YadisException; import org.openid4java.discovery.yadis.YadisHtmlParser; import org.openid4java.discovery.yadis.YadisResolver; import org.w3c.dom.NodeList; import org.w3c.dom.html.HTMLHeadElement; import org.w3c.dom.html.HTMLMetaElement; /** * A {@link org.openid4java.discovery.yadis.YadisHtmlParser} implementation using the DOMParser of CyberNeko HTML. * * @author Sutra Zhou * @since 0.9.4 * @see org.openid4java.util.OpenID4JavaDOMParser */ public class CyberNekoDOMYadisHtmlParser implements YadisHtmlParser { private static final Log _log = LogFactory.getLog(CyberNekoDOMYadisHtmlParser.class); private static final boolean DEBUG = _log.isDebugEnabled(); /* * (non-Javadoc) * * @see org.openid4java.discovery.yadis.YadisParser#getHtmlMeta(java.lang.String) */ public String getHtmlMeta(String input) throws YadisException { String xrdsLocation = null; HTMLDocumentImpl doc = this.parseDocument(input); if (DEBUG) { try { _log.debug("document:\n" + OpenID4JavaDOMParser.toXmlString(doc)); } catch (TransformerException e) { _log.debug("An exception occurs while transforming the document to string in debugging.", e); } } NodeList heads = doc.getElementsByTagName("head"); if (heads.getLength() != 1) throw new YadisException( "HTML response must have exactly one HEAD element, " + "found " + heads.getLength() + " : " + heads.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); HTMLHeadElement head = (HTMLHeadElement) doc.getHead(); NodeList metaElements = head.getElementsByTagName("META"); if (metaElements == null || metaElements.getLength() == 0) { if (DEBUG) _log.debug("No element found under . " + "See Yadis specification, section 6.2.5/1."); } else { for (int i = 0, len = metaElements.getLength(); i < len; i++) { HTMLMetaElement metaElement = (HTMLMetaElement) metaElements.item(i); String httpEquiv = metaElement.getHttpEquiv(); if (YadisResolver.YADIS_XRDS_LOCATION.equalsIgnoreCase(httpEquiv)) { if (xrdsLocation != null) throw new YadisException( "More than one " + YadisResolver.YADIS_XRDS_LOCATION + "META tags found in HEAD: " + head.toString(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); xrdsLocation = metaElement.getContent(); if (DEBUG) _log.debug("Found " + YadisResolver.YADIS_XRDS_LOCATION + " META tags."); } } } return xrdsLocation; } private HTMLDocumentImpl parseDocument(String htmlData) throws YadisException { OpenID4JavaDOMParser parser = new OpenID4JavaDOMParser(); try { parser.parse(OpenID4JavaDOMParser.createInputSource(htmlData)); } catch (Exception e) { throw new YadisException("Error parsing HTML message", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, e); } if (parser.isIgnoredHeadStartElement()) { throw new YadisException("HTML response must have exactly one HEAD element.", OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } return (HTMLDocumentImpl) parser.getDocument(); } } openid4java-0.9.6.662/src/org/openid4java/discovery/yadis/YadisResolver.java0000644001501200150120000004474311504002767026142 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import com.google.inject.Inject; import org.apache.http.HttpException; import org.apache.http.HttpStatus; import org.apache.http.Header; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.client.ClientProtocolException; import java.io.IOException; import java.util.Set; import java.util.Collections; import java.util.List; import org.openid4java.OpenIDException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.xrds.XrdsParser; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.HttpResponse; import org.openid4java.util.OpenID4JavaUtils; /** * Yadis discovery protocol implementation. *

* Yadis discovery protocol returns a Yadis Resource Descriptor (XRDS) document * associated with a Yadis Identifier (YadisID) *

* YadisIDs can be any type of identifiers that are resolvable to a URL form, * and in addition the URL form uses a HTTP or a HTTPS schema. Such an URL * is defined by the Yadis speficification as a YadisURL. This functionality * is implemented by the YadisURL helper class. *

* The discovery of the XRDS document is performed by the discover method * on a YadisUrl. *

* Internal parameters used during the discovery process : *

* * @author Marius Scurtescu, Johnny Bufu, Sutra Zhou */ public class YadisResolver { private static Log _log = LogFactory.getLog(YadisResolver.class); private static final boolean DEBUG = _log.isDebugEnabled(); // Yadis constants public static final String YADIS_XRDS_LOCATION = "X-XRDS-Location"; private static final String YADIS_CONTENT_TYPE = "application/xrds+xml"; private static final String YADIS_ACCEPT_HEADER = "text/html; q=0.3, application/xhtml+xml; q=0.5, " + YADIS_CONTENT_TYPE; private static final String YADIS_HTML_PARSER_CLASS_NAME_KEY = "discovery.yadis.html.parser"; private static final YadisHtmlParser YADIS_HTML_PARSER; private static final String XRDS_PARSER_CLASS_NAME_KEY = "discovery.xrds.parser"; private static final XrdsParser XRDS_PARSER; static { String className = OpenID4JavaUtils.getProperty(YADIS_HTML_PARSER_CLASS_NAME_KEY); if (DEBUG) _log.debug(YADIS_HTML_PARSER_CLASS_NAME_KEY + ":" + className); try { YADIS_HTML_PARSER = (YadisHtmlParser) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } className = OpenID4JavaUtils.getProperty(XRDS_PARSER_CLASS_NAME_KEY); if (DEBUG) _log.debug(XRDS_PARSER_CLASS_NAME_KEY + ":" + className); try { XRDS_PARSER = (XrdsParser) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } /** * Maximum number of redirects to be followed for the HTTP calls. * Defalut 10. */ private int _maxRedirects = 10; private final HttpFetcher _httpFetcher; /** * Gets the internal limit configured for the maximum number of redirects * to be followed for the HTTP calls. */ public int getMaxRedirects() { return _maxRedirects; } /** * Sets the maximum number of redirects to be followed for the HTTP calls. */ public void setMaxRedirects(int maxRedirects) { this._maxRedirects = maxRedirects; } @Inject public YadisResolver(HttpFetcherFactory httpFetcherFactory) { this(httpFetcherFactory.createFetcher( HttpRequestOptions.getDefaultOptionsForDiscovery())); } public YadisResolver(HttpFetcher httpFetcher) { _httpFetcher = httpFetcher; } /** * Performs Relyin Party discovery on the supplied URL. * * @param url RP's realm or return_to URL * @return List of DiscoveryInformation entries discovered * from the RP's endpoints */ public List discoverRP(String url) throws DiscoveryException { return discover(url, 0, Collections.singleton(DiscoveryInformation.OPENID2_RP)) .getDiscoveredInformation(Collections.singleton(DiscoveryInformation.OPENID2_RP)); } /** * Performs Yadis discovery on the YadisURL. *

*

*

* The maximum number of redirects that are followed is determined by the * #_maxRedirects member field. * * @param url YadisURL on which discovery will be performed * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. * @see YadisResult #discover(String, int, HttpCache) */ public List discover(String url) throws DiscoveryException { return discover(url, _maxRedirects, _httpFetcher); } /** * Performs Yadis discovery on the YadisURL. *

*

*

* The maximum number of redirects that are followed is determined by the * #_maxRedirects member field. * * @param url YadisURL on which discovery will be performed * @param httpFetcher {@link HttpFetcher} object to use for the call * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. * @see YadisResult #discover(String, int, HttpCache) */ public List discover(String url, HttpFetcher httpFetcher) throws DiscoveryException { return discover(url, _maxRedirects, httpFetcher); } /** * Performs Yadis discovery on the YadisURL. *

*

* * @param url YadisURL on which discovery will be performed * @param maxRedirects The maximum number of redirects to be followed. * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. * @see YadisResult */ public List discover(String url, int maxRedirects) throws DiscoveryException { return discover(url, maxRedirects, _httpFetcher); } /** * Performs Yadis discovery on the YadisURL. *

*

* * @param url YadisURL on which discovery will be performed * @param maxRedirects The maximum number of redirects to be followed. * @param httpFetcher {@link HttpFetcher} object to use for the call. * @return List of DiscoveryInformation entries discovered * obtained from the URL Identifier. * @see YadisResult */ public List discover(String url, int maxRedirects, HttpFetcher httpFetcher) throws DiscoveryException { return discover(url, maxRedirects, httpFetcher, DiscoveryInformation.OPENID_OP_TYPES) .getDiscoveredInformation(DiscoveryInformation.OPENID_OP_TYPES); } public YadisResult discover(String url, int maxRedirects, Set serviceTypes) throws DiscoveryException { return discover(url, maxRedirects, _httpFetcher, serviceTypes); } public YadisResult discover(String url, int maxRedirects, HttpFetcher httpFetcher, Set serviceTypes) throws DiscoveryException { YadisUrl yadisUrl = new YadisUrl(url); // try to retrieve the Yadis Descriptor URL with a HEAD call first YadisResult result = retrieveXrdsLocation(yadisUrl, false, maxRedirects, serviceTypes); // try GET if (result.getXrdsLocation() == null) result = retrieveXrdsLocation(yadisUrl, true, maxRedirects, serviceTypes); if (result.getXrdsLocation() != null) { retrieveXrdsDocument(result, maxRedirects, serviceTypes); } else if (result.hasEndpoints()) { // report the yadis url as the xrds location result.setXrdsLocation(url, OpenIDException.YADIS_INVALID_URL); } _log.info("Yadis discovered " + result.getEndpointCount() + " endpoints from: " + url); return result; } /** * Tries to retrieve the XRDS document via a GET call on XRDS location * provided in the result parameter. * * @param result The YadisResult object containing a valid XRDS location. * It will be further populated with the Yadis discovery results. * @param cache The HttpClient object to use for placing the call * @param maxRedirects */ private void retrieveXrdsDocument(YadisResult result, int maxRedirects, Set serviceTypes) throws DiscoveryException { _httpFetcher.getRequestOptions().setMaxRedirects(maxRedirects); try { HttpResponse resp = _httpFetcher.get(result.getXrdsLocation().toString()); if (resp == null || HttpStatus.SC_OK != resp.getStatusCode()) throw new YadisException("GET failed on " + result.getXrdsLocation(), OpenIDException.YADIS_GET_ERROR); // update xrds location, in case redirects were followed result.setXrdsLocation(resp.getFinalUri(), OpenIDException.YADIS_GET_INVALID_RESPONSE); Header contentType = resp.getResponseHeader("content-type"); if ( contentType != null && contentType.getValue() != null) result.setContentType(contentType.getValue()); if (resp.isBodySizeExceeded()) throw new YadisException( "More than " + _httpFetcher.getRequestOptions().getMaxBodySize() + " bytes in HTTP response body from " + result.getXrdsLocation(), OpenIDException.YADIS_XRDS_SIZE_EXCEEDED); result.setEndpoints(XRDS_PARSER.parseXrds(resp.getBody(), serviceTypes)); } catch (IOException e) { throw new YadisException("Fatal transport error: " + e.getMessage(), OpenIDException.YADIS_GET_TRANSPORT_ERROR, e); } } /** * Parses the HTML input stream and scans for the Yadis XRDS location * in the HTML HEAD Meta tags. * * @param input input data stream * @return String the XRDS location URL, or null if not found * @throws YadisException on parsing errors or Yadis protocal violations */ private String getHtmlMeta(String input) throws YadisException { String xrdsLocation; if (input == null) throw new YadisException("Cannot download HTML message", OpenIDException.YADIS_HTMLMETA_DOWNLOAD_ERROR); xrdsLocation = YADIS_HTML_PARSER.getHtmlMeta(input); if (DEBUG) { _log.debug("input:\n" + input); _log.debug("xrdsLocation: " + xrdsLocation); } return xrdsLocation; } /** * Tries to retrieve the XRDS location url by performing a cheap HEAD call * on the YadisURL. *

* The returned string should be validated before being used * as a XRDS-Location URL. * * @param cache HttpClient object to use for placing the call * @param maxRedirects * @param url The YadisURL * @param result The location of the XRDS document and the normalized * Url will be returned in the YadisResult object. *

* The location of the XRDS document will be null if: *

* @throws YadisException if: * */ private YadisResult retrieveXrdsLocation( YadisUrl url, boolean useGet, int maxRedirects, Set serviceTypes) throws DiscoveryException { int maxattempts = 1; /*** * Need to try GET twice in some cases, because some major RPs do a redirect * when Accept header is set to YADIS_ACCEPT_HEADER * So, we need to retry with Accept header YADIS_CONTENT_TYPE */ if (useGet) maxattempts = 2; YadisResult result = new YadisResult(); for (int attempt = 1; attempt <= maxattempts; attempt++) { try { result.setYadisUrl(url); if (DEBUG) _log.debug( "Performing HTTP " + (useGet ? "GET" : "HEAD") + " on: " + url + " ..."); HttpRequestOptions requestOptions = _httpFetcher.getRequestOptions(); requestOptions.setMaxRedirects(maxRedirects); if (useGet) { if (attempt == 1) requestOptions.addRequestHeader("Accept", YADIS_ACCEPT_HEADER); else requestOptions.addRequestHeader("Accept", YADIS_CONTENT_TYPE); } HttpResponse resp = useGet ? _httpFetcher.get(url.getUrl().toString(), requestOptions) : _httpFetcher.head(url.getUrl().toString(), requestOptions); Header[] locationHeaders = resp.getResponseHeaders(YADIS_XRDS_LOCATION); Header contentType = resp.getResponseHeader("content-type"); if (HttpStatus.SC_OK != resp.getStatusCode()) { // won't be able to recover from a GET error, throw if (useGet) throw new YadisException("GET failed on " + url + " : " + resp.getStatusCode(), OpenIDException.YADIS_GET_ERROR); // HEAD is optional, will fall-back to GET if (DEBUG) _log.debug("Cannot retrieve " + YADIS_XRDS_LOCATION + " using HEAD from " + url.getUrl().toString() + "; status=" + resp.getStatusCode()); } else if ((locationHeaders != null && locationHeaders.length > 1)) { // fail if there are more than one YADIS_XRDS_LOCATION headers throw new YadisException("Found " + locationHeaders.length + " " + YADIS_XRDS_LOCATION + " headers.", useGet ? OpenIDException.YADIS_GET_INVALID_RESPONSE : OpenIDException.YADIS_HEAD_INVALID_RESPONSE); } else if (locationHeaders != null && locationHeaders.length > 0) { // we have exactly one xrds location header result.setXrdsLocation(locationHeaders[0].getValue(), useGet ? OpenIDException.YADIS_GET_INVALID_RESPONSE : OpenIDException.YADIS_HEAD_INVALID_RESPONSE); result.setNormalizedUrl(resp.getFinalUri()); } else if (contentType != null && contentType.getValue() != null && contentType.getValue().split(";")[0].equalsIgnoreCase(YADIS_CONTENT_TYPE) && resp.getBody() != null) { // no location, but got xrds document result.setNormalizedUrl(resp.getFinalUri()); result.setContentType(contentType.getValue()); if (resp.isBodySizeExceeded()) throw new YadisException( "More than " + requestOptions.getMaxBodySize() + " bytes in HTTP response body from " + url, OpenIDException.YADIS_XRDS_SIZE_EXCEEDED); result.setEndpoints(XRDS_PARSER.parseXrds(resp.getBody(), serviceTypes)); } else if (resp.getBody() != null) { // fall-back to html-meta, if present String xrdsLocation = getHtmlMeta(resp.getBody()); if (xrdsLocation != null) { result.setNormalizedUrl(resp.getFinalUri()); result.setXrdsLocation(xrdsLocation, OpenIDException.YADIS_GET_INVALID_RESPONSE); } } return result; } catch (ClientProtocolException e) { if (useGet && attempt == 2) throw new YadisException("ClientProtocol error: " + e.getMessage(), OpenIDException.YADIS_HEAD_TRANSPORT_ERROR, e); else if (useGet && attempt == 1) continue; return result; } catch (IOException e) { throw new YadisException("I/O transport error: " + e.getMessage(), OpenIDException.YADIS_HEAD_TRANSPORT_ERROR, e); } } return result; } /* visible for testing */ public HttpFetcher getHttpFetcher() { return _httpFetcher; } } openid4java-0.9.6.662/src/org/openid4java/discovery/Identifier.java0000644001501200150120000000040411034531516024277 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import java.io.Serializable; /** * @author Marius Scurtescu, Johnny Bufu */ public interface Identifier extends Serializable { public String getIdentifier(); } openid4java-0.9.6.662/src/org/openid4java/discovery/XriIdentifier.java0000644001501200150120000000244411140116773024772 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; /** * @author Marius Scurtescu, Johnny Bufu */ public class XriIdentifier implements Identifier { private String identifier; private String iriNormalForm; private String uriNormalForm; public XriIdentifier(String identifier, String iriNormalForm, String uriNormalForm) throws DiscoveryException { this.identifier = identifier; this.iriNormalForm = iriNormalForm; this.uriNormalForm = uriNormalForm; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; XriIdentifier that = (XriIdentifier) o; if (iriNormalForm != null ? !iriNormalForm.equals(that.iriNormalForm) : that.iriNormalForm != null) return false; return true; } public int hashCode() { return (iriNormalForm != null ? iriNormalForm.hashCode() : 0); } public String getIdentifier() { return identifier; } public String toString() { return identifier; } public String toIRINormalForm() { return iriNormalForm; } public String toURINormalForm() { return uriNormalForm; } } openid4java-0.9.6.662/src/org/openid4java/discovery/Discovery.java0000644001501200150120000001400211537353076024176 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import com.google.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.discovery.html.HtmlResolver; import org.openid4java.discovery.xri.XriResolver; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.OpenID4JavaUtils; import java.util.List; import java.util.regex.Pattern; /** * @author Marius Scurtescu, Johnny Bufu */ public class Discovery { private static Log _log = LogFactory.getLog(Discovery.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static final Pattern URL_PATTERN = Pattern.compile("^https?://", Pattern.CASE_INSENSITIVE); private static final Pattern XRI_PATTERN = Pattern.compile("^[!=@\\$\\+\\(]", Pattern.CASE_INSENSITIVE); private HtmlResolver _htmlResolver; private YadisResolver _yadisResolver; private XriResolver _xriResolver; private static final String XRI_RESOLVER_CLASS_NAME_KEY = "discovery.xri.resolver"; public static XriResolver getXriResolver() { String className = OpenID4JavaUtils.getProperty(XRI_RESOLVER_CLASS_NAME_KEY); if (DEBUG) _log.debug(XRI_RESOLVER_CLASS_NAME_KEY + ":" + className); try { return (XriResolver) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException("Error initializing XRI resolver.", e); } } @Inject public Discovery(HtmlResolver htmlResolver, YadisResolver yadisResolver, XriResolver xriResolver) { _htmlResolver = htmlResolver; _yadisResolver = yadisResolver; _xriResolver = xriResolver; } public Discovery() { this( new HtmlResolver(new HttpFetcherFactory()), new YadisResolver(new HttpFetcherFactory()), getXriResolver()); } public void setXriResolver(XriResolver xriResolver) { _xriResolver = xriResolver; } public void setYadisResolver(YadisResolver yadisResolver) { _yadisResolver = yadisResolver; } public void setHtmlResolver(HtmlResolver htmlResolver) { _htmlResolver = htmlResolver; } public Identifier parseIdentifier(String identifier) throws DiscoveryException { return parseIdentifier(identifier, false); } public Identifier parseIdentifier(String identifier, boolean removeFragment) throws DiscoveryException { try { // strip the xri:// prefix if it exists if (identifier.toLowerCase().startsWith("xri://")) { if (DEBUG) _log.debug("Dropping xri:// prefix from identifier: " + identifier); identifier = identifier.substring(6); } if (URL_PATTERN.matcher(identifier).find()) { if (DEBUG) _log.debug("Creating URL identifier for: " + identifier); return new UrlIdentifier(identifier, removeFragment); } else if (XRI_PATTERN.matcher(identifier).find()) { if (DEBUG) _log.debug("Creating XRI identifier for: " + identifier); return _xriResolver.parseIdentifier(identifier); } else { if (DEBUG) _log.debug("Creating URL identifier (http:// prepended) for: " + identifier); return new UrlIdentifier("http://" + identifier, removeFragment); } } catch (Exception e) { throw new DiscoveryException( "Cannot parse identifier: " + identifier, e); } } public List discover(String identifier) throws DiscoveryException { return discover(parseIdentifier(identifier, true)); // remove fragment } public List discover(Identifier identifier) throws DiscoveryException { List result; if (identifier instanceof XriIdentifier) { _log.info("Starting discovery on XRI identifier: " + identifier); result = _xriResolver.discover((XriIdentifier) identifier); } else if (identifier instanceof UrlIdentifier) { _log.info("Starting discovery on URL identifier: " + identifier); UrlIdentifier urlId = (UrlIdentifier) identifier; result = _yadisResolver.discover(urlId.getIdentifier()); // fall-back to HTML discovery if (result == null || result.size() == 0) { _log.info("No OpenID service endpoints discovered through Yadis;" + " attempting HTML discovery..."); result = _htmlResolver.discoverHtml(urlId); } } else { throw new DiscoveryException( "Unknown identifier type: " + identifier.toString()); } _log.info("Discovered " + result.size() + " OpenID endpoints."); return result; } /** * Performs discovery on the Relying Party's realm and returns a list of * OpenID 2.0 DiscoveryInformation entries. *

* Static method / caller must provide a YadisResolver so that * the OP doesn't have to instantiate a Discovery object. * * @param realm RP's realm. * @param yadisResolver The YadisResolver instance to be used for discovery. * @return List of OpenID 2.0 DiscoveryInformation endpoints. */ public static List rpDiscovery(String realm, YadisResolver yadisResolver) throws DiscoveryException { // don't follow redirects when doing RP discovery return yadisResolver.discoverRP(realm); } /* visible for testing */ public YadisResolver getYadisResolver() { return _yadisResolver; } } openid4java-0.9.6.662/src/org/openid4java/discovery/DiscoveryException.java0000644001501200150120000000156511034531516026054 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class DiscoveryException extends OpenIDException { public DiscoveryException(String message) { super(message, DISCOVERY_ERROR); } public DiscoveryException(String message, int code) { super(message, code); } public DiscoveryException(Throwable cause) { super(DISCOVERY_ERROR, cause); } public DiscoveryException(int code, Throwable cause) { super(code, cause); } public DiscoveryException(String message, Throwable cause) { super(message, DISCOVERY_ERROR, cause); } public DiscoveryException(String message, int code, Throwable cause) { super(message, code, cause); } } openid4java-0.9.6.662/src/org/openid4java/discovery/xrds/0000755001501200150120000000000011627733442022346 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/discovery/xrds/XrdsParser.java0000644001501200150120000000144211140116773025277 0ustar miguelmiguelpackage org.openid4java.discovery.xrds; import org.openid4java.discovery.DiscoveryException; import java.util.List; import java.util.Set; /** * XRDS parser for OpenID. */ public interface XrdsParser { /** * Parses a XRDS document and extracts the relevant information * for the specified service endpoint types. * * @param xrdsInput the XRDS document in String format * discovered from an Identifier. * @param targetTypes Set of service endpoint types * that should be matched * @return a List of {@link XrdsServiceEndpoint}s * extracted from the XRDS document, * in the proper, sorted order */ public List parseXrds(String input, Set targetTypes) throws DiscoveryException; } openid4java-0.9.6.662/src/org/openid4java/discovery/xrds/XrdsParserImpl.java0000644001501200150120000002122111200670447026116 0ustar miguelmiguelpackage org.openid4java.discovery.xrds; import org.openid4java.discovery.Discovery; import org.openid4java.discovery.DiscoveryException; import org.openid4java.OpenIDException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.SAXException; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.xml.parsers.*; import java.util.*; import java.io.ByteArrayInputStream; import java.io.IOException; /** * @author jbufu */ public class XrdsParserImpl implements XrdsParser { private static final Log _log = LogFactory.getLog(XrdsParserImpl.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; private static final String XRDS_SCHEMA = "xrds.xsd"; private static final String XRD_SCHEMA = "xrd.xsd"; private static final String XRD_NS = "xri://$xrd*($v*2.0)"; private static final String XRD_ELEM_XRD = "XRD"; private static final String XRD_ELEM_TYPE = "Type"; private static final String XRD_ELEM_URI = "URI"; private static final String XRD_ELEM_LOCALID = "LocalID"; private static final String XRD_ELEM_CANONICALID = "CanonicalID"; private static final String XRD_ATTR_PRIORITY = "priority"; private static final String OPENID_NS = "http://openid.net/xmlns/1.0"; private static final String OPENID_ELEM_DELEGATE = "Delegate"; public List parseXrds(String input, Set targetTypes) throws DiscoveryException { if (DEBUG) _log.debug("Parsing XRDS input for service types: " + targetTypes.toString()); Document document = parseXmlInput(input); NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD); Node lastXRD; if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null) throw new DiscoveryException("No XRD elements found."); // get the canonical ID, if any (needed for XRIs) String canonicalId = null; Node canonicalIdNode; NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID); for (int i = 0; i < canonicalIDs.getLength(); i++) { canonicalIdNode = canonicalIDs.item(i); if (canonicalIdNode.getParentNode() != lastXRD) continue; if (canonicalId != null) throw new DiscoveryException("More than one Canonical ID found."); canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? canonicalIdNode.getFirstChild().getNodeValue() : null; } // extract the services that match the specified target types NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE); Map serviceTypes = new HashMap(); Set selectedServices = new HashSet(); Node typeNode, serviceNode; for (int i = 0; i < types.getLength(); i++) { typeNode = types.item(i); String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? typeNode.getFirstChild().getNodeValue() : null; if (type == null) continue; serviceNode = typeNode.getParentNode(); if (serviceNode.getParentNode() != lastXRD) continue; if (targetTypes.contains(type)) selectedServices.add(serviceNode); addServiceType(serviceTypes, serviceNode, type); } if (DEBUG) _log.debug("Found " + serviceTypes.size() + " services for the requested types."); // extract local IDs Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document); Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document); // build XrdsServiceEndpoints for all URIs in the found services List result = new ArrayList(); NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI); Node uriNode; for (int i = 0; i < uris.getLength(); i++) { uriNode = uris.item(i); if (uriNode == null || !selectedServices.contains(uriNode.getParentNode())) continue; String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? uriNode.getFirstChild().getNodeValue() : null; serviceNode = uriNode.getParentNode(); Set typeSet = (Set) serviceTypes.get(serviceNode); String localId = (String) serviceLocalIDs.get(serviceNode); String delegate = (String) serviceDelegates.get(serviceNode); XrdsServiceEndpoint endpoint = new XrdsServiceEndpoint(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, delegate, canonicalId); if (DEBUG) _log.debug("Discovered endpoint: \n" + endpoint); result.add(endpoint); } Collections.sort(result); return result; } private Map extractElementsByParent(String ns, String elem, Set parents, Document document) { Map result = new HashMap(); NodeList nodes = document.getElementsByTagNameNS(ns, elem); Node node; for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); if (node == null || !parents.contains(node.getParentNode())) continue; String localId = node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.TEXT_NODE ? node.getFirstChild().getNodeValue() : null; result.put(node.getParentNode(), localId); } return result; } private int getPriority(Node node) { if (node.hasAttributes()) { Node priority = node.getAttributes().getNamedItem(XRD_ATTR_PRIORITY); if (priority != null) return Integer.parseInt(priority.getNodeValue()); else return XrdsServiceEndpoint.LOWEST_PRIORITY; } return 0; } private Document parseXmlInput(String input) throws DiscoveryException { if (input == null) throw new DiscoveryException("Cannot read XML message", OpenIDException.XRDS_DOWNLOAD_ERROR); if (DEBUG) _log.debug("Parsing XRDS input: " + input); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); dbf.setAttribute(JAXP_SCHEMA_SOURCE, new Object[] { Discovery.class.getResourceAsStream(XRD_SCHEMA), Discovery.class.getResourceAsStream(XRDS_SCHEMA), }); DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { throw exception; } }); return builder.parse(new ByteArrayInputStream(input.getBytes())); } catch (ParserConfigurationException e) { throw new DiscoveryException("Parser configuration error", OpenIDException.XRDS_PARSING_ERROR, e); } catch (SAXException e) { throw new DiscoveryException("Error parsing XML document", OpenIDException.XRDS_PARSING_ERROR, e); } catch (IOException e) { throw new DiscoveryException("Error reading XRDS document", OpenIDException.XRDS_DOWNLOAD_ERROR, e); } } private void addServiceType(Map serviceTypes, Node serviceNode, String type) { Set types = (Set) serviceTypes.get(serviceNode); if (types == null) { types = new HashSet(); serviceTypes.put(serviceNode, types); } types.add(type); } } openid4java-0.9.6.662/src/org/openid4java/discovery/xrds/XrdsServiceEndpoint.java0000644001501200150120000000676311200670527027156 0ustar miguelmiguelpackage org.openid4java.discovery.xrds; import java.util.Set; import java.util.Arrays; /** * Encapsulates the (OpenID-related) information extracted in * service elements discovered through Yadis. * * Note: this class has a natural ordering that is inconsistent with equals. * Only the URI priority and Service priority fields are used for comparison. * * @author jbufu */ public class XrdsServiceEndpoint implements Comparable { private int servicePriority; private int uriPriority; private Set types; private String uri; private String localId; private String delegate; public static final int LOWEST_PRIORITY = -1; private String canonicalId; public XrdsServiceEndpoint(String uri, Set types, int servicePriority, int uriPriority, String localId, String delegate, String canonicalId) { this.servicePriority = servicePriority; this.uriPriority = uriPriority; this.types = types; this.uri = uri; this.localId = localId; this.delegate = delegate; this.canonicalId = canonicalId; } public int getServicePriority() { return servicePriority; } public void setServicePriority(int servicePriority) { this.servicePriority = servicePriority; } public int getUriPriority() { return uriPriority; } public void setUriPriority(int uriPriority) { this.uriPriority = uriPriority; } public Set getTypes() { return types; } public void setTypes(Set types) { this.types = types; } public boolean matchesType(String type) { return types != null && types.contains(type); } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getLocalId() { return localId; } public void setLocalId(String localId) { this.localId = localId; } public String getDelegate() { return delegate; } public void setDelegate(String delegate) { this.delegate = delegate; } public String getCanonicalId() { return canonicalId; } public void setCanonicalId(String canonicalId) { this.canonicalId = canonicalId; } public int compareTo(Object o) { XrdsServiceEndpoint other = (XrdsServiceEndpoint) o; if (servicePriority == LOWEST_PRIORITY && other.servicePriority != LOWEST_PRIORITY) return 1; if (other.servicePriority == LOWEST_PRIORITY && servicePriority != LOWEST_PRIORITY) return -1; if (servicePriority < other.servicePriority) return -1; if (servicePriority > other.servicePriority) return 1; if (uriPriority == LOWEST_PRIORITY && other.uriPriority != LOWEST_PRIORITY) return 1; if (other.uriPriority == LOWEST_PRIORITY && uriPriority != LOWEST_PRIORITY) return -1; if (uriPriority < other.uriPriority) return -1; if (uriPriority > other.uriPriority) return 1; // XRI spec says the consumer should pick at random here return 0; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Service priority: ").append(servicePriority); sb.append("\nType: ").append(types.toString()); sb.append("\nURI: ").append(uri); sb.append("\nURI Priority: ").append(uriPriority); sb.append("\nLocalID: ").append(localId); return sb.toString(); } } openid4java-0.9.6.662/src/org/openid4java/discovery/xrds.xsd0000644001501200150120000000226311140116773023061 0ustar miguelmiguel openid4java-0.9.6.662/src/org/openid4java/discovery/xrd.xsd0000644001501200150120000001722311140116773022700 0ustar miguelmiguel openid4java-0.9.6.662/src/org/openid4java/openid4java-default.properties0000644001501200150120000000127411140116774025320 0ustar miguelmiguel# HTML Parser for HtmlResolver of discovery - Must implement org.openid4java.discovery.html.HtmlPaser discovery.html.parser=org.openid4java.discovery.html.CyberNekoDOMHtmlParser # HTML Parser for YadisResolver of discovery - Must implement org.openid4java.discovery.yadis.YadisHtmlParser discovery.yadis.html.parser=org.openid4java.discovery.yadis.CyberNekoDOMYadisHtmlParser # XRDS Parser for YadisResolver of discovery - Must implement org.openid4java.discovery.yadis.YadisXrdsParser discovery.xrds.parser=org.openid4java.discovery.xrds.XrdsParserImpl discovery.xri.resolver=org.openid4java.discovery.xri.XriDotNetProxyResolver #discovery.xri.resolver=org.openid4java.discovery.xri.LocalXriResolveropenid4java-0.9.6.662/src/org/openid4java/server/0000755001501200150120000000000011627733442020665 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/server/InMemoryServerAssociationStore.java0000644001501200150120000000477011034531515027665 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import java.util.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class InMemoryServerAssociationStore implements ServerAssociationStore { private static Log _log = LogFactory.getLog(InMemoryServerAssociationStore.class); private static final boolean DEBUG = _log.isDebugEnabled(); private String _timestamp; private int _counter; private Map _handleMap; public InMemoryServerAssociationStore() { _timestamp = Long.toString(new Date().getTime()); _counter = 0; _handleMap = new HashMap(); } public synchronized Association generate(String type, int expiryIn) throws AssociationException { removeExpired(); String handle = _timestamp + "-" + _counter++; Association association = Association.generate(type, handle, expiryIn); _handleMap.put(handle, association); if (DEBUG) _log.debug("Generated association, handle: " + handle + " type: " + type + " expires in: " + expiryIn + " seconds."); return association; } public synchronized Association load(String handle) { removeExpired(); return (Association) _handleMap.get(handle); } public synchronized void remove(String handle) { if (DEBUG) _log.debug("Removing association, handle: " + handle); _handleMap.remove(handle); removeExpired(); } private synchronized void removeExpired() { Set handleToRemove = new HashSet(); Iterator handles = _handleMap.keySet().iterator(); while (handles.hasNext()) { String handle = (String) handles.next(); Association association = (Association) _handleMap.get(handle); if (association.hasExpired()) handleToRemove.add(handle); } handles = handleToRemove.iterator(); while (handles.hasNext()) { String handle = (String) handles.next(); if (DEBUG) _log.debug("Removing expired association, handle: " + handle); _handleMap.remove(handle); } } protected synchronized int size() { return _handleMap.size(); } } openid4java-0.9.6.662/src/org/openid4java/server/ServerManager.java0000644001501200150120000007704711537353076024311 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import com.google.inject.Inject; import org.openid4java.message.*; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.association.AssociationSessionType; import org.openid4java.association.AssociationException; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.association.Association; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.OpenIDException; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Manages OpenID communications with an OpenID Relying Party (Consumer). * * @author Marius Scurtescu, Johnny Bufu */ public class ServerManager { private static Log _log = LogFactory.getLog(ServerManager.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Keeps track of the associations established with consumer sites. */ private ServerAssociationStore _sharedAssociations = new InMemoryServerAssociationStore(); /** * Keeps track of private (internal) associations created for signing * authentication responses for stateless consumer sites. */ private ServerAssociationStore _privateAssociations = new InMemoryServerAssociationStore(); /** * Nonce generator implementation. */ private NonceGenerator _nonceGenerator = new IncrementalNonceGenerator(); // --- association preferences --- /** * The lowest encryption level session accepted for association sessions */ private AssociationSessionType _minAssocSessEnc = AssociationSessionType.NO_ENCRYPTION_SHA1MAC; /** * The preferred association session type; will be attempted first. */ private AssociationSessionType _prefAssocSessEnc = AssociationSessionType.DH_SHA256; /** * Expiration time (in seconds) for associations. */ private int _expireIn = 1800; // --- authentication preferences --- /** * In OpenID 1.x compatibility mode, the URL at the OpenID Provider where * the user should be directed when a immediate authentication request * fails. *

* MUST be configured in order for the OpenID provider to be able to * respond correctly with AuthImmediateFailure messages in compatibility * mode. */ private String _userSetupUrl = null; /** * List of coma-separated fields to be signed in authentication responses. */ private String _signFields; /** * Array of extension namespace URIs that the consumer manager will sign, * if present in auth responses. */ private String[] _signExtensions; /** * Used to perform verify realms against return_to URLs. */ private RealmVerifier _realmVerifier; /** * The OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. *

* This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ private String _opEndpointUrl; /** * Gets the store implementation used for keeping track of the generated * associations established with consumer sites. * * @see ServerAssociationStore */ public ServerAssociationStore getSharedAssociations() { return _sharedAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated associations established with consumer sites. * * @param sharedAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setSharedAssociations(ServerAssociationStore sharedAssociations) { _sharedAssociations = sharedAssociations; } /** * Gets the store implementation used for keeping track of the generated * private associations (used for signing responses to stateless consumer * sites). * * @see ServerAssociationStore */ public ServerAssociationStore getPrivateAssociations() { return _privateAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated private associations (used for signing responses to * stateless consumer sites). * * @param privateAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setPrivateAssociations(ServerAssociationStore privateAssociations) { _privateAssociations = privateAssociations; } /** * Gets the minimum level of encryption configured for association sessions. *

* Default: no-encryption session, SHA1 MAC association */ public AssociationSessionType getMinAssocSessEnc() { return _minAssocSessEnc; } /** * Gets the NonceGenerator used for generating nonce tokens to uniquely * identify authentication responses. * * @see NonceGenerator */ public NonceGenerator getNonceGenerator() { return _nonceGenerator; } /** * Sets the NonceGenerator implementation that will be used to generate * nonce tokens to uniquely identify authentication responses. * * @see NonceGenerator */ public void setNonceGenerator(NonceGenerator nonceGenerator) { _nonceGenerator = nonceGenerator; } /** * Configures the minimum level of encryption accepted for association * sessions. *

* Default: no-encryption session, SHA1 MAC association */ public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc) { this._minAssocSessEnc = minAssocSessEnc; } /** * Gets the preferred association / session type. */ public AssociationSessionType getPrefAssocSessEnc() { return _prefAssocSessEnc; } /** * Sets the preferred association / session type. * * @see AssociationSessionType */ public void setPrefAssocSessEnc(AssociationSessionType type) throws ServerException { if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) ) throw new ServerException("Unsupported association / session type: " + type.getSessionType() + " : " + type.getAssociationType()); if (_minAssocSessEnc.isBetter(type) ) throw new ServerException( "Minimum encryption settings cannot be better than the preferred"); this._prefAssocSessEnc = type; } /** * Gets the expiration time (in seconds) for the generated associations */ public int getExpireIn() { return _expireIn; } /** * Sets the expiration time (in seconds) for the generated associations */ public void setExpireIn(int _expireIn) { this._expireIn = _expireIn; } /** * Gets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public String getUserSetupUrl() { return _userSetupUrl; } /** * Sets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public void setUserSetupUrl(String userSetupUrl) { this._userSetupUrl = userSetupUrl; } /** * Sets the list of parameters that the OpenID Provider will sign when * generating authentication responses. *

* The fields in the list must be coma-separated and must not include the * 'openid.' prefix. Fields that are required to be signed are automatically * added by the underlying logic, so that a valid message is generated, * regardles if they are included in the user-supplied list or not. */ public void setSignFields(String signFields) { this._signFields = signFields; } /** * Gets the list of parameters that the OpenID Provider will sign when * generating authentication responses. *

* Coma-separated list. */ public String getSignFields() { return _signFields; } public void setSignExtensions(String[] extensins) { _signExtensions = extensins; } public String[] getSignExtensions() { return _signExtensions; } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } /** * Gets the flag that instructs the realm verifier to enforce validation * of the return URL agains the endpoints discovered from the RP's realm. */ public boolean getEnforceRpId() { return _realmVerifier.getEnforceRpId(); } /** * Sets the flag that instructs the realm verifier to enforce validation * of the return URL agains the endpoints discovered from the RP's realm. */ public void setEnforceRpId(boolean enforceRpId) { _realmVerifier.setEnforceRpId(enforceRpId); } /** * Gets OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. *

* This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public String getOPEndpointUrl() { return _opEndpointUrl; } /** * Sets the OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. *

* This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public void setOPEndpointUrl(String opEndpointUrl) { this._opEndpointUrl = opEndpointUrl; } /** * Constructs a ServerManager with default settings. */ public ServerManager() { this(new RealmVerifierFactory(new YadisResolver(new HttpFetcherFactory()))); } @Inject public ServerManager(RealmVerifierFactory factory) { // initialize a default realm verifier _realmVerifier = factory.getRealmVerifierForServer(); _realmVerifier.setEnforceRpId(false); } /** * Processes a Association Request and returns a Association Response * message, according to the request parameters and the preferences * configured for the OpenID Provider * * @return AssociationResponse upon successfull association, * or AssociationError if no association * was established * */ public Message associationResponse(ParameterList requestParams) { boolean isVersion2 = requestParams.hasParameter("openid.ns"); _log.info("Processing association request..."); try { // build request message from response params (+ integrity check) AssociationRequest assocReq = AssociationRequest.createAssociationRequest(requestParams); isVersion2 = assocReq.isVersion2(); AssociationSessionType type = assocReq.getType(); // is supported / allowed ? if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) || _minAssocSessEnc.isBetter(type)) { throw new AssociationException("Unable create association for: " + type.getSessionType() + " / " + type.getAssociationType() ); } else // all ok, go ahead { Association assoc = _sharedAssociations.generate( type.getAssociationType(), _expireIn); _log.info("Returning shared association; handle: " + assoc.getHandle()); return AssociationResponse.createAssociationResponse(assocReq, assoc); } } catch (OpenIDException e) { // association failed, respond accordingly if (isVersion2) { _log.warn("Cannot establish association, " + "responding with an OpenID2 association error.", e); return AssociationError.createAssociationError( e.getMessage(), _prefAssocSessEnc); } else { _log.warn("Error processing an OpenID1 association request: " + e.getMessage() + " Responding with a dummy association.", e); try { // generate dummy association & no-encryption response // for compatibility mode Association dummyAssoc = _sharedAssociations.generate( Association.TYPE_HMAC_SHA1, 0); AssociationRequest dummyRequest = AssociationRequest.createAssociationRequest( AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC); return AssociationResponse.createAssociationResponse( dummyRequest, dummyAssoc); } catch (OpenIDException ee) { _log.error("Error creating negative OpenID1 association response.", e); return null; } } } } /** * Processes a Authentication Request received from a consumer site. *

* Uses ServerManager's global OpenID Provider endpoint URL. * * @return An signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, true); } /** * Processes a Authentication Request received from a consumer site. *

* Uses ServerManager's global OpenID Provider endpoint URL. * * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved) { return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, true); } /** * Processes a Authentication Request received from a consumer site. *

* Uses ServerManager's global OpenID Provider endpoint URL. * * @return A positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, boolean signNow) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, signNow); } /** * Processes a Authentication Request received from a consumer site. *

* Uses ServerManager's global OpenID Provider endpoint URL. * * @return A positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, boolean signNow) { return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, signNow); } /** * Processes a Authentication Request received from a consumer site. *

* * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, true); } /** * Processes a Authentication Request received from a consumer site. *

* * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest auhtReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint) { return authResponse(auhtReq, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, true); } /** * Processes a Authentication Request received from a consumer site, * after parsing the request parameters into a valid AuthRequest. *

* * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint, boolean signNow) { _log.info("Parsing authentication request..."); AuthRequest authReq; boolean isVersion2 = Message.OPENID2_NS.equals( requestParams.getParameterValue("openid.ns")); try { // build request message from response params (+ integrity check) authReq = AuthRequest.createAuthRequest( requestParams, _realmVerifier); return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, signNow); } catch (MessageException e) { if (requestParams.hasParameter("openid.return_to")) { _log.error("Invalid authentication request; " + "responding with an indirect error message.", e); return IndirectError.createIndirectError(e, requestParams.getParameterValue("openid.return_to"), ! isVersion2 ); } else { _log.error("Invalid authentication request; " + "responding with a direct error message.", e); return DirectError.createDirectError( e, ! isVersion2 ); } } } /** * Processes a Authentication Request received from a consumer site. * * @param opEndpoint The endpoint URL where the OP accepts OpenID * authentication requests. * @param authReq A valid authentication request. * @param userSelId OP-specific Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param userSelClaimed Claimed Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param authenticatedAndApproved Flag indicating that the OP has * authenticated the user and the user * has approved the authentication * transaction * @param signNow If true, the returned AuthSuccess will be signed. * If false, the signature will not be computed and * set - this will have to be performed later, * using #sign(org.openid4java.message.Message). * * @return

*/ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint, boolean signNow) { _log.info("Processing authentication request..."); boolean isVersion2 = authReq.isVersion2(); try { new URL(opEndpoint); } catch (MalformedURLException e) { String errMsg = "Invalid OP-endpoint configured; " + "cannot issue authentication responses." + opEndpoint; _log.error(errMsg, e); return DirectError.createDirectError( new ServerException(errMsg, e), isVersion2); } try { if (authReq.getReturnTo() == null) { _log.error("No return_to in the received (valid) auth request; " + "returning null auth response."); return null; } String id; String claimed; if (AuthRequest.SELECT_ID.equals(authReq.getIdentity())) { id = userSelId; claimed = userSelClaimed; } else { id = userSelId != null ? userSelId : authReq.getIdentity(); claimed = userSelClaimed != null ? userSelClaimed : authReq.getClaimed(); } if (id == null) throw new ServerException( "No identifier provided by the authntication request" + "or by the OpenID Provider"); if (DEBUG) _log.debug("Using ClaimedID: " + claimed + " OP-specific ID: " + id); if (authenticatedAndApproved) // positive response { Association assoc = null; String handle = authReq.getHandle(); String invalidateHandle = null; if (handle != null) { assoc = _sharedAssociations.load(handle); if (assoc == null) { _log.info("Invalidating handle: " + handle); invalidateHandle = handle; } else _log.info("Loaded shared association; handle: " + handle); } if (assoc == null) { assoc = _privateAssociations.generate( _prefAssocSessEnc.getAssociationType(), _expireIn); _log.info("Generated private association; handle: " + assoc.getHandle()); } AuthSuccess response = AuthSuccess.createAuthSuccess( opEndpoint, claimed, id, !isVersion2, authReq.getReturnTo(), isVersion2 ? _nonceGenerator.next() : null, invalidateHandle, assoc, false); if (_signFields != null) response.setSignFields(_signFields); if (_signExtensions != null) response.setSignExtensions(_signExtensions); if (signNow) response.setSignature(assoc.sign(response.getSignedText())); _log.info("Returning positive assertion for " + response.getReturnTo()); return response; } else // negative response { if (authReq.isImmediate()) { _log.error("Responding with immediate authentication " + "failure to " + authReq.getReturnTo()); authReq.setImmediate(false); String separator = _userSetupUrl.contains("?") ? "&" : "?"; return AuthImmediateFailure.createAuthImmediateFailure( _userSetupUrl + separator + authReq.wwwFormEncoding(), authReq.getReturnTo(), ! isVersion2); } else { _log.error("Responding with authentication failure to " + authReq.getReturnTo()); return new AuthFailure(! isVersion2, authReq.getReturnTo()); } } } catch (OpenIDException e) { if (authReq.hasParameter("openid.return_to")) { _log.error("Error processing authentication request; " + "responding with an indirect error message.", e); return IndirectError.createIndirectError(e, authReq.getReturnTo(), ! isVersion2 ); } else { _log.error("Error processing authentication request; " + "responding with a direct error message.", e); return DirectError.createDirectError( e, ! isVersion2 ); } } } /** * Signs an AuthSuccess message, using the association identified by the * handle specified within the message. * * @param authSuccess The Authentication Success message to be signed. * * @throws ServerException If the Association corresponding to the handle * in the @authSuccess cannot be retrieved from * the store. * @throws AssociationException If the signature cannot be computed. * */ public void sign(AuthSuccess authSuccess) throws ServerException, AssociationException { String handle = authSuccess.getHandle(); // try shared associations first, then private Association assoc = _sharedAssociations.load(handle); if (assoc == null) assoc = _privateAssociations.load(handle); if (assoc == null) throw new ServerException( "No association found for handle: " + handle); authSuccess.setSignature(assoc.sign(authSuccess.getSignedText())); } /** * Responds to a verification request from the consumer. * * @param requestParams ParameterList containing the parameters received * in a verification request from a consumer site. * @return VerificationResponse to be sent back to the * consumer site. */ public Message verify(ParameterList requestParams) { _log.info("Processing verification request..."); boolean isVersion2 = true; try { // build request message from response params (+ ntegrity check) VerifyRequest vrfyReq = VerifyRequest.createVerifyRequest(requestParams); isVersion2 = vrfyReq.isVersion2(); String handle = vrfyReq.getHandle(); boolean verified = false; Association assoc = _privateAssociations.load(handle); if (assoc != null) // verify the signature { _log.info("Loaded private association; handle: " + handle); verified = assoc.verifySignature( vrfyReq.getSignedText(), vrfyReq.getSignature()); // remove the association so that the request // cannot be verified more than once _privateAssociations.remove(handle); } VerifyResponse vrfyResp = VerifyResponse.createVerifyResponse(! vrfyReq.isVersion2()); vrfyResp.setSignatureVerified(verified); if (verified) { String invalidateHandle = vrfyReq.getInvalidateHandle(); if (invalidateHandle != null && _sharedAssociations.load(invalidateHandle) == null) { _log.info("Confirming shared association invalidate handle: " + invalidateHandle); vrfyResp.setInvalidateHandle(invalidateHandle); } } else _log.error("Signature verification failed, handle: " + handle); _log.info("Responding with " + (verified? "positive" : "negative") + " verification response"); return vrfyResp; } catch (OpenIDException e) { _log.error("Error processing verification request; " + "responding with verification error.", e); return DirectError.createDirectError(e, ! isVersion2); } } } openid4java-0.9.6.662/src/org/openid4java/server/JdbcServerAssociationStore.java0000644001501200150120000001636211034531515026770 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import java.util.*; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * JDBC implementation for the ServerAssociationStore interface. *

* The JdbcServerAssociation store requires a javax.sql.DataSource to be * configured and passed in to it with the setDataSource setter method. * The table name also needs to be specified, either through the constructor, * or through the setTableName setter. *

* The specified table must have the following structure: *

* * @author Marius Scurtescu, Johnny Bufu */ public class JdbcServerAssociationStore extends JdbcDaoSupport implements ServerAssociationStore { private static Log _log = LogFactory.getLog(JdbcServerAssociationStore.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static Random _random = new Random(System.currentTimeMillis()); private static final int CLEANUP_INTERVAL = 60 * 1000; // 1 min in millis private static long _lastCleanup = 0; private String _tableName; public JdbcServerAssociationStore() { } public JdbcServerAssociationStore(String tableName) { _tableName = tableName; } public String getTableName() { return _tableName; } public void setTableName(String tableName) { this._tableName = tableName; } public Association generate(String type, int expiryIn) throws AssociationException { cleanupExpired(); String sql = "INSERT INTO " + _tableName + " (handle, type, mackey, expdate) VALUES (?,?,?,?)"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); int attemptsLeft = 5; while (attemptsLeft > 0) { try { String handle = Long.toHexString(_random.nextLong()); Association association = Association.generate(type, handle, expiryIn); int cnt = jdbcTemplate.update(sql, new Object[] { association.getHandle(), association.getType(), new String(Base64.encodeBase64( association.getMacKey().getEncoded())), association.getExpiry() }); if (cnt == 1) { if (DEBUG) _log.debug("Generated association, handle: " + handle + " type: " + type + " expires in: " + expiryIn + " seconds."); return association; } } catch (DataAccessException e) { _log.error("Error generating association; attempts left: " + (attemptsLeft-1), e); } attemptsLeft--; } throw new AssociationException( "JDBCServerAssociationStore: Error generating association."); } public Association load(String handle) { try { String sql = "SELECT type,mackey,expdate FROM " + _tableName + " WHERE handle=?"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); Map res = jdbcTemplate.queryForMap(sql, new Object[] {handle}); String type = (String) res.get("type"); String macKey = (String) res.get("mackey"); Date expDate = (Date) res.get("expdate"); if (type == null || macKey == null || expDate == null) throw new AssociationException("Invalid association data " + "retrived from database; cannot create Association " + "object for handle: " + handle); Association assoc; if (Association.TYPE_HMAC_SHA1.equals(type)) assoc = Association.createHmacSha1(handle, Base64.decodeBase64(macKey.getBytes() ), expDate); else if (Association.TYPE_HMAC_SHA256.equals(type)) assoc = Association.createHmacSha256(handle, Base64.decodeBase64(macKey.getBytes() ), expDate); else throw new AssociationException("Invalid association type " + "retrieved from database: " + type); if (DEBUG) _log.debug("Retrieved association for handle: " + handle + " from table: " + _tableName); return assoc; } catch (AssociationException ase ) { _log.error("Error retrieving association from table: " + _tableName, ase); return null; } catch (IncorrectResultSizeDataAccessException rse) { _log.warn("Association not found for handle: " + handle + " in the table: " + _tableName); return null; } catch (DataAccessException dae) { _log.error("Error retrieving association for handle: " + handle + "from table: " + _tableName, dae); return null; } } public void remove(String handle) { try { String sql = "DELETE FROM " + _tableName + " WHERE handle=?"; JdbcTemplate jdbcTemplate = getJdbcTemplate(); int cnt = jdbcTemplate.update(sql, new Object[] { handle } ); if (cnt == 1 && DEBUG) _log.debug("Removed association, handle: " + handle + " from table: " + _tableName); if (cnt != 1) _log.warn("Trying to remove handle: " + handle + " from table: " + _tableName + "; affected entries: " + cnt); } catch (Exception e) { _log.error("Error removing association from table: " + _tableName, e); } } private void cleanupExpired() { if (System.currentTimeMillis() - _lastCleanup < CLEANUP_INTERVAL) return; try { String sql = "DELETE FROM " + _tableName + " WHERE expdate Offers support for implementing an OpenID Provider server.

The general usage pattern for a OpenID Provider is outlined below:

    // instantiate a ServerManager object
    public static ServerManager manager = new ServerManager();

    // configure the OpenID Provider's endpoint URL
    static
    {
        manager.setOPEndpointUrl("Http://my.openidprovider.com/server");
    }

    // extract the parameters from the request
    ParameterList request = new ParameterList(httpReq.getParameterMap());

    String mode = request.hasParameter("openid.mode") ?
            request.getParameterValue("openid.mode") : null;

    Message response;
    String responseText;

    if ("associate".equals(mode))
    {
        // --- process an association request ---
        response = manager.associationResponse(request);
        responseText = response.keyValueFormEncoding();
    }
    else if ("checkid_setup".equals(mode)
            || "checkid_immediate".equals(mode))
    {
        // interact with the user and obtain data needed to continue
        List userData = userInteraction(request);

        String userSelectedId = (String) userData.get(0);
        String userSelectedClaimedId = (String) userData.get(1);
        Boolean authenticatedAndApproved = (Boolean) userData.get(2);

        // --- process an authentication request ---
        response = manager.authResponse(request,
                userSelectedId,
                userSelectedClaimedId,
                authenticatedAndApproved.booleanValue());

        // caller will need to decide which of the following to use:
        // - GET HTTP-redirect to the return_to URL
        // - HTML FORM Redirection
        responseText = response.wwwFormEncoding();
    }
    else if ("check_authentication".equals(mode))
    {
        // --- processing a verification request ---
        response = manager.verify(request);
        responseText = response.keyValueFormEncoding();
    }
    else
    {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
    }

    // return the result to the user
    return responseText;

openid4java-0.9.6.662/src/org/openid4java/server/RealmVerifierFactory.java0000644001501200150120000000231411352263621025604 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.server; import com.google.inject.Inject; import org.openid4java.discovery.yadis.YadisResolver; /** * Factory object that, given a Yadis resolver, makes {@link RealmVerifier}s. */ public class RealmVerifierFactory { private final YadisResolver _yadisResolver; @Inject public RealmVerifierFactory(YadisResolver yadisResolver) { _yadisResolver = yadisResolver; } public RealmVerifier getRealmVerifierForConsumer() { return new RealmVerifier(false, _yadisResolver); } public RealmVerifier getRealmVerifierForServer() { return new RealmVerifier(true, _yadisResolver); } } openid4java-0.9.6.662/src/org/openid4java/server/NonceGenerator.java0000644001501200150120000000031111034531515024421 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; /** * @author Marius Scurtescu, Johnny Bufu */ public interface NonceGenerator { public String next(); } openid4java-0.9.6.662/src/org/openid4java/server/SampleServer.java0000644001501200150120000001737211034531515024137 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import org.openid4java.message.AuthRequest; import org.openid4java.message.AuthSuccess; import org.openid4java.message.MessageExtension; import org.openid4java.message.ParameterList; import org.openid4java.message.Message; import org.openid4java.message.DirectError; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchRequest; import org.openid4java.message.ax.FetchResponse; import org.openid4java.message.sreg.SRegMessage; import org.openid4java.message.sreg.SRegRequest; import org.openid4java.message.sreg.SRegResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletOutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.IOException; /** * Sample Server (OpenID Provider) implementation. */ public class SampleServer { // instantiate a ServerManager object public ServerManager manager = new ServerManager(); public SampleServer() { this("http://my.openidprovider.com/server"); } public SampleServer(String endPointUrl) { manager.setOPEndpointUrl(endPointUrl); // for a working demo, not enforcing RP realm discovery // since this new feature is not deployed manager.getRealmVerifier().setEnforceRpId(false); } public String processRequest(HttpServletRequest httpReq, HttpServletResponse httpResp) throws Exception { // extract the parameters from the request ParameterList request = new ParameterList(httpReq.getParameterMap()); String mode = request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null; Message response; String responseText; if ("associate".equals(mode)) { // --- process an association request --- response = manager.associationResponse(request); responseText = response.keyValueFormEncoding(); } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) { // interact with the user and obtain data needed to continue List userData = userInteraction(request); String userSelectedClaimedId = (String) userData.get(0); Boolean authenticatedAndApproved = (Boolean) userData.get(1); String email = (String) userData.get(2); // --- process an authentication request --- AuthRequest authReq = AuthRequest.createAuthRequest(request, manager.getRealmVerifier()); String opLocalId = null; // if the user chose a different claimed_id than the one in request if (userSelectedClaimedId != null && userSelectedClaimedId.equals(authReq.getClaimed())) { //opLocalId = lookupLocalId(userSelectedClaimedId); } response = manager.authResponse(request, opLocalId, userSelectedClaimedId, authenticatedAndApproved.booleanValue(), false); // Sign after we added extensions. if (response instanceof DirectError) return directResponse(httpResp, response.keyValueFormEncoding()); else { if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) { MessageExtension ext = authReq.getExtension(AxMessage.OPENID_NS_AX); if (ext instanceof FetchRequest) { FetchRequest fetchReq = (FetchRequest) ext; Map required = fetchReq.getAttributes(true); //Map optional = fetchReq.getAttributes(false); if (required.containsKey("email")) { Map userDataExt = new HashMap(); //userDataExt.put("email", userData.get(3)); FetchResponse fetchResp = FetchResponse.createFetchResponse(fetchReq, userDataExt); // (alternatively) manually add attribute values fetchResp.addAttribute("email", "http://schema.openid.net/contact/email", email); response.addExtension(fetchResp); } } else //if (ext instanceof StoreRequest) { throw new UnsupportedOperationException("TODO"); } } if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG)) { MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG); if (ext instanceof SRegRequest) { SRegRequest sregReq = (SRegRequest) ext; List required = sregReq.getAttributes(true); //List optional = sregReq.getAttributes(false); if (required.contains("email")) { // data released by the user Map userDataSReg = new HashMap(); //userData.put("email", "user@example.com"); SRegResponse sregResp = SRegResponse.createSRegResponse(sregReq, userDataSReg); // (alternatively) manually add attribute values sregResp.addAttribute("email", email); response.addExtension(sregResp); } } else { throw new UnsupportedOperationException("TODO"); } } // Sign the auth success message. // This is required as AuthSuccess.buildSignedList has a `todo' tag now. manager.sign((AuthSuccess) response); // caller will need to decide which of the following to use: // option1: GET HTTP-redirect to the return_to URL return response.getDestinationUrl(true); // option2: HTML FORM Redirection //RequestDispatcher dispatcher = // getServletContext().getRequestDispatcher("formredirection.jsp"); //httpReq.setAttribute("prameterMap", response.getParameterMap()); //httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false)); //dispatcher.forward(request, response); //return null; } } else if ("check_authentication".equals(mode)) { // --- processing a verification request --- response = manager.verify(request); responseText = response.keyValueFormEncoding(); } else { // --- error response --- response = DirectError.createDirectError("Unknown request"); responseText = response.keyValueFormEncoding(); } // return the result to the user return responseText; } protected List userInteraction(ParameterList request) throws ServerException { throw new ServerException("User-interaction not implemented."); } private String directResponse(HttpServletResponse httpResp, String response) throws IOException { ServletOutputStream os = httpResp.getOutputStream(); os.write(response.getBytes()); os.close(); return null; } } openid4java-0.9.6.662/src/org/openid4java/server/ServerException.java0000644001501200150120000000150611034531515024644 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class ServerException extends OpenIDException { public ServerException(String message) { super(message, SERVER_ERROR); } public ServerException(String message, int code) { super(message, code); } public ServerException(String message, Throwable cause) { super(message, SERVER_ERROR, cause); } public ServerException(String message, int code, Throwable cause) { super(message, code, cause); } public ServerException(Throwable cause) { super(cause); } public ServerException(int code, Throwable cause) { super(code, cause); } } openid4java-0.9.6.662/src/org/openid4java/server/IncrementalNonceGenerator.java0000644001501200150120000000233111034531515026607 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import org.openid4java.util.InternetDateFormat; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class IncrementalNonceGenerator implements NonceGenerator { private static Log _log = LogFactory.getLog(IncrementalNonceGenerator.class); private static final boolean DEBUG = _log.isDebugEnabled(); private static InternetDateFormat _dateFormat = new InternetDateFormat(); private String _timestamp = ""; private int _counter = 0; public synchronized String next() { String currentTimestamp = getCurrentTimpestamp(); if (_timestamp.equals(currentTimestamp)) { _counter++; } else { _timestamp = currentTimestamp; _counter = 0; } String nonce = _timestamp + Integer.toString(_counter); if (DEBUG) _log.debug("Generated nonce: " + nonce); return nonce; } private String getCurrentTimpestamp() { Date now = new Date(); return _dateFormat.format(now); } } openid4java-0.9.6.662/src/org/openid4java/infocard/0000755001501200150120000000000011627733442021144 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/infocard/InfocardException.java0000644001501200150120000000117511034531514025403 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard; import org.openid4java.OpenIDException; /** * @author Johnny Bufu */ public class InfocardException extends OpenIDException { public InfocardException(String message) { super(message, INFOCARD_ERROR); } public InfocardException(String message, int code) { super(message, code); } public InfocardException(String message, Throwable cause) { super(message, INFOCARD_ERROR, cause); } public InfocardException(Throwable cause) { super(INFOCARD_ERROR, cause); } } openid4java-0.9.6.662/src/org/openid4java/infocard/OpenIDTokenType.java0000644001501200150120000000216511034531514024760 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard; /** * Enumeration class with the defined OpenID token types. */ public class OpenIDTokenType { /** * OpenID 1.1 token type. */ public static final OpenIDTokenType OPENID11_TOKEN = new OpenIDTokenType("http://specs.openid.net/auth/1.1"); /** * OpenID 2.0 token type. */ public static final OpenIDTokenType OPENID20_TOKEN = new OpenIDTokenType("http://specs.openid.net/auth/2.0"); /** * The OpenID Identifier claim type. */ public static final String OPENID_CLAIM = "http://schema.openid.net/2007/05/claims/identifier"; /** * Token URI value. */ private final String _tokenTypeUri; /** * Constructs a token type for the given URI value. */ private OpenIDTokenType(String uriValue) { _tokenTypeUri = uriValue; } /** * Gets the URI string value for the token type. * @return String representation of the token URI type. */ public String toString() { return _tokenTypeUri; } } openid4java-0.9.6.662/src/org/openid4java/infocard/package.html0000644001501200150120000000226511034531514023416 0ustar miguelmiguel Provides support for
OpenID-InforCards.

RP support:

OP support:

See also:

openid4java-0.9.6.662/src/org/openid4java/infocard/rp/0000755001501200150120000000000011627733442021565 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/infocard/rp/InfocardInvocation.java0000644001501200150120000002202111034531513026167 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard.rp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.message.ax.FetchRequest; import org.openid4java.infocard.OpenIDTokenType; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Utility class to generate HTML or XHTLM snippets that express * Relying Parties' requirements and invoke Infocard Selectors, * requesting login with an OpenID Infocard. *

* Attribute Exchange Fetch Requests can be mapped to Infocard claim URIs. * * @author Johnny Bufu */ public class InfocardInvocation { private static Log _log = LogFactory.getLog(InfocardInvocation.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * The requested token type (OpenID 1.1 or 2.0) */ private OpenIDTokenType _tokenType; /** * List of required claim URIs. The OpenID Identifier claim * is always part of the list. */ private List _requiredClaims = new ArrayList(); /** * List of optional claim URIs. */ private List _optionalClaims = new ArrayList(); /** * The issuer's URL for the accepted claims. */ private String _issuer; /** * The issuer's WS-SecurityPolicy URL, if different than "/mex". */ private String _issuerPolicy; /** * Relying Party's privacy URL. */ private String _privacyUrl; /** * Relying Party's privacy document version. When selectors notice * a change in this value, users are prompted with the privacy policy * document retrieved from the privacyUrl. */ private int _privacyVersion; // todo: enforce data types? /** * Creates a new InfocardInvocation object, describing Relying Party's * requirements. * * @param tokenType The required token type. */ public InfocardInvocation(OpenIDTokenType tokenType) { _requiredClaims.add(OpenIDTokenType.OPENID_CLAIM); _tokenType = tokenType; if (DEBUG) _log.debug("Created " + _tokenType + " token type InfocardInvocation"); } /** * Creates an InfocardInvocation object from an Attribute Exchange * Fetch Request. *

* Attriute type URIs are mapped to Infocard claim URIs. * Attribute value count and update_url features are cannot be * expressed in InfocardInvocation data structures. * * @param fetch The Fetch Request. */ public InfocardInvocation(FetchRequest fetch) { _requiredClaims.add(OpenIDTokenType.OPENID_CLAIM); _tokenType = OpenIDTokenType.OPENID20_TOKEN; _requiredClaims.addAll(fetch.getAttributes(true).values()); _optionalClaims.addAll(fetch.getAttributes(false).values()); if (DEBUG) _log.debug("Created " + _tokenType + " token type InfocardInvocation from a FetchRequest."); } /** * Gets the token type. */ public OpenIDTokenType getTokenType() { return _tokenType; } /** * Sets the token type. * @param tokenType */ public void setTokenType(OpenIDTokenType tokenType) { this._tokenType = tokenType; } /** * Gets required or optional claim URIs. *

* The OpenID Identifier claim is always part of the required claims list. * * @param required If true, the required claims are returned; optional * claims are returned otherwise. * @return The list of configured required/optional claims. */ public List getClaims(boolean required) { return required ? _requiredClaims : _optionalClaims; } /** * Adds a claim URI to the required or optional claim list. * * @param claim The claim URI to be added. * @param required If true, the clai is added to the required * claims list, otherwise it is added to the * optional claims list. */ public void addClaim(String claim, boolean required) { if (required && ! _requiredClaims.contains(claim)) _requiredClaims.add(claim); else if (! _optionalClaims.contains(claim)) _optionalClaims.add(claim); } /** * Sets the list of required or optional claim URIs. *

* If the required claim list is set, and the OpenID Identifier claim * is not part of the provided list, it is added transparently to the list. * * @param claims List of claim URIs. * @param required If true, the required claims list is set, * otherwise the optional claims list is set. */ public void setClaims(List claims, boolean required) { if (required) { _requiredClaims = claims; if (! _requiredClaims.contains(OpenIDTokenType.OPENID_CLAIM)) _requiredClaims.add(OpenIDTokenType.OPENID_CLAIM); } else _optionalClaims = claims; } /** * Gets the issuer URL. */ public String getIssuer() { return _issuer; } /** * Sets the issuer URL. * @param issuer */ public void setIssuer(String issuer) { this._issuer = issuer; } /** * Gets the issuer policy URL, if different than "/mex". */ public String getIssuerPolicy() { return _issuerPolicy; } /** * Sets the issuer policy URL, if different than "/mex". */ public void setIssuerPolicy(String issuerPolicy) { this._issuerPolicy = issuerPolicy; } /** * Gets the Relyin Party's privacy policy URL. */ public String getPrivacyUrl() { return _privacyUrl; } /** * Gets the Relying Party's privacy document's version. */ public int getPrivacyVersion() { return _privacyVersion; } /** * Sets the Relyin Party's privacy policy URL and version. *

* When selectors notice a change in this value, users are prompted * with the privacy policy document retrieved from the privacyUrl. */ public void setPrivacyData(String url, int version) { _privacyUrl = url; _privacyVersion = version; } /** * Generates the HTML element used to describe * the Relying Party's requirements and invoke the infocard selectors. */ public String getHtmlObject() { StringBuffer object = new StringBuffer(); object.append(""); object.append(getObjectParam("tokenType", _tokenType.toString())); // claims object.append(getObjectParam("requiredClaims", arrayToString(_requiredClaims))); if (_optionalClaims.size() > 0) object.append(getObjectParam("optionslClaims", arrayToString(_optionalClaims))); // issuer if (_issuer != null && _issuer.length() > 0) object.append(getObjectParam("issuer", _issuer)); if (_issuerPolicy != null && _issuerPolicy.length() > 0) object.append(getObjectParam("issuerPolicy", _issuerPolicy)); // privacy if (_privacyUrl != null && _privacyUrl.length() > 0) { object.append(getObjectParam("privacyUrl", _privacyUrl)); object.append(getObjectParam("privacyVersion", Integer.toString(_privacyVersion))); } if (DEBUG) _log.debug("Generated element: " + object); return object.toString(); } /** * Generates the XHTML snippet element used to describe * the Relying Party's requirements and invoke the infocard selectors. */ public String getXhtml() { StringBuffer xhtml = new StringBuffer(); if (DEBUG) _log.debug("Generated XHTML invocation snippet: " + xhtml); // todo: xhtml throw new UnsupportedOperationException("XHTML invocation not implemented"); } /** * Generates an HTML snippet for an parameter * from a name-value pair. */ public String getObjectParam(String paramName, String paramValue) { StringBuffer param = new StringBuffer(); param.append(" 0) { Iterator iter = list.iterator(); while (iter.hasNext()) { result.append(iter.next()); result.append(" "); } result.deleteCharAt(result.length() - 1); } return result.toString(); } } openid4java-0.9.6.662/src/org/openid4java/infocard/sts/0000755001501200150120000000000011627733442021755 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/infocard/sts/OpenIDTokenGeneratorHandlerFactory.java0000644001501200150120000000146211034531514031423 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard.sts; /** * Implements the IConfigurableComponentFactory that creates the IssueHandler implementation. * * @author Johnny Bufu */ public class OpenIDTokenGeneratorHandlerFactory implements org.eclipse.higgins.configuration.api.IConfigurableComponentFactory { /** * Provides access to the singleton instance * * @return the singleton instance */ public org.eclipse.higgins.configuration.api.IConfigurableComponent getSingletonInstance() { return null; } /** * Provides access to the new instance * * @return the new instance */ public org.eclipse.higgins.configuration.api.IConfigurableComponent getNewInstance() { return new org.openid4java.infocard.sts.OpenIDTokenGeneratorHandler(); } } openid4java-0.9.6.662/src/org/openid4java/infocard/sts/OpenIDTokenGeneratorHandler.java0000644001501200150120000004243311034531514030076 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard.sts; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.UnsupportedEncodingException; import org.eclipse.higgins.sts.api.*; import org.eclipse.higgins.sts.common.Fault; import org.eclipse.higgins.sts.utilities.XMLHelper; import org.openid4java.message.AuthSuccess; import org.openid4java.message.ax.FetchResponse; import org.openid4java.server.ServerAssociationStore; import org.openid4java.server.JdbcServerAssociationStore; import org.openid4java.server.NonceGenerator; import org.openid4java.server.IncrementalNonceGenerator; import org.openid4java.association.AssociationException; import org.openid4java.association.Association; import org.openid4java.OpenIDException; import org.openid4java.infocard.OpenIDTokenType; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.util.Base64; import javax.sql.DataSource; import javax.naming.InitialContext; import javax.naming.NamingException; /** * Handle RSTs and generate RSTRs containing OpenID Tokens. * * @author Johnny Bufu */ public class OpenIDTokenGeneratorHandler extends org.eclipse.higgins.sts.server.token.handler.TokenHandler { private final org.eclipse.higgins.sts.utilities.LogHelper log = new org.eclipse.higgins.sts.utilities.LogHelper (OpenIDTokenGeneratorHandler.class.getName()); javax.xml.namespace.QName qnameIdentityClaimType = new javax.xml.namespace.QName(null, "ClaimType"); javax.xml.namespace.QName qnameIdentityClaimURI = new javax.xml.namespace.QName(null, "Uri"); private boolean bConfigured = false; // nonce generator not actually used: // verification will remove private assoc on first use private NonceGenerator _nonceGenerator = new IncrementalNonceGenerator(); private ServerAssociationStore _privateAssociations; private String _opEndpoint; private Integer _expireIn; /** * Protected constructor, must use TokenGeneratorHandlerFactory */ protected OpenIDTokenGeneratorHandler() { this.log.trace("TokenGeneratorHandler::TokenGeneratorHandler"); } /* (non-Javadoc) * @see org.eclipse.higgins.sts.IExtension#configure(java.util.Hashtable) */ public void configure (final Map mapGlobalSettings, final String strComponentName, final Map mapComponentSettings) { this.log.trace("TokenGeneratorHandler::initialize"); String tableName = (String) mapComponentSettings.get("AssocTableName"); JdbcServerAssociationStore privateAssociations = new JdbcServerAssociationStore(tableName); boolean status = true; try { InitialContext cxt = new InitialContext(); String dataSourceJndi = (String) mapComponentSettings.get("AssocDataSource"); DataSource ds = (DataSource) cxt.lookup(dataSourceJndi); privateAssociations.setDataSource(ds); } catch (NamingException e) { log.error("Unable to load JNDI data source from context."); status = false; } _privateAssociations = privateAssociations; java.net.URI opEndpointUri = (java.net.URI) mapComponentSettings.get("OPEndpoint"); _opEndpoint = opEndpointUri != null ? opEndpointUri.toString() : null; _expireIn = (Integer) mapComponentSettings.get("AssocExpiry"); this.bConfigured = status; } /* (non-Javadoc) * @see org.eclipse.higgins.sts.IExtension#invoke */ public void invoke (final java.util.Map mapGlobalSettings, final String strComponentName, final java.util.Map mapComponentSettings, final java.util.Map mapInvocationSettings, final IConstants constants, final ISTSRequest request, final ISTSResponse response) { this.log.trace("TokenGeneratorHandler::invoke: " + strComponentName); if (!this.bConfigured) { setWstFault(constants, response, "The specified request failed", "Issue handler not configured"); return; } // --- load component configuration --- final java.net.URI uriDefaultKeyType = (java.net.URI)mapComponentSettings.get("DefaultKeyType"); this.log.trace("DefaultKeyType: " + uriDefaultKeyType != null ? uriDefaultKeyType.toString() : null); final java.lang.Boolean bIncludeBearerSubjectName = (java.lang.Boolean)mapComponentSettings.get("IncludeBearerSubjectName"); this.log.trace("IncludeBearerSubjectName: " + bIncludeBearerSubjectName != null ? bIncludeBearerSubjectName.toString() : null); final java.net.URI uriTokenIssuer = (java.net.URI)mapComponentSettings.get("TokenIssuer"); this.log.trace("TokenIssuer: " + uriTokenIssuer != null ? uriTokenIssuer.toString() : null); if (null == uriTokenIssuer) { setWstFault(constants, response, "The specified request failed", "TokenIssuer not set."); return; } final java.net.URI uriSubjectNameIdentifier = (java.net.URI)mapComponentSettings.get("SubjectNameIdentifierAttribute"); if (null != uriSubjectNameIdentifier) this.log.trace("SubjectNameIdentifier: " + uriSubjectNameIdentifier != null ? uriSubjectNameIdentifier.toString() : null); final java.net.URI uriSubjectNameIdentifierFormat = (java.net.URI)mapComponentSettings.get("SubjectNameIdentifierFormat"); if (null != uriSubjectNameIdentifierFormat) this.log.trace("SubjectNameIdentifierFormat: " + uriSubjectNameIdentifierFormat != null ? uriSubjectNameIdentifierFormat.toString() : null); final java.lang.Boolean bEncryptToken = (java.lang.Boolean)mapComponentSettings.get("EncryptToken"); this.log.trace("EncryptToken: " + bEncryptToken != null ? bEncryptToken.toString() : null); // --- extract needed data from the RST --- final java.util.List listRST = request.getRequestSecurityTokenCollection(); final IRequestSecurityToken RST = (IRequestSecurityToken)listRST.get(0); final org.eclipse.higgins.sts.api.ILifetime ltLifetime = RST.getLifetime(); final java.net.URI uriTokenType = RST.getTokenType(); if (uriTokenType == null || (! OpenIDTokenType.OPENID20_TOKEN.toString().equals(uriTokenType.toString()) && ! OpenIDTokenType.OPENID11_TOKEN.toString().equals(uriTokenType.toString()) ) ) { setWstFault(constants, response, "Invalid token type", "Cannot handle tokens of type: " + uriTokenType); return; } boolean compat = OpenIDTokenType.OPENID11_TOKEN.equals(uriTokenType.toString()); // appliesTo = OpenID return_to URL final org.eclipse.higgins.sts.api.IAppliesTo appliesToRequest = RST.getAppliesTo(); java.net.URI uriAppliesTo = null; this.log.trace("Checking for AppliesTo"); if (appliesToRequest != null) { this.log.trace("Found AppliesTo"); final org.eclipse.higgins.sts.api.IEndpointReference eprAppliesTo = appliesToRequest.getEndpointReference(); uriAppliesTo = eprAppliesTo.getAddress(); } if (uriAppliesTo == null) { setWstFault(constants, response, "The specified request failed", "AppliesTo / return_url not found; required for OpenID Tokens."); return; } final org.eclipse.higgins.sts.api.IDigitalIdentity digitalIdentity = RST.getDigitalIdentity(); if (null == digitalIdentity) { setWstFault(constants, response, "The specified request failed", "Digital Subject was not found"); return; } // --- build response --- final OMFactory omFactory = OMAbstractFactory.getOMFactory(); final OMNamespace omIdentityNamespace = omFactory.createOMNamespace( constants.getIdentityNamespace().toString(),"ic"); final OMNamespace omWSTrustNamespace = omFactory.createOMNamespace( constants.getWSTrustNamespace().toString(),"wst"); final OMElement omRequestedDisplayToken = omFactory.createOMElement( "RequestedDisplayToken", omIdentityNamespace); final OMElement omDisplayToken = omFactory.createOMElement( "DisplayToken", omIdentityNamespace, omRequestedDisplayToken); OMElement omRequestedSecurityToken = omFactory.createOMElement( "RequestedSecurityToken", omWSTrustNamespace); final org.apache.axiom.om.OMElement omRequestedAttachedReference = omFactory.createOMElement("RequestedAttachedReference", omWSTrustNamespace); final org.apache.axiom.om.OMElement omRequestedUnattachedReference = omFactory.createOMElement("RequestedUnattachedReference", omWSTrustNamespace); final org.apache.axiom.om.OMNamespace omWSSNamespace = omFactory.createOMNamespace(constants.getWSSecurityNamespace().toString(), "wsse"); final org.apache.axiom.om.OMElement omSecurityTokenReference1 = omFactory.createOMElement("SecurityTokenReference", omWSSNamespace, omRequestedAttachedReference); final org.apache.axiom.om.OMElement omSecurityTokenReference2 = omFactory.createOMElement("SecurityTokenReference", omWSSNamespace, omRequestedUnattachedReference); final org.apache.axiom.om.OMElement omKeyIdentifier1 = omFactory.createOMElement("KeyIdentifier", omWSSNamespace, omSecurityTokenReference1); final org.apache.axiom.om.OMElement omKeyIdentifier2 = omFactory.createOMElement("KeyIdentifier", omWSSNamespace, omSecurityTokenReference2); String keyIdentifierValueType = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1"; omKeyIdentifier1.addAttribute("ValueType", keyIdentifierValueType, null); omKeyIdentifier2.addAttribute("ValueType", keyIdentifierValueType, null); // --- process the claims / attribute request --- String claimedID = null; Map attrs = new HashMap(); final java.util.List listClaims = digitalIdentity.getClaims(); final java.util.Map mapAttributeClaim = (java.util.Map)mapGlobalSettings.get("AttributeClaimMap"); String claimTypeUri; String value; String displayTag; Iterator claimsIter = listClaims.iterator(); while (claimsIter.hasNext()) { final IClaim claim = (IClaim) claimsIter.next(); value = claim.getValues().hasNext() ? (String) claim.getValues().next() : null; if (value == null) continue; claimTypeUri = claim.getType().getName().toString(); displayTag = (String) ((Map)mapAttributeClaim.get(claimTypeUri)).get("DisplayName"); if (OpenIDTokenType.OPENID_CLAIM.equals(claimTypeUri)) { claimedID = value; addDisplayClaim(claimTypeUri, claimedID, displayTag, omDisplayToken, omIdentityNamespace, omFactory); if (compat) break; } else if (! compat) { attrs.put(claimTypeUri, value); addDisplayClaim(claimTypeUri, value, displayTag, omDisplayToken, omIdentityNamespace, omFactory); } } if (claimedID == null) { setWstFault(constants, response, "Cannot process OpenID-token RST", "No claimed identifier found."); return; } Association assoc; try { assoc = _privateAssociations.generate( org.openid4java.association.Association.TYPE_HMAC_SHA1, _expireIn.intValue()); } catch (AssociationException e) { setWstFault(constants, response, "Cannot instantiate private association store", e.getMessage()); return; } if (! compat && _opEndpoint == null) { setWstFault(constants, response, "Cannot process OpenID-token RST", "OP-Endpoint not configured; required for OpenID 2 messages."); return; } // nonces not used: OP invalidates private assoc handle on first use String nonce = _nonceGenerator.next(); AuthSuccess openidResp; try { openidResp = AuthSuccess.createAuthSuccess( _opEndpoint, claimedID, claimedID, compat, uriAppliesTo.toString(), nonce, null, assoc, false); if (! compat) { FetchResponse fetchResp = FetchResponse.createFetchResponse(); fetchResp.addAttributes(attrs); openidResp.addExtension(fetchResp); } // sign the message openidResp.setSignature(assoc.sign(openidResp.getSignedText())); } catch (OpenIDException e) { setWstFault(constants, response, "Cannot generate OpenID assertion", e.getMessage()); return; } // set the attached / unattached token reference hash MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { setWstFault(constants, response, "Cannot create SHA-1 hash for Requested(Un)AttachedReference", e.getMessage()); return; } String sha1base64 = null; try { sha1base64 = Base64.encode( md.digest(openidResp.keyValueFormEncoding().getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { setWstFault(constants, response, "Unsupported encoding for the OpenID message", e.getMessage()); return; } omKeyIdentifier1.setText(sha1base64); omKeyIdentifier2.setText(sha1base64); //todo: move this to OMElement OpenIDToken.getToken()? //OpenIDToken openidToken = new OpenIDToken(openidResp); final OMNamespace omOpenIDNamespace = omFactory.createOMNamespace( org.openid4java.message.Message.OPENID2_NS, "openid"); OMElement omOpenIDToken = omFactory.createOMElement( "OpenIDToken", omOpenIDNamespace, omRequestedSecurityToken); omOpenIDToken.setText(openidResp.keyValueFormEncoding()); final java.util.List listRSTR = response.getRequestSecurityTokenResponseCollection(); if (0 == listRSTR.size()) { listRSTR.add(new org.eclipse.higgins.sts.common.RequestSecurityTokenResponse()); } final org.eclipse.higgins.sts.api.IRequestSecurityTokenResponse RSTR = (org.eclipse.higgins.sts.common.RequestSecurityTokenResponse)listRSTR.get(0); try { RSTR.setTokenType(uriTokenType); RSTR.setLifetime(ltLifetime); RSTR.setRequestedSecurityToken( XMLHelper.toElement(omRequestedSecurityToken)); RSTR.setRequestedDisplayToken( XMLHelper.toElement(omRequestedDisplayToken)); RSTR.setRequestedAttachedReference (org.eclipse.higgins.sts.utilities.XMLHelper.toElement(omRequestedAttachedReference)); RSTR.setRequestedUnattachedReference (org.eclipse.higgins.sts.utilities.XMLHelper.toElement(omRequestedUnattachedReference)); } catch (final Exception e) { org.eclipse.higgins.sts.utilities.ExceptionHelper.Log(this.log,e); setWstFault(constants, response, "The specified request failed", "Failed to set RequestSecurityToken elements."); } } private void setWstFault(IConstants constants, ISTSResponse response, String reason, String detail) { final Fault fault = new Fault( constants.getWSTrustNamespace(), "wst", constants.getRequestFailedFaultCode(), reason, detail); response.setFault(fault); } public void addDisplayClaim(String uri, String value, String displayTag, OMElement omParent, OMNamespace omNs, OMFactory omFactory) { final OMElement elemDisplayClaim = omFactory.createOMElement( "DisplayClaim", omNs, omParent); elemDisplayClaim.addAttribute("Uri", uri, null); // build and set the display tag as the part after the last "/" final OMElement elemDisplayTag = omFactory.createOMElement( "DisplayTag", omNs, elemDisplayClaim); if (displayTag == null || displayTag.length() == 0) { int lastIndex = uri.lastIndexOf("/"); displayTag = ""; if (lastIndex > -1 && uri.length() > lastIndex) displayTag = uri.substring(lastIndex + 1); } elemDisplayTag.setText(displayTag); // set the display value final OMElement elemDisplayValue = omFactory.createOMElement( "DisplayValue", omNs, elemDisplayClaim); elemDisplayValue.setText(value); } }openid4java-0.9.6.662/src/org/openid4java/infocard/OpenIDToken.java0000644001501200150120000001254511034531514024121 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard; import org.openid4java.message.Message; import org.openid4java.message.ParameterList; import org.openid4java.OpenIDException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; /** * Models the OpenID Infocard token used to transport OpenID messages. * An OpenID token encapsulates an OpenID message in key-value form into * an element. *

* Provides functionality for OPs / Servers to create OpenID tokens from * OpenID messages, and for RPs / Consumers to parse received tokens into * OpenID messages. */ public class OpenIDToken { private static Log _log = LogFactory.getLog(OpenIDToken.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Token type data structure. */ private OpenIDTokenType _tokenType; /** * The encapsulated OpenID Message. */ private Message _openidMessage; /** * Constructs an OpenID token encapsulating the provided OpenID Message. * Should be used on the OP/STS side to generate a RSTR. * * @param openidMessage The OpenID message obtained from * ServerManager.authResponse(). */ public OpenIDToken(Message openidMessage) { setOpenIDMessage(openidMessage); if (DEBUG) _log.debug("Created " + _tokenType +" token"); } /** * Parses the data posted by the selector into an OpenID token. * Should be used on the RP side. * * @param xmlToken The "xmlToken" parameter posted by the selector. * @return An OpenIDToken encapsulating the OpenID AuthResponse. */ public static OpenIDToken createFromXmlToken(String xmlToken) throws InfocardException { if (xmlToken == null) throw new InfocardException("Error processing xmlToken: null value"); if (DEBUG) _log.debug("Processing xmlToken: " + xmlToken); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse( new ByteArrayInputStream(xmlToken.getBytes("utf-8"))); String keyValueForm; try { keyValueForm = document.getElementsByTagNameNS( Message.OPENID2_NS, "OpenIDToken") .item(0).getFirstChild().getNodeValue(); } catch (Exception e) { throw new InfocardException( "Error extracting OpenID message from the xmlToken", e); } Message message = Message.createMessage( ParameterList.createFromKeyValueForm(keyValueForm)); return new OpenIDToken(message); // DOM exceptions : } catch (ParserConfigurationException e) { throw new InfocardException("Parser configuration error", e); } catch (SAXException e) { throw new InfocardException("Error parsing XML token document", e); } catch (IOException e) { throw new InfocardException("Error reading xmlToken document", e); } catch (OpenIDException e) { throw new InfocardException("Error building OpenID message from xmlToken", e); } } /** * Gets the OpenID message contained in the OpenID token. */ public Message getOpenIDMessage() { return _openidMessage; } /** * Gets the OpenID message as a ParameterList. * @return ParameterList containing the OpenID message. */ public ParameterList getOpenIDParams() { return new ParameterList(_openidMessage.getParameterMap()); } /** * Sets the OpenID Message to encapsulate into the token. */ public void setOpenIDMessage(Message openidMessage) { this._openidMessage = openidMessage; if (OpenIDTokenType.OPENID20_TOKEN.toString().equals( openidMessage.getParameterValue("openid.ns"))) _tokenType = OpenIDTokenType.OPENID20_TOKEN; else _tokenType = OpenIDTokenType.OPENID11_TOKEN; } /** * Gets the OpenID token type. * * @see org.openid4java.infocard.OpenIDTokenType */ public OpenIDTokenType getTokenType() { return _tokenType; } /** * Generates the XML string representation of the OpenID token. */ public String getToken() { StringBuffer token = new StringBuffer(); token.append(""); token.append(_openidMessage.keyValueFormEncoding()); token.append(""); return token.toString(); } } openid4java-0.9.6.662/src/org/openid4java/util/0000755001501200150120000000000011627733442020334 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/util/InternetDateFormat.java0000644001501200150120000000250611034531517024730 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Locale; import java.util.TimeZone; import java.util.Date; /** * A date formatter based on the Internet Date/Time format. This is defined in section 5.6 of RFC 3339. * *

A date formatted in this way looks like:
* 2005-05-15T17:11:51Z * * @see RFC 3339: section 5.6 * @author Marius Scurtescu, Johnny Bufu */ public class InternetDateFormat extends SimpleDateFormat { private static Log _log = LogFactory.getLog(InternetDateFormat.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone("GMT"); public InternetDateFormat() { super(PATTERN, Locale.US); setTimeZone(GMT_TIME_ZONE); } public Date parse(String source) throws ParseException { Date date = super.parse(source.toUpperCase()); if (DEBUG) _log.debug("Parsed " + source + " into Data object: " + date); return date; } } openid4java-0.9.6.662/src/org/openid4java/util/AbstractHttpFetcher.java0000644001501200150120000000504311352263621025075 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.util; import java.io.IOException; import java.util.Map; public abstract class AbstractHttpFetcher implements HttpFetcher { /** * Default set of HTTP request options to be used when placing HTTP * requests, if a custom one was not specified. */ private HttpRequestOptions _defaultOptions = new HttpRequestOptions(); /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#get(java.lang.String) */ public HttpResponse get(String url) throws IOException { return get(url, _defaultOptions); } public abstract HttpResponse get(String url, HttpRequestOptions requestOptions) throws IOException; /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#getDefaultRequestOptions() */ public HttpRequestOptions getDefaultRequestOptions() { return _defaultOptions; } /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#getRequestOptions() */ public HttpRequestOptions getRequestOptions() { return new HttpRequestOptions(_defaultOptions); } /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#head(java.lang.String) */ public HttpResponse head(String url) throws IOException { return head(url, _defaultOptions); } public abstract HttpResponse post(String url, Map parameters, HttpRequestOptions requestOptions) throws IOException; /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#head(java.lang.String) */ public HttpResponse post(String url, Map parameters) throws IOException { return post(url, parameters, _defaultOptions); } public abstract HttpResponse head(String url, HttpRequestOptions requestOptions) throws IOException; /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#setDefaultRequestOptions(org.openid4java.util.HttpRequestOptions) */ public void setDefaultRequestOptions(HttpRequestOptions defaultOptions) { this._defaultOptions = defaultOptions; } } openid4java-0.9.6.662/src/org/openid4java/util/HttpUtils.java0000644001501200150120000000401311352263621023125 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.AllClientPNames; import java.util.Iterator; import java.util.Map; public final class HttpUtils { private HttpUtils() { // empty } public static void dispose(final org.apache.http.HttpResponse response) { if (response != null) { HttpEntity e = response.getEntity(); if (e != null) { dispose(e); } } } public static void dispose(final HttpEntity entity) { if (entity != null) { try { entity.consumeContent(); } catch (Exception ignored) { // ignored } } } public static void setRequestOptions(HttpRequestBase request, HttpRequestOptions requestOptions) { request.getParams().setParameter(AllClientPNames.MAX_REDIRECTS, new Integer(requestOptions.getMaxRedirects())); request.getParams().setParameter(AllClientPNames.SO_TIMEOUT, new Integer(requestOptions.getSocketTimeout())); request.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, new Integer(requestOptions.getConnTimeout())); request.getParams().setParameter(AllClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.valueOf(requestOptions.getAllowCircularRedirects())); Map requestHeaders = requestOptions.getRequestHeaders(); if (requestHeaders != null) { Iterator iter = requestHeaders.keySet().iterator(); String headerName; while (iter.hasNext()) { headerName = (String) iter.next(); request.addHeader(headerName, (String) requestHeaders.get(headerName)); } } } } openid4java-0.9.6.662/src/org/openid4java/util/HttpRequestOptions.java0000644001501200150120000001663511504002570025037 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import java.util.Map; import java.util.HashMap; /** * Container class for the various options associated with HTTP requests. * * @see org.openid4java.util.HttpCache * @author Marius Scurtescu, Johnny Bufu */ public class HttpRequestOptions { /** * Returns an {@link HttpRequestOptions} object suitable to use for * HTTP requests to perform discovery. */ public static HttpRequestOptions getDefaultOptionsForDiscovery() { return new HttpRequestOptions(); } /** * Returns an {@link HttpRequestOptions} object suitable to use for * HTTP requests to OP endpoints for the purpose of creating associations * or verifying signatures. */ public static HttpRequestOptions getDefaultOptionsForOpCalls() { HttpRequestOptions options = new HttpRequestOptions(); options.setConnTimeout(10000); options.setSocketTimeout(10000); options.setMaxRedirects(0); options.setAllowCircularRedirects(false); return options; } /** * HTTP connect timeout, in milliseconds. Default 3000 miliseconds. */ private int _connTimeout = 3000; /** * HTTP socket (read) timeout, in milliseconds. Default 5000 miliseconds. */ private int _socketTimeout = 5000; /** * Maximum number of redirects to be followed for the HTTP calls. * Defalut 10. */ private int _maxRedirects = 10; /** * Maximum size in bytes to be retrieved for the response body. * Default 100,000 bytes. */ private int _maxBodySize = 100000; /** * Map with HTTP request headers to be used when placing the HTTP request. */ private Map _requestHeaders = new HashMap(); /** * If set to false, a new HTTP request will be placed even if a cached copy * exists. This applies to the internal HttpCache, not the HTTP protocol * cache-control mechanisms. * * @see org.openid4java.util.HttpCache */ private boolean _useCache = true; private boolean _allowCircularRedirects = true; /** * If HttpRequestOptions' content type matches a cached HttpResponse's * content type, the cache copy is returned; otherwise a new HTTP request * is placed. */ private String _contentType = null; /** * If set to a positive value, then new HTTP request will be placed if * the cache is older than that positive value (in seconds) * This applies to the internal HttpCache, not the HTTP protocol * cache-control mechanisms. * * @see org.openid4java.util.HttpCache */ private long _cacheTTLSeconds = -1; /** * Constructs a set of HTTP request options with the default values. */ public HttpRequestOptions() { } /** * Creates a new HttpRequestOptions object as a clone of the provided * parameter. * * @param other HttpRequestOptions instance to be cloned. */ public HttpRequestOptions(HttpRequestOptions other) { this._connTimeout = other._connTimeout; this._socketTimeout = other._socketTimeout; this._maxRedirects = other._maxRedirects; this._maxBodySize = other._maxBodySize; if (other._requestHeaders != null) this._requestHeaders = new HashMap(other._requestHeaders); this._useCache = other._useCache; this._contentType = other._contentType; this._allowCircularRedirects = other._allowCircularRedirects; this._cacheTTLSeconds = other._cacheTTLSeconds; } /** * Gets the HTTP connect timeout, in milliseconds. */ public int getConnTimeout() { return _connTimeout; } /** * Sets the HTTP connect timeout, in milliseconds. */ public void setConnTimeout(int connTimeout) { this._connTimeout = connTimeout; } /** * Gets the HTTP socket (read) timeout, in milliseconds. */ public int getSocketTimeout() { return _socketTimeout; } /** * Sets HTTP socket (read) timeout, in milliseconds. */ public void setSocketTimeout(int socketTimeout) { this._socketTimeout = socketTimeout; } /** * Gets the internal limit configured for the maximum number of redirects * to be followed for the HTTP calls. */ public int getMaxRedirects() { return _maxRedirects; } /** * Sets the maximum number of redirects to be followed for the HTTP calls. */ public void setMaxRedirects(int maxRedirects) { this._maxRedirects = maxRedirects; } /** * Gets configuration parameter for the maximum HTTP body size * that will be downloaded. */ public int getMaxBodySize() { return _maxBodySize; } /** * Sets the maximum HTTP body size that will be downloaded. */ public void setMaxBodySize(int maxBodySize) { this._maxBodySize = maxBodySize; } /** * Gets the HTTP request headers that will be used when placing * HTTP requests using the options in this object. */ public Map getRequestHeaders() { return _requestHeaders; } /** * Sets the HTTP request headers that will be used when placing * HTTP requests using the options in this object. */ public void setRequestHeaders(Map requestHeaders) { this._requestHeaders = requestHeaders; } /** * Adds a new HTTP request header. */ public void addRequestHeader(String headerName, String headerValue) { _requestHeaders.put(headerName, headerValue); } /** * Returns true if a cached copy can be used when placing HTTP requests * using the options in this object. This applies to the internally * implemented HTTP cache, NOT to the HTTP protocol cache-control. */ public boolean isUseCache() { return _useCache; } /** * Sets the flag for allowing cached copy to be used when placing * HTTP requests using the options in this object. This applies * to the internally implemented HTTP cache, NOT to the HTTP protocol * cache-control. */ public void setUseCache(boolean useCache) { this._useCache = useCache; } /** * Gets the required content-type for the HTTP response. If this option * matches the content-type of a cached response, the cached copy is used; * otherwise a new HTTP request is made. */ public String getContentType() { return _contentType; } /** * Sets the required content-type for the HTTP response. If this option * matches the content-type of a cached response, the cached copy is used; * otherwise a new HTTP request is made. */ public void setContentType(String contentType) { this._contentType = contentType; } public boolean getAllowCircularRedirects() { return _allowCircularRedirects; } public void setAllowCircularRedirects(boolean allow) { _allowCircularRedirects = allow; } /** * * Gets the TTL for the cached response in seconds */ public long getCacheTTLSeconds() { return _cacheTTLSeconds; } /** * * Sets the TTL for the cached response in seconds */ public void setCacheTTLSeconds(long ttl) { _cacheTTLSeconds = ttl; } } openid4java-0.9.6.662/src/org/openid4java/util/ProxyProperties.java0000644001501200150120000000530711275161465024401 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; /** * Utility bean for setting transport properties in runtime. */ public class ProxyProperties { private static final String ANONYMOUS = "anonymous"; protected int proxyPort = -1; protected String domain; protected String password; protected String proxyHostName; protected String userName; public ProxyProperties() { } public String getDomain() { if (domain == null || domain.length() == 0) { return ANONYMOUS; } else { return domain; } } public void setDomain(String domain) { this.domain = domain; } public String getPassword() { if (password == null || password.length() == 0) { return ANONYMOUS; } else { return password; } } public void setPassword(String password) { this.password = password; } public String getProxyHostName() { return proxyHostName; } public void setProxyHostName(String proxyHostName) { this.proxyHostName = proxyHostName; } public int getProxyPort() { return proxyPort; } public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } public String getUserName() { if (userName == null || userName.length() == 0) { return ANONYMOUS; } else { return userName; } } public void setUserName(String userName) { this.userName = userName; } /** * Get the proxy credentials. * * @return the proxy credentials */ public Credentials getCredentials() { Credentials credentials = null; if (this.getDomain().equals(ANONYMOUS)) { credentials = new UsernamePasswordCredentials( this.getUserName(), this.getPassword()); } else { credentials = new NTCredentials( this.getUserName(), this.getPassword(), this.getProxyHostName(), this.getDomain()); } return credentials; } /** * {@inheritDoc} */ @Override public String toString() { return this.getDomain() + "\\" + this.getUserName() + ":" + this.getPassword() + "@" + this.getProxyHostName() + ":" + this.getProxyPort(); } } openid4java-0.9.6.662/src/org/openid4java/util/HttpFetcherFactory.java0000644001501200150120000000441011537353076024747 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.util; import javax.net.ssl.SSLContext; import org.apache.http.conn.ssl.X509HostnameVerifier; import com.google.inject.Inject; import com.google.inject.Provider; public class HttpFetcherFactory { private final Provider _provider; @Inject public HttpFetcherFactory(Provider provider) { _provider = provider; } /** * Public constructor for non-Guice installations. Results in * {@link HttpCache} being used as the {@link HttpFetcher} */ public HttpFetcherFactory() { this(new HttpCacheProvider()); } public HttpFetcherFactory(SSLContext sslContext) { this(new HttpCacheProvider(sslContext)); } public HttpFetcherFactory(SSLContext sslContext, X509HostnameVerifier hostnameVerifier) { this(new HttpCacheProvider(sslContext, hostnameVerifier)); } public HttpFetcher createFetcher(HttpRequestOptions defaultOptions) { final HttpFetcher fetcher = _provider.get(); fetcher.setDefaultRequestOptions(defaultOptions); return fetcher; } private static class HttpCacheProvider implements Provider { private final SSLContext sslContext; private final X509HostnameVerifier hostnameVerifier; public HttpCacheProvider(SSLContext sslContext, X509HostnameVerifier hostnameVerifier) { this.sslContext = sslContext; this.hostnameVerifier = hostnameVerifier; } public HttpCacheProvider(SSLContext sslContext) { this(sslContext, null); } public HttpCacheProvider() { this(null, null); } public HttpFetcher get() { return new HttpCache(this.sslContext, this.hostnameVerifier); } } } openid4java-0.9.6.662/src/org/openid4java/util/HttpClientFactory.java0000644001501200150120000001225111537353076024607 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ /* * Created on Mar 5, 2007 */ package org.openid4java.util; import javax.net.ssl.SSLContext; import org.apache.http.HttpHost; import org.apache.http.client.*; import org.apache.http.client.params.AllClientPNames; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; /** * This class handles all HTTPClient connections for the * org.openid4java packages. * * @author Kevin */ public class HttpClientFactory { private HttpClientFactory() {} /** * proxy properties for HTTPClient calls */ private static ProxyProperties proxyProperties = null; private static boolean multiThreadedHttpClient = true; public static ProxyProperties getProxyProperties() { return proxyProperties; } public static void setProxyProperties(ProxyProperties proxyProperties) { HttpClientFactory.proxyProperties = proxyProperties; } public static boolean isMultiThreadedHttpClient() { return multiThreadedHttpClient; } /** * Configures the type of HttpClient's constructed by the factory. * * @param multiThreadedHttpClient if true, MultiThreadedHttpConnectionManager's are constructed; * if false - SimpleHttpConnectionManager's. * */ public static void setMultiThreadedHttpClient(boolean multiThreadedHttpClient) { HttpClientFactory.multiThreadedHttpClient = multiThreadedHttpClient; } public static HttpClient getInstance(int maxRedirects, Boolean allowCircularRedirects, int connTimeout, int socketTimeout, String cookiePolicy) { return getInstance(maxRedirects, allowCircularRedirects, connTimeout, socketTimeout, cookiePolicy, null, null); } public static HttpClient getInstance(int maxRedirects, Boolean allowCircularRedirects, int connTimeout, int socketTimeout, String cookiePolicy, SSLContext sslContext, X509HostnameVerifier hostnameVerifier) { HttpParams httpParams = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory; if (null == sslContext) { sslSocketFactory = SSLSocketFactory.getSocketFactory(); } else { sslSocketFactory = new SSLSocketFactory(sslContext); } if (null != hostnameVerifier) { sslSocketFactory.setHostnameVerifier(hostnameVerifier); } registry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager connManager; if (multiThreadedHttpClient) connManager = new ThreadSafeClientConnManager(httpParams, registry); else connManager = new SingleClientConnManager(httpParams, registry); DefaultHttpClient client = new DefaultHttpClient(connManager, httpParams); client.getParams().setParameter(AllClientPNames.MAX_REDIRECTS, new Integer(maxRedirects)); client.getParams().setParameter(AllClientPNames.ALLOW_CIRCULAR_REDIRECTS, allowCircularRedirects); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, new Integer(socketTimeout)); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, new Integer(connTimeout)); if (cookiePolicy == null) { client.setCookieStore(null); } else { client.getParams().setParameter(AllClientPNames.COOKIE_POLICY, cookiePolicy); } if (proxyProperties != null) { HttpHost proxy = new HttpHost( proxyProperties.getProxyHostName(), proxyProperties.getProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); //now set headers for auth AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME); Credentials credentials = proxyProperties.getCredentials(); client.getCredentialsProvider().setCredentials(authScope, credentials); } return client; } } openid4java-0.9.6.662/src/org/openid4java/util/HttpFetcher.java0000644001501200150120000000464311352263621023416 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.util; import com.google.inject.ImplementedBy; import java.io.IOException; import java.util.Map; /** * Interface for fetching HTTP requests. The default implementation caches * responses, but can be replaced by custom implementations. */ @ImplementedBy(HttpCache.class) public interface HttpFetcher { /** * Returns the default {@link HttpRequestOptions}. Note that this does * not return a clone, so manipulating the object returned here will * manipulate the {@link HttpRequestOptions} used by the {@link HttpFetcher}. */ public HttpRequestOptions getDefaultRequestOptions(); /** * Gets a clone of the default HttpRequestOptions. */ public HttpRequestOptions getRequestOptions(); public void setDefaultRequestOptions(HttpRequestOptions defaultOptions); /** * GETs a HTTP URL. A cached copy will be returned if one exists. * * @param url The HTTP URL to GET. * @return A HttpResponse object containing the fetched data. * * @see HttpResponse */ public HttpResponse get(String url) throws IOException; /** * GETs a HTTP URL. A cached copy will be returned if one exists and the * supplied options match it. * * @param url The HTTP URL to GET. * @return A HttpResponse object containing the fetched data. * * @see HttpRequestOptions, HttpResponse */ public HttpResponse get(String url, HttpRequestOptions requestOptions) throws IOException; public HttpResponse head(String url) throws IOException; public HttpResponse head(String url, HttpRequestOptions requestOptions) throws IOException; public HttpResponse post(String url, Map parameters) throws IOException; public HttpResponse post(String url, Map parameters, HttpRequestOptions requestOptions) throws IOException; } openid4java-0.9.6.662/src/org/openid4java/util/HttpResponse.java0000644001501200150120000000211311352263621023622 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.http.Header; /** * Container class for HTTP responses. * * @author Marius Scurtescu, Johnny Bufu */ public interface HttpResponse { /** * Gets the status code of the HttpResponse. */ public int getStatusCode(); /** * Gets the final URI from where the document was obtained, * after following redirects. */ public String getFinalUri(); /** * Gets the first header matching the provided headerName parameter, * or null if no header with that name exists. */ public Header getResponseHeader(String headerName); /** * Gets an array of Header objects for the provided headerName parameter. */ public Header[] getResponseHeaders(String headerName); /** * Gets the HttpResponse body. */ public String getBody(); /** * Returns true if the HTTP response size exceeded the maximum * allowed by the (default) HttpRequestOptions. */ public boolean isBodySizeExceeded(); } openid4java-0.9.6.662/src/org/openid4java/util/HttpCache.java0000644001501200150120000004165211537353076023053 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.AllClientPNames; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.message.BasicNameValuePair; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Date; import javax.net.ssl.SSLContext; /** * Wrapper cache around HttpClient providing caching for HTTP requests. * Intended to be used to optimize the number of HTTP requests performed * during OpenID discovery. * * @author Marius Scurtescu, Johnny Bufu */ public class HttpCache extends AbstractHttpFetcher { private static Log _log = LogFactory.getLog(HttpCache.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * HttpClient used to place the HTTP requests. */ private HttpClient _client; /** * Cache for GET requests. Map of URL -> HttpResponse. */ private Map _getCache = new HashMap(); // todo: cache management /** * Cache for HEAD requests. Map of URL -> HttpResponse. */ private Map _headCache = new HashMap(); public HttpCache() { this(null); } public HttpCache(SSLContext sslContext) { this(sslContext, null); } /** * Constructs a new HttpCache object, that will be initialized with the * default set of HttpRequestOptions. * * @see HttpRequestOptions */ public HttpCache(SSLContext sslContext, X509HostnameVerifier hostnameVerifier) { super(); _client = HttpClientFactory.getInstance( getDefaultRequestOptions().getMaxRedirects(), getDefaultRequestOptions().getAllowCircularRedirects(), getDefaultRequestOptions().getSocketTimeout(), getDefaultRequestOptions().getConnTimeout(), null, sslContext, hostnameVerifier); } /** * Removes a cached GET response. * * @param url The URL for which to remove the cached response. */ private void removeGet(String url) { if (_getCache.keySet().contains(url)) { _log.info("Removing cached GET response for " + url); _getCache.remove(url); } else _log.info("NOT removing cached GET for " + url + " NOT FOUND."); } /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#get(java.lang.String, org.openid4java.util.HttpRequestOptions) */ public HttpResponse get(String url, HttpRequestOptions requestOptions) throws IOException { DefaultHttpResponse resp = (DefaultHttpResponse) _getCache.get(url); if (resp != null) { if (match(resp, requestOptions)) { _log.info("Returning cached GET response for " + url); return resp; } else { _log.info("Removing cached GET for " + url); removeGet(url); } } HttpGet get = new HttpGet(url); org.apache.http.HttpResponse httpResponse = null; HttpEntity responseEntity = null; try { get.getParams().setParameter(AllClientPNames.HANDLE_REDIRECTS, Boolean.TRUE); HttpUtils.setRequestOptions(get, requestOptions); httpResponse = _client.execute(get); responseEntity = httpResponse.getEntity(); int statusCode = httpResponse.getStatusLine().getStatusCode(); String statusLine = httpResponse.getStatusLine().getReasonPhrase(); ResponseBody body = getResponseBody(responseEntity, requestOptions.getMaxBodySize()); resp = new DefaultHttpResponse(statusCode, statusLine, requestOptions.getMaxRedirects(), get.getURI().toString(), httpResponse.getAllHeaders(), body.getBody()); resp.setBodySizeExceeded(body.isBodyTruncated()); // save result in cache _getCache.put(url, resp); } finally { HttpUtils.dispose(responseEntity); } return resp; } private List toList(Map parameters) { List list = new ArrayList(parameters.size()); for (Entry entry : parameters.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return list; } @Override public HttpResponse post(String url, Map parameters, HttpRequestOptions requestOptions) throws IOException { // we don't actually cache posts, since they are used for // association requests and signature verification // build the post message with the parameters from the request HttpPost post = new HttpPost(url); DefaultHttpResponse resp; org.apache.http.HttpResponse httpResponse = null; try { // can't follow redirects on a POST (w/o user intervention) post.getParams().setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, false); HttpUtils.setRequestOptions(post, requestOptions); post.setEntity(new UrlEncodedFormEntity(toList(parameters), "UTF-8")); // place the http call to the OP if (DEBUG) _log.debug("Performing HTTP POST on " + url); httpResponse = _client.execute(post); int statusCode = httpResponse.getStatusLine().getStatusCode(); String statusLine = httpResponse.getStatusLine().getReasonPhrase(); ResponseBody body = getResponseBody(httpResponse.getEntity(), requestOptions.getMaxBodySize()); resp = new DefaultHttpResponse(statusCode, statusLine, requestOptions.getMaxRedirects(), post.getURI().toString(), httpResponse.getAllHeaders(), body.getBody()); resp.setBodySizeExceeded(body.isBodyTruncated()); } finally { HttpUtils.dispose(httpResponse); } return resp; } /** * Returns content of an HTTP response entitity, but no more than maxBytes. * @throws IOException */ private ResponseBody getResponseBody(HttpEntity response, int maxBodySize) throws IOException { InputStream httpBodyInput = response.getContent(); if (httpBodyInput == null) { return new ResponseBody(null, false); } // trim down maxBodySize if we know the content is smaller than // maxBodySize if ((response.getContentLength() > 0) && (response.getContentLength() < maxBodySize)) { maxBodySize = (int) response.getContentLength(); } byte data[] = new byte[maxBodySize]; int totalRead = 0; int currentRead; while (totalRead < maxBodySize) { currentRead = httpBodyInput.read( data, totalRead, maxBodySize - totalRead); if (currentRead == -1) break; totalRead += currentRead; } boolean bodySizeExceeded = (httpBodyInput.read() > 0); httpBodyInput.close(); if (DEBUG) _log.debug("Read " + totalRead + " bytes."); return new ResponseBody(new String(data, 0, totalRead), bodySizeExceeded); } private boolean match(DefaultHttpResponse resp, HttpRequestOptions requestOptions) { // use cache? if ( resp != null && ! requestOptions.isUseCache()) { _log.info("Explicit fresh GET requested; removing cached copy"); return false; } //is cache fresh? if ( resp != null && (requestOptions.getCacheTTLSeconds() >= 0)) { long cacheTTL = requestOptions.getCacheTTLSeconds() * 1000; Date now = new Date(); long currentTime = now.getTime(); long cacheExpTime = resp.getTimestamp() + cacheTTL; if (cacheExpTime < currentTime) { String cacheExpTimeStr = (new Date(cacheExpTime)).toString(); _log.info("Cache Expired at " + cacheExpTimeStr + "; removing cached copy"); return false; } } // content type rules String requiredContentType = requestOptions.getContentType(); if (resp != null && requiredContentType != null) { Header responseContentType = resp.getResponseHeader("content-type"); if ( responseContentType != null && responseContentType.getValue() != null && !responseContentType.getValue().split(";")[0] .equalsIgnoreCase(requiredContentType) ) { _log.info("Cached GET response does not match " + "the required content type, removing."); return false; } } if (resp != null && resp.getMaxRedirectsFollowed() > requestOptions.getMaxRedirects()) { _log.info("Cached GET response used " + resp.getMaxRedirectsFollowed() + " max redirects; current requirement is: " + requestOptions.getMaxRedirects()); return false; } return true; } /* (non-Javadoc) * @see org.openid4java.util.HttpFetcher#head(java.lang.String, org.openid4java.util.HttpRequestOptions) */ public HttpResponse head(String url, HttpRequestOptions requestOptions) throws IOException { DefaultHttpResponse resp = (DefaultHttpResponse) _headCache.get(url); if (resp != null) { if (match(resp, requestOptions)) { _log.info("Returning cached HEAD response for " + url); return resp; } else { _log.info("Removing cached HEAD for " + url); removeGet(url); } } HttpHead head = new HttpHead(url); org.apache.http.HttpResponse httpResponse = null; HttpEntity responseEntity = null; try { head.getParams().setParameter(AllClientPNames.HANDLE_REDIRECTS, Boolean.TRUE); HttpUtils.setRequestOptions(head, requestOptions); httpResponse = _client.execute(head); responseEntity = httpResponse.getEntity(); int statusCode = httpResponse.getStatusLine().getStatusCode(); String statusLine = httpResponse.getStatusLine().getReasonPhrase(); resp = new DefaultHttpResponse(statusCode, statusLine, requestOptions.getMaxRedirects(), head.getURI().toString(), httpResponse.getAllHeaders(), null); // save result in cache _headCache.put(url, resp); } finally { HttpUtils.dispose(responseEntity); } return resp; } private static class DefaultHttpResponse implements HttpResponse { /** * The status code of the HTTP response. */ private int _statusCode; /** * The status line of the HTTP response. */ private String _statusLine; /** * The maximum HTTP redirects limit that was configured * when this HTTP response was obtained. */ private int _maxRedirectsFollowed; /** * The final URI from where the document was obtained, * after following redirects. */ private String _finalUri; /** * Map of header names List of Header objects of the HTTP response. */ private Map _responseHeaders; /** * The HTTP response body. */ private String _body; /** * Flag to indicate if the HTTP response size exceeded the maximum * allowed by the (default) HttpRequestOptions. */ private boolean _bodySizeExceeded = false; /** * timestamp of creation * *(number of milliseconds since January 1, 1970, 00:00:00 GMT) */ private long _timestamp; /** * Constructs a new HttpResponse with the provided parameters. */ public DefaultHttpResponse(int statusCode, String statusLine, int redirectsFollowed, String finalUri, Header[] responseHeaders, String body) { _statusCode = statusCode; _statusLine = statusLine; _maxRedirectsFollowed = redirectsFollowed; _finalUri = finalUri; _responseHeaders = new HashMap(); if (responseHeaders != null) { String headerName; Header header; for (int i=0; i < responseHeaders.length; i++) { // HTTP header names are case-insensitive headerName = responseHeaders[i].getName().toLowerCase(); header = responseHeaders[i]; List headerList = (List) _responseHeaders.get(headerName); if (headerList != null) headerList.add(responseHeaders[i]); else _responseHeaders.put(headerName, new ArrayList(Arrays.asList(new Header[] {header}))); } } _body = body; Date now = new Date(); _timestamp = now.getTime(); } /** * Gets the status code of the HttpResponse. */ public int getStatusCode() { return _statusCode; } /** * Gets the status line of the HttpResponse. */ public String getStatusLine() { return _statusLine; } /** * Gets the maximum HTTP redirects limit that was configured * when this HTTP response was obtained. */ public int getMaxRedirectsFollowed() { return _maxRedirectsFollowed; } /** * Gets the final URI from where the document was obtained, * after following redirects. */ public String getFinalUri() { return _finalUri; } /** * Gets the first header matching the provided headerName parameter, * or null if no header with that name exists. */ public Header getResponseHeader(String headerName) { List headerList = (List) _responseHeaders.get(headerName.toLowerCase()); if (headerList != null && headerList.size() > 0) return (Header) headerList.get(0); else return null; } /** * Gets an array of Header objects for the provided headerName parameter. */ public Header[] getResponseHeaders(String headerName) { List headerList = (List) _responseHeaders.get(headerName.toLowerCase()); if (headerList != null) return (Header[]) headerList.toArray(new Header[headerList.size()]); else return new Header[]{}; // empty array, same as HttpClient's method } /** * Gets the HttpResponse body. */ public String getBody() { return _body; } /** * Returns true if the HTTP response size exceeded the maximum * allowed by the (default) HttpRequestOptions. * @return */ public boolean isBodySizeExceeded() { return _bodySizeExceeded; } /** * Sets the flag to indicate whether the HTTP response size exceeded * the maximum allowed by the (default) HttpRequestOptions. */ public void setBodySizeExceeded(boolean bodySizeExceeded) { this._bodySizeExceeded = bodySizeExceeded; } public long getTimestamp() { return _timestamp; } } private static class ResponseBody { private final String body; private final boolean bodyIsTruncated; public ResponseBody(String body, boolean truncated) { this.body = body; this.bodyIsTruncated = truncated; } public String getBody() { return body; } public boolean isBodyTruncated() { return bodyIsTruncated; } } } openid4java-0.9.6.662/src/org/openid4java/util/OpenID4JavaDOMParser.java0000644001501200150120000000764411155267317024732 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import java.io.ByteArrayInputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.cyberneko.html.HTMLTagBalancingListener; import org.cyberneko.html.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.html.HTMLHtmlElement; import org.xml.sax.InputSource; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; /** * A DOMParser extends from Cyberneko HTML. *

* This extended parser marks that a(or more) HTML element head is * ignored while parsing. *

* * @author Sutra Zhou * @see NekoHTML * @since 0.9.4 */ public class OpenID4JavaDOMParser extends DOMParser implements HTMLTagBalancingListener { /** * Create an InputSource form a String. * * @param s * the String * @return an InputSource * @throws NullPointerException * if s is null. */ public static InputSource createInputSource(String s) { try { return new InputSource( new ByteArrayInputStream(s.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Transform the document to string. * * @param doc the document * @return a string * @throws TransformerException If an unrecoverable error occurs * during the course of the transformation. */ public static String toXmlString(Document doc) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = factory.newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource source = new DOMSource(doc); StringWriter xmlString = new StringWriter(); StreamResult streamResult = new StreamResult(xmlString); transformer.transform(source, streamResult); return xmlString.toString(); } private boolean ignoredHeadStartElement; /** * @see NekoHTML | Parser Settings */ public OpenID4JavaDOMParser() { try { this.setFeature("http://xml.org/sax/features/namespaces", false); } catch (SAXNotRecognizedException e) { // Do nothing as this exception will not happen. } catch (SAXNotSupportedException e) { // Do nothing as this exception will not happen. } } public boolean isIgnoredHeadStartElement() { return ignoredHeadStartElement; } public void ignoredEndElement(QName element, Augmentations augs) { // Do nothing. } public void ignoredStartElement(QName element, XMLAttributes attrs, Augmentations augs) { if (element.rawname.equals("HEAD") && this.fCurrentNode instanceof HTMLHtmlElement) { this.ignoredHeadStartElement = true; } } }openid4java-0.9.6.662/src/org/openid4java/util/OpenID4JavaUtils.java0000644001501200150120000000435211140116774024221 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; /** * Load properties from classpath:org.openid4java.util.openid4java-default.properties, * then load custom properties from classpath:openid4java.properties * to replace the default if exists.. * * @author Sutra Zhou * */ public class OpenID4JavaUtils { private static Log _log = LogFactory.getLog(OpenID4JavaUtils.class); private static final Properties _appProperties; static { // Load default properties first, then use custom properties to replace // the default. _appProperties = new Properties(); _appProperties.putAll(loadProperties("openid4java-default.properties")); Properties custom = loadProperties("/openid4java.properties"); if (custom != null) { _appProperties.putAll(custom); } } private static Properties loadProperties(String name) { Properties p = null; InputStream is = OpenIDException.class.getResourceAsStream(name); if (is != null) { p = new Properties(); try { p.load(is); } catch (IOException e) { _log.error("Load properties from " + name + " failed.", e); } finally { try { is.close(); } catch (IOException e) { _log.warn("Error closing resource stream.", e); } } } else { _log.debug("Resource " + name + " not found."); } return p; } public static String getProperty(String key) { return _appProperties.getProperty(key); } public static String getProperty(String key, String defaultValue) { return _appProperties.getProperty(key, defaultValue); } private OpenID4JavaUtils() { } } openid4java-0.9.6.662/src/org/openid4java/OpenIDException.java0000644001501200150120000000617511140116774023221 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java; /** * @author Marius Scurtescu, Johnny Bufu */ public class OpenIDException extends Exception { private int _errorCode; // error codes intended to help pinpoint the subsystem / cause of a failure public static final int OPENID_ERROR = 0x0000; public static final int MESSAGE_ERROR = 0x0100; public static final int ASSOC_ERROR = 0x0200; public static final int AUTH_ERROR = 0x0300; public static final int AUTH_REALM_ERROR = 0x0301; public static final int VERIFY_ERROR = 0x0400; public static final int DISCOVERY_ERROR = 0x0500; public static final int DISCOVERY_HTML_ERROR = 0x0600; public static final int DISCOVERY_HTML_GET_ERROR = 0x0601; public static final int DISCOVERY_HTML_NODATA_ERROR = 0x0602; public static final int DISCOVERY_HTML_PARSE_ERROR = 0x0603; public static final int YADIS_ERROR = 0x0700; public static final int YADIS_INVALID_URL = 0x0702; public static final int YADIS_INVALID_SCHEME = 0x0703; public static final int YADIS_HEAD_TRANSPORT_ERROR = 0x0704; public static final int YADIS_HEAD_INVALID_RESPONSE = 0x0705; public static final int YADIS_GET_ERROR = 0x0706; public static final int YADIS_GET_TRANSPORT_ERROR = 0x0707; public static final int YADIS_GET_INVALID_RESPONSE = 0x0708; public static final int YADIS_GET_NO_XRDS = 0x0709; public static final int YADIS_HTMLMETA_DOWNLOAD_ERROR = 0x070A; public static final int YADIS_HTMLMETA_INVALID_RESPONSE = 0x070B; public static final int XRDS_DOWNLOAD_ERROR = 0x070C; public static final int XRDS_PARSING_ERROR = 0x070D; public static final int YADIS_XRDS_SIZE_EXCEEDED = 0x070E; public static final int XRI_ERROR = 0x0800; public static final int SERVER_ERROR = 0x0900; public static final int CONSUMER_ERROR = 0x0A00; public static final int INFOCARD_ERROR = 0x0B00; public static final int EXTENSION_ERROR = 0x0C00; public static final int AX_ERROR = 0x0C10; public static final int SREG_ERROR = 0x0C20; public static final int PAPE_ERROR = 0x0C30; public OpenIDException(String message) { this(message, OPENID_ERROR); } public OpenIDException(String message, int code) { super(message); _errorCode = code; } public OpenIDException(String message, Throwable cause) { this(message, OPENID_ERROR, cause); } public OpenIDException(String message, int code, Throwable cause) { super(message, cause); _errorCode = code; } public OpenIDException(Throwable cause) { this(OPENID_ERROR, cause); } public OpenIDException(int code, Throwable cause) { super(cause); _errorCode = code; } public int getErrorCode() { return _errorCode; } public void setErrorCode(int errorCode) { this._errorCode = errorCode; } // override getMessage() to prefix with the error code public String getMessage() { return "0x" + Integer.toHexString(_errorCode) + ": " + super.getMessage(); } } openid4java-0.9.6.662/src/org/openid4java/association/0000755001501200150120000000000011627733442021673 5ustar miguelmiguelopenid4java-0.9.6.662/src/org/openid4java/association/AssociationSessionType.java0000644001501200150120000002063411034531517027214 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Modells the session and association types allowed in OpenID associations. *

* Association requests and responses must have one of the * AssociationSessionType's defined here. *

* Compatibility mode flag defines backwards-compatibile value sets allowed * in OpenID 1.x, but not in OpenID 2 * * @see Association DiffieHellmanSession * @author Marius Scurtescu, Johnny Bufu */ public class AssociationSessionType implements Comparable { private static Log _log = LogFactory.getLog(AssociationSessionType.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final AssociationSessionType NO_ENCRYPTION_SHA1MAC = new AssociationSessionType("no-encryption", null, Association.TYPE_HMAC_SHA1, false, 0); public static final AssociationSessionType NO_ENCRYPTION_COMPAT_SHA1MAC = new AssociationSessionType("", null, Association.TYPE_HMAC_SHA1, true, 1); public static final AssociationSessionType NO_ENCRYPTION_SHA256MAC = new AssociationSessionType("no-encryption", null, Association.TYPE_HMAC_SHA256, false, 2); public static final AssociationSessionType DH_SHA1 = new AssociationSessionType("DH-SHA1", DiffieHellmanSession.H_ALGORITHM_SHA1, Association.TYPE_HMAC_SHA1, false, 3); public static final AssociationSessionType DH_COMPAT_SHA1 = new AssociationSessionType("DH-SHA1", DiffieHellmanSession.H_ALGORITHM_SHA1, Association.TYPE_HMAC_SHA1, true, 4); public static final AssociationSessionType DH_SHA256 = new AssociationSessionType("DH-SHA256", DiffieHellmanSession.H_ALGORITHM_SHA256, Association.TYPE_HMAC_SHA256, false, 5); /** * Session type; possible values are 'no-encryption', DH-*; * can be blank or null in compatibility mode. */ private String _sessType; /** * The H algorithm used for Diffie-Hellman sessions. * Null for no-encryption sessions. */ private String _hAlgorithm; /** * Association type; possible values are HMAC-SHA1 and HMAC-SHA256. */ private String _assocType; /** * Compatibility mode flag defines backwards-compatibile value sets allowed * in OpenID 1.x, but not in OpenID 2 */ private boolean _compat; /** * Field used for ordering and comparing the encryption 'level' of * AssociationSessionType's. * * @see #isBetter(AssociationSessionType) */ private int _order; /** * Creates a AssociationSessionType with all the specified parameters. * * @param sessType Session type * @param hAlgorithm H algorithm for Diffie-Hellman sessions * @param assocType Association type * @param compat True for compatibility-mode types, false otherwise * @param order internal order, used for sorting encryption level */ private AssociationSessionType(String sessType, String hAlgorithm, String assocType, boolean compat, int order) { _sessType = sessType; _hAlgorithm = hAlgorithm; _assocType = assocType; _compat = compat; _order = order; } /** * Creates a OpenID 2 AssociationSessionType with the specified session type * and HMAC-SHA1 association type. * * @param sessType The session type. */ public static AssociationSessionType create(String sessType) throws AssociationException { return create(sessType, Association.TYPE_HMAC_SHA1); } /** * Creates a OpenID 2 AssociationSessionType with the specified session and * association types. * * @param sessType The session type. * @param assocType The association type. */ public static AssociationSessionType create(String sessType, String assocType) throws AssociationException { return create(sessType, assocType, false); } /** * Creates a AssociationSessionType with the specified session and * association types. *

* Compatibility flag defines backwards-compatibile value sets allowed * in OpenID 1.x, but not in OpenID 2 * * @param sessType The session type. * @param assocType The association type. * @param compatibility True for OpenID 1.x association / * session types. * @throws AssociationException For unsupported parameter sets. */ public static AssociationSessionType create(String sessType, String assocType, boolean compatibility) throws AssociationException { AssociationSessionType result; if(! compatibility && "no-encryption".equals(sessType) && Association.TYPE_HMAC_SHA1.equals(assocType)) result = NO_ENCRYPTION_SHA1MAC; else if (! compatibility && "no-encryption".equals(sessType) && Association.TYPE_HMAC_SHA256.equals(assocType)) result = NO_ENCRYPTION_SHA256MAC; else if ( compatibility && ("".equals(sessType) || sessType == null) && (Association.TYPE_HMAC_SHA1.equals(assocType) || assocType == null)) { // sess_type: DH-SHA1, blank, may be omitted in v1 response // assoc_type: HMAC_SHA1, may be omitted in v1 requests result = NO_ENCRYPTION_COMPAT_SHA1MAC; } else if (! compatibility && "DH-SHA1".equals(sessType) && Association.TYPE_HMAC_SHA1.equals(assocType)) result = DH_SHA1; else if (compatibility && ("DH-SHA1".equals(sessType) || sessType == null)) result = DH_COMPAT_SHA1; else if (! compatibility && "DH-SHA256".equals(sessType) && Association.TYPE_HMAC_SHA256.equals(assocType) ) result = DH_SHA256; else throw new AssociationException( "Unsupported session / association type: " + sessType + " : " + assocType + ", compatibility: " + compatibility); if (DEBUG) _log.debug("Session:Association Type: " + result); return result; } /** * Gets the session type. */ public String getSessionType() { return _sessType; } /** * Gets the H algorithm of the Diffie-Hellman session, or null for * no-encryption session types. */ public String getHAlgorithm() { return _hAlgorithm; } /** * Gets the association type. */ public String getAssociationType() { return _assocType; } /** * Gets the MAC key size, in bits, of this association type. */ public int getKeySize() { if (Association.TYPE_HMAC_SHA1.equals(_assocType)) return Association.HMAC_SHA1_KEYSIZE; else if (Association.TYPE_HMAC_SHA256.equals(_assocType)) return Association.HMAC_SHA256_KEYSIZE; else return 0; } /** * Compares to another AssociationSessionType; used for sorting. */ public int compareTo(Object object) { AssociationSessionType that = (AssociationSessionType) object; if (this._order == that._order) return 0; else return this._order > that._order ? 1 : -1; } /** * Returns true if the specified argument's encryption level is considered * better than the one of the current instance. */ public boolean isBetter(AssociationSessionType other) { return this.compareTo(other) > 0; } /** * Returns true for OpenID 2 AssociationSessionType's, or false for * OpenID 1.x types. */ public boolean isVersion2() { return ! _compat; } public String toString() { return _sessType + ":" + _assocType + ":" + (_compat ? "OpenID1" : "OpenID2"); } } openid4java-0.9.6.662/src/org/openid4java/association/Association.java0000644001501200150120000002041011504002570024770 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.crypto.SecretKey; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; import java.security.GeneralSecurityException; import java.util.Date; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * @author Marius Scurtescu, Johnny Bufu */ public class Association implements Serializable { private static Log _log = LogFactory.getLog(Association.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String FAILED_ASSOC_HANDLE = " "; public static final String TYPE_HMAC_SHA1 = "HMAC-SHA1"; public static final String TYPE_HMAC_SHA256 = "HMAC-SHA256"; public static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; public static final int HMAC_SHA1_KEYSIZE = 160; public static final int HMAC_SHA256_KEYSIZE = 256; private String _type; private String _handle; private SecretKey _macKey; private Date _expiry; private Association(String type, String handle, SecretKey macKey, Date expiry) { if (DEBUG) _log.debug("Creating association, type: " + type + " handle: " + handle + " expires: " + expiry); _type = type; _handle = handle; _macKey = macKey; _expiry = expiry; } private Association(String type, String handle, SecretKey macKey, int expiryIn) { this(type, handle, macKey, new Date(System.currentTimeMillis() + expiryIn * 1000)); } public static Association getFailedAssociation(Date expiry) { return new Association(null, FAILED_ASSOC_HANDLE, null, expiry); } public static Association getFailedAssociation(int expiryIn) { return getFailedAssociation(new Date(System.currentTimeMillis() + expiryIn * 1000)); } public static Association generate(String type, String handle, int expiryIn) throws AssociationException { if (TYPE_HMAC_SHA1.equals(type)) { return generateHmacSha1(handle, expiryIn); } else if (TYPE_HMAC_SHA256.equals(type)) { return generateHmacSha256(handle, expiryIn); } else { throw new AssociationException("Unknown association type: " + type); } } public static Association generateHmacSha1(String handle, int expiryIn) { SecretKey macKey = generateMacSha1Key(); if (DEBUG) _log.debug("Generated SHA1 MAC key: " + macKey); return new Association(TYPE_HMAC_SHA1, handle, macKey, expiryIn); } public static Association createHmacSha1(String handle, byte[] macKeyBytes, int expiryIn) { SecretKey macKey = createMacKey(HMAC_SHA1_ALGORITHM, macKeyBytes); return new Association(TYPE_HMAC_SHA1, handle, macKey, expiryIn); } public static Association createHmacSha1(String handle, byte[] macKeyBytes, Date expDate) { SecretKey macKey = createMacKey(HMAC_SHA1_ALGORITHM, macKeyBytes); return new Association(TYPE_HMAC_SHA1, handle, macKey, expDate); } public static Association generateHmacSha256(String handle, int expiryIn) { SecretKey macKey = generateMacSha256Key(); if (DEBUG) _log.debug("Generated SHA256 MAC key: " + macKey); return new Association(TYPE_HMAC_SHA256, handle, macKey, expiryIn); } public static Association createHmacSha256(String handle, byte[] macKeyBytes, int expiryIn) { SecretKey macKey = createMacKey(HMAC_SHA256_ALGORITHM, macKeyBytes); return new Association(TYPE_HMAC_SHA256, handle, macKey, expiryIn); } public static Association createHmacSha256(String handle, byte[] macKeyBytes, Date expDate) { SecretKey macKey = createMacKey(HMAC_SHA256_ALGORITHM, macKeyBytes); return new Association(TYPE_HMAC_SHA256, handle, macKey, expDate); } protected static SecretKey generateMacKey(String algorithm, int keySize) { try { KeyGenerator keyGen = KeyGenerator.getInstance(algorithm); keyGen.init(keySize); return keyGen.generateKey(); } catch (NoSuchAlgorithmException e) { _log.error("Unsupported algorithm: " + algorithm + ", size: " + keySize, e); return null; } } protected static SecretKey generateMacSha1Key() { return generateMacKey(HMAC_SHA1_ALGORITHM, HMAC_SHA1_KEYSIZE); } protected static SecretKey generateMacSha256Key() { return generateMacKey(HMAC_SHA256_ALGORITHM, HMAC_SHA256_KEYSIZE); } public static boolean isHmacSupported(String hMacType) { String hMacAlgorithm; if (TYPE_HMAC_SHA1.equals(hMacType)) hMacAlgorithm = HMAC_SHA1_ALGORITHM; else if (TYPE_HMAC_SHA256.equals(hMacType)) hMacAlgorithm = HMAC_SHA256_ALGORITHM; else return false; try { KeyGenerator.getInstance(hMacAlgorithm); } catch (NoSuchAlgorithmException e) { return false; } return true; } public static boolean isHmacSha256Supported() { try { KeyGenerator.getInstance(HMAC_SHA256_ALGORITHM); return true; } catch (NoSuchAlgorithmException e) { return false; } } public static boolean isHmacSha1Supported() { try { KeyGenerator.getInstance(HMAC_SHA1_ALGORITHM); return true; } catch (NoSuchAlgorithmException e) { return false; } } protected static SecretKey createMacKey(String algorithm, byte[] macKey) { return new SecretKeySpec(macKey, algorithm); } public String getType() { return _type; } public String getHandle() { return _handle; } public SecretKey getMacKey() { return _macKey; } public Date getExpiry() { return _expiry; } public boolean hasExpired() { Date now = new Date(); return _expiry.before(now); } protected byte[] sign(byte[] data) throws AssociationException { try { String algorithm = _macKey.getAlgorithm(); Mac mac = Mac.getInstance(algorithm); mac.init(_macKey); return mac.doFinal(data); } catch (GeneralSecurityException e) { throw new AssociationException("Cannot sign!", e); } } public String sign(String text) throws AssociationException { if (DEBUG) _log.debug("Computing signature for input data:\n" + text); try { String signature = new String(Base64.encodeBase64(sign(text.getBytes("utf-8"))), "utf-8"); if (DEBUG) _log.debug("Calculated signature: " + signature); return signature; } catch (UnsupportedEncodingException e) { throw new AssociationException("Unsupported encoding for signed text.", e); } } public boolean verifySignature(String text, String signature) throws AssociationException { if (DEBUG) _log.debug("Verifying signature: " + signature); // The Java String.equals() method returns on the first difference in // its inputs, which allows a timing attack to recover signature values. // This verification method will take the same amount of time for any // two inputs of equal length. String textSig = sign(text); if (textSig.length() == 0 || textSig.length() != signature.length()) { return false; } int result = 0; for (int i = 0; i < textSig.length(); i++) { result |= textSig.charAt(i) ^ signature.charAt(i); } return result == 0; } } openid4java-0.9.6.662/src/org/openid4java/association/AssociationException.java0000644001501200150120000000155411034531517026665 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import org.openid4java.OpenIDException; /** * @author Marius Scurtescu, Johnny Bufu */ public class AssociationException extends OpenIDException { public AssociationException(String message) { super(message, ASSOC_ERROR); } public AssociationException(String message, int code) { super(message, code); } public AssociationException(String message, Throwable cause) { super(message, ASSOC_ERROR, cause); } public AssociationException(Throwable cause) { super(cause); } public AssociationException(int code, Throwable cause) { super(code, cause); } public AssociationException(String message, int code, Throwable cause) { super(message, code, cause); } } openid4java-0.9.6.662/src/org/openid4java/association/DiffieHellmanSession.java0000644001501200150120000003223111034531517026561 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHGenParameterSpec; import javax.crypto.spec.DHPublicKeySpec; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.interfaces.DHPrivateKey; import java.math.BigInteger; import java.security.*; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class DiffieHellmanSession { private static Log _log = LogFactory.getLog(DiffieHellmanSession.class); private static final boolean DEBUG = _log.isDebugEnabled(); public static final String DEFAULT_MODULUS_HEX = "DCF93A0B883972EC0E19989AC5A2CE310E1D37717E8D9571BB7623731866E61E" + "F75A2E27898B057F9891C2E27A639C3F29B60814581CD3B2CA3986D268370557" + "7D45C2E7E52DC81C7A171876E5CEA74B1448BFDFAF18828EFD2519F14E45E382" + "6634AF1949E5B535CC829A483B8A76223E5D490A257F05BDFF16F2FB22C583AB"; public static final String DEFAULT_MODULUS_BASE64 = "ANz5OguIOXLsDhmYmsWizjEOHTdxfo2Vcbt2I3MYZuYe91ouJ4mLBX+YkcLiemOc" + "Pym2CBRYHNOyyjmG0mg3BVd9RcLn5S3IHHoXGHblzqdLFEi/368Ygo79JRnxTkXj" + "gmY0rxlJ5bU1zIKaSDuKdiI+XUkKJX8Fvf8W8vsixYOr"; public static final long DEFAULT_GENERATOR = 2; public static final String DEFAULT_GENERATOR_BASE64 = "Ag=="; public static final String ALGORITHM = "DH"; public static final String H_ALGORITHM_SHA1 = "SHA-1"; public static final String H_ALGORITHM_SHA256 = "SHA-256"; private AssociationSessionType _type; private DHParameterSpec _dhParameterSpec; private KeyPair _keyPair; private MessageDigest _hDigest; private DiffieHellmanSession(AssociationSessionType type, DHParameterSpec dhParameterSpec) throws AssociationException { _type = type; _dhParameterSpec = dhParameterSpec; _keyPair = generateKeyPair(dhParameterSpec); try { _hDigest = MessageDigest.getInstance(_type.getHAlgorithm()); } catch (NoSuchAlgorithmException e) { throw new AssociationException("Unsupported H algorithm: " + _type.getHAlgorithm(), e); } } public String toString() { return _type + " base: " + _dhParameterSpec.getG() + " modulus: " + _dhParameterSpec.getP(); } public static DiffieHellmanSession create(AssociationSessionType type, String modulusBase64, String generatorBase64) throws AssociationException { byte[] modulus = Base64.decodeBase64(modulusBase64.getBytes()); byte[] generator = Base64.decodeBase64(generatorBase64.getBytes()); BigInteger p = new BigInteger(modulus); BigInteger g = new BigInteger(generator); DHParameterSpec dhParameterSpec = new DHParameterSpec(p, g); return create(type, dhParameterSpec); } public static DiffieHellmanSession create(AssociationSessionType type, DHParameterSpec dhParameterSpec) throws AssociationException { DiffieHellmanSession dh = new DiffieHellmanSession(type, dhParameterSpec); if (DEBUG) _log.debug("Created DH session: " + dh); return dh; } public static DHParameterSpec getDefaultParameter() { BigInteger p = new BigInteger(DEFAULT_MODULUS_HEX, 16); BigInteger g = BigInteger.valueOf(DEFAULT_GENERATOR); return new DHParameterSpec(p, g); } public static DHParameterSpec generateRandomParameter(int primeSize, int keySize) { try { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance(ALGORITHM); DHGenParameterSpec genParameterSpec = new DHGenParameterSpec(primeSize, keySize); paramGen.init(genParameterSpec); AlgorithmParameters params = paramGen.generateParameters(); DHParameterSpec result = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class); if (DEBUG) _log.debug("Generated random DHParameterSpec, base: " + result.getG() + ", modulus: " + result.getP()); return result; } catch (GeneralSecurityException e) { _log.error("Cannot generate DH params for primeSize: " + primeSize + " keySize: " + keySize, e); return null; } } protected static KeyPair generateKeyPair(DHParameterSpec dhSpec) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); keyGen.initialize(dhSpec); return keyGen.generateKeyPair(); } catch (GeneralSecurityException e) { _log.error("Cannot generate key pair for DHParameterSpec, base: " + dhSpec.getG() + ", modulus: " + dhSpec.getP() ); return null; } } public AssociationSessionType getType() { return _type; } /** * Gets the modulus for the Diffie-Hellman key echange. * This is the value passed in the openid.dh_modulus association * request parameter. * * @return The base 64 encoded two's-complement representation of the * modulus: base64(btwoc(p)) */ public String getModulus() { BigInteger p = _dhParameterSpec.getP(); return new String(Base64.encodeBase64(p.toByteArray())); } /** * Gets the generator for the Diffie-Hellman key echange. * This is the value passed in the openid.dh_gen association * request parameter. * * @return The base 64 encoded two's-complement representation of the * generator: base64(btwoc(g)) */ public String getGenerator() { BigInteger g = _dhParameterSpec.getG(); return new String(Base64.encodeBase64(g.toByteArray())); } /** * Get the Diffie-Hellman public key. * This is the value passed in the openid.dh_consumer_public * association request parameter and the value passed in the * openid.dh_server_public association response parameter. * * @return The base 64 encoded two's-complement representation of the * public key: base64(btwoc(g ^ x mod p)) */ public String getPublicKey() { DHPublicKey publicKey = (DHPublicKey) _keyPair.getPublic(); return publicKeyToString(publicKey); } protected DHPrivateKey getPrivateKey() { return (DHPrivateKey) _keyPair.getPrivate(); } /** * Encrypts the association MAC key. The encryption takes palce on the * server side (aka OP). This is the value passed in the * openid.enc_mac_key association response parameter. * * @param macKey The MAC key in binary format. * @param consumerPublicKeyBase64 The base 64 encoding of the consumer * Diffie-Hellman public key. This is the * value passed in the * openid.dh_consumer_public * association request parameter. * @return The base 64 encoded two's-complement * representation of the encrypted mac key: * base64(H(btwoc(g ^ (xa * xb) mod p)) XOR MAC) * @throws AssociationException if the lengths of the mac key and digest * of Diffie-Hellman shared secred do not * match. */ public String encryptMacKey(byte[] macKey, String consumerPublicKeyBase64) throws AssociationException { byte[] hzz = getDigestedZZ(consumerPublicKeyBase64); if (hzz.length != macKey.length) throw new AssociationException( "MAC key legth different from shared secret digest length!"); byte[] encMacKey = new byte[hzz.length]; for (int i = 0; i < hzz.length; i++) { byte b1 = hzz[i]; byte b2 = macKey[i]; encMacKey[i] = (byte) (b1 ^ b2); } String encMacKeyBase64 = new String(Base64.encodeBase64(encMacKey)); if (DEBUG) _log.debug("Encrypted MAC key Base64: " + encMacKeyBase64); return encMacKeyBase64; } /** * Decrypts the association AMC key. The decryption takes palce on the * consumer side (aka RP). * * @param encMacKeyBase64 The base 64 encoded two's-complement * representation of the encrypted mac key: * base64(H(btwoc(g ^ (xa * xb) mod p)) XOR MAC). * This is the value passed in the * openid.enc_mac_key association * response parameter. * @param serverPublicKeyBase64 The base 64 encoding of the server * Diffie-Hellman public key. This is the * value passed in the * openid.dh_server_public * association response parameter. * @return The MAC key in binary format. * @throws AssociationException if the lengths of the encrypted mac key * and digest of Diffie-Hellman shared * secret do not match. */ public byte[] decryptMacKey(String encMacKeyBase64, String serverPublicKeyBase64) throws AssociationException { byte[] hzz = getDigestedZZ(serverPublicKeyBase64); byte[] encMacKey = Base64.decodeBase64(encMacKeyBase64.getBytes()); if (hzz.length != encMacKey.length) throw new AssociationException( "Encrypted MAC key legth different from shared secret digest length!"); byte[] macKey = new byte[hzz.length]; for (int i = 0; i < hzz.length; i++) { byte b1 = hzz[i]; byte b2 = encMacKey[i]; macKey[i] = (byte) (b1 ^ b2); } if (DEBUG) _log.debug("Decrypted MAC key Base64: " + new String(Base64.encodeBase64(macKey))); return macKey; } protected static String publicKeyToString(DHPublicKey publicKey) { return new String(Base64.encodeBase64(publicKey.getY().toByteArray())); } protected DHPublicKey stringToPublicKey(String publicKeyBase64) { try { byte[] yBinary = Base64.decodeBase64(publicKeyBase64.getBytes()); BigInteger y = new BigInteger(yBinary); DHPublicKeySpec dhPublicKeySpec = new DHPublicKeySpec( y, _dhParameterSpec.getP(), _dhParameterSpec.getG() ); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); return (DHPublicKey) keyFactory.generatePublic(dhPublicKeySpec); } catch (GeneralSecurityException e) { _log.error("Cannot create PublicKey object from: " + publicKeyBase64, e); return null; } } protected byte[] getDigestedZZ(String otherPublicKeyBase64) { DHPublicKey dhPublicKey = stringToPublicKey(otherPublicKeyBase64); DHPrivateKey dhPrivateKey = getPrivateKey(); BigInteger xa = dhPrivateKey.getX(); BigInteger yb = dhPublicKey.getY(); BigInteger p = _dhParameterSpec.getP(); BigInteger zz = yb.modPow(xa, p); return _hDigest.digest(zz.toByteArray()); } private static boolean isDhSupported() { try { AlgorithmParameterGenerator.getInstance(ALGORITHM); KeyPairGenerator.getInstance(ALGORITHM); KeyFactory.getInstance(ALGORITHM); return true; } catch (NoSuchAlgorithmException e) { return false; } } public static boolean isDhSupported(AssociationSessionType type) { String hAlg = type.getHAlgorithm(); if (hAlg == null) // no encryption sessions return true; else return isDhShaSupported(hAlg); } public static boolean isDhShaSupported(String shaAlgorithm) { if (!isDhSupported()) return false; try { MessageDigest.getInstance(shaAlgorithm); return true; } catch (NoSuchAlgorithmException e) { return false; } } public static boolean isDhSha1Supported() { return isDhShaSupported(H_ALGORITHM_SHA1); } public static boolean isDhSha256Supported() { return isDhShaSupported(H_ALGORITHM_SHA256); } } openid4java-0.9.6.662/MAINTAINERS0000644001501200150120000000232711200345022015252 0ustar miguelmiguel.... OpenID4Java Library - MAINTAINERS ======================================================================== - M: Maintainer - S: Status: - supported : someone paid to look after this - maintained : someone looks after this - fixes/patches : someone that has contributed fixes/patches - orphan : no current maintainer, help needed! ------------------------------------------------------------------------ Entire Library, including documentation: M: Marius Scurtescu S: maintained M: Johnny Bufu S: maintained M: Sutra Zhou S: fixes/patches M: Shihab Hamid S: fixes/patches M: Justen Stepka S: fixes/patches ======================================================================== Copyright 2006-2008 Sxip Identity Corporation Project home page and package distribution: => http://code.google.com/p/openid4java => http://code.google.com/p/openid4java/downloads/ For support, please visit the wiki and join the Google Groups! => http://groups.google.com/group/openid4java/ => http://code.google.com/p/openid4java/w/ OpenID => http://openid.net/ Released under the Apache License 2.0 => see LICENSE openid4java-0.9.6.662/project.properties0000644001501200150120000000104511551251720017347 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # component.name=openid4java component.ver=0.9.6 jvm.ver=1.5 debug=true eol.style=unix # sources src=${basedir}/src # libs lib.dir=${basedir}/lib libext.dir=${lib.dir}/extra endorsed.dir=${lib.dir}/endorsed # tests test.dir=${basedir}/test test.src=${test.dir}/src test.data=${test.dir}/yadisdata test.servlet.port=8989 # compiled classes classes=${build}/classes classes.test=${build}/test/classes # build and distribution build=${basedir}/build # documentation apidoc=${basedir}/apidoc openid4java-0.9.6.662/LICENSE0000644001501200150120000002613711034532111014571 0ustar miguelmiguel Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. openid4java-0.9.6.662/VERSION0000644001501200150120000000006411553422342014635 0ustar miguelmiguel#Tue, 19 Apr 2011 17:12:18 -0700 Version=0.9.6.662 openid4java-0.9.6.662/test/0000755001501200150120000000000011034531505014540 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/0000755001501200150120000000000011627733442015343 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/0000755001501200150120000000000011034531505016116 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/0000755001501200150120000000000011034531510020316 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/consumer/0000755001501200150120000000000011627733442022171 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/consumer/InjectionTest.java0000644001501200150120000001012411352263621025604 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.consumer; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import junit.framework.TestCase; import org.apache.http.Header; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.util.AbstractHttpFetcher; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.HttpResponse; import java.util.Map; public class InjectionTest extends TestCase { public void testNonGuice() throws Exception { ConsumerManager m = new ConsumerManager(); HttpFetcher fetcher = m.getHttpFetcher(); assertTrue(fetcher instanceof HttpCache); assertEquals(0, fetcher.getDefaultRequestOptions().getMaxRedirects()); YadisResolver yadis = m.getDiscovery().getYadisResolver(); fetcher = yadis.getHttpFetcher(); assertTrue(fetcher instanceof HttpCache); assertEquals(10, fetcher.getDefaultRequestOptions().getMaxRedirects()); } public void testGuiceNoModule() throws Exception { Injector injector = Guice.createInjector(); ConsumerManager m = injector.getInstance(ConsumerManager.class); HttpFetcher fetcher = m.getHttpFetcher(); assertTrue(fetcher instanceof HttpCache); assertEquals(0, fetcher.getDefaultRequestOptions().getMaxRedirects()); YadisResolver yadis = m.getDiscovery().getYadisResolver(); fetcher = yadis.getHttpFetcher(); assertTrue(fetcher instanceof HttpCache); assertEquals(10, fetcher.getDefaultRequestOptions().getMaxRedirects()); } public void testGuiceInjectedFetcher() throws Exception { Injector injector = Guice.createInjector(new TestModule()); ConsumerManager m = injector.getInstance(ConsumerManager.class); HttpFetcher fetcher = m.getHttpFetcher(); assertTrue(fetcher instanceof TestFetcher); assertEquals(0, fetcher.getDefaultRequestOptions().getMaxRedirects()); YadisResolver yadis = m.getDiscovery().getYadisResolver(); fetcher = yadis.getHttpFetcher(); assertTrue(fetcher instanceof TestFetcher); assertEquals(10, fetcher.getDefaultRequestOptions().getMaxRedirects()); } private static class TestModule extends AbstractModule { @Override protected void configure() { bind(HttpFetcher.class).to(TestFetcher.class); } } private static class TestFetcher extends AbstractHttpFetcher { @Override public HttpResponse get(String url, HttpRequestOptions requestOptions) { return new TestHttpResponse(url, "test"); } @Override public HttpResponse head(String url, HttpRequestOptions requestOptions) { return new TestHttpResponse(url, "test"); } @Override public HttpResponse post(String url, Map content, HttpRequestOptions requestOptions) { return new TestHttpResponse(url, "test"); } } private static class TestHttpResponse implements HttpResponse { private final String url; private final String body; public TestHttpResponse(String url, String body) { this.url = url; this.body = body; } public String getBody() { return body; } public String getFinalUri() { return url; } public Header getResponseHeader(String headerName) { return null; } public Header[] getResponseHeaders(String headerName) { return new Header[0]; } public int getStatusCode() { return 200; } public boolean isBodySizeExceeded() { return false; } } } openid4java-0.9.6.662/test/src/org/openid4java/consumer/EhcacheNonceVerifierTest.java0000644001501200150120000000223711034531507027665 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import junit.framework.Test; import junit.framework.TestSuite; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Cache; /** * @author Marius Scurtescu, Johnny Bufu */ public class EhcacheNonceVerifierTest extends AbstractNonceVerifierTest { private CacheManager _cacheManager; public EhcacheNonceVerifierTest(String name) { super(name); } public void setUp() throws Exception { _cacheManager = new CacheManager(); super.setUp(); } public void tearDown() throws Exception { super.tearDown(); _cacheManager = null; } public NonceVerifier createVerifier(int maxAge) { _cacheManager.removalAll(); _cacheManager.addCache(new Cache("testCache", 100, false, false, maxAge, maxAge)); EhcacheNonceVerifier nonceVerifier = new EhcacheNonceVerifier(maxAge); nonceVerifier.setCache(_cacheManager.getCache("testCache")); return nonceVerifier; } public static Test suite() { return new TestSuite(EhcacheNonceVerifierTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/consumer/AbstractNonceVerifierTest.java0000644001501200150120000000566611034531507030121 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import org.openid4java.util.InternetDateFormat; import org.openid4java.server.NonceGenerator; import org.openid4java.server.IncrementalNonceGenerator; import java.util.Date; /** * @author Marius Scurtescu, Johnny Bufu */ public abstract class AbstractNonceVerifierTest extends TestCase { protected NonceVerifier _nonceVerifier; protected InternetDateFormat _dateFormat = new InternetDateFormat(); public static final int MAX_AGE = 60; public AbstractNonceVerifierTest(String name) { super(name); } public void setUp() throws Exception { _nonceVerifier = createVerifier(MAX_AGE); } public abstract NonceVerifier createVerifier(int maxAge); public void tearDown() throws Exception { super.tearDown(); } public void testSeen() { String nonce = _dateFormat.format(new Date()) + "abc"; assertEquals(NonceVerifier.OK, _nonceVerifier.seen("op1", nonce)); assertEquals(NonceVerifier.SEEN, _nonceVerifier.seen("op1", nonce)); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("op2", nonce)); } public void testMalformed() { assertEquals(NonceVerifier.INVALID_TIMESTAMP, _nonceVerifier.seen("op1", "xyz")); } public void testExpired() { Date now = new Date(); Date past = new Date(now.getTime() - (MAX_AGE + 1) * 1000); String nonce = _dateFormat.format(past) + "abc"; assertEquals(NonceVerifier.TOO_OLD, _nonceVerifier.seen("op1", nonce)); } public void testNonceCleanup() throws Exception { NonceGenerator nonceGenerator = new IncrementalNonceGenerator(); _nonceVerifier = createVerifier(1); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.com", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.com", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.com", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.com", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.net", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.net", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.net", nonceGenerator.next())); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.net", nonceGenerator.next())); Thread.sleep(1000); assertEquals(NonceVerifier.OK, _nonceVerifier.seen("http://example.org", nonceGenerator.next())); } public static Test suite() { return new TestSuite(AbstractNonceVerifierTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/consumer/InMemoryConsumerAssociationStoreTest.java0000644001501200150120000000160111034531507032345 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Marius Scurtescu */ public class InMemoryConsumerAssociationStoreTest extends ConsumerAssociationStoreTest { public InMemoryConsumerAssociationStoreTest(String name) { super(name); } protected ConsumerAssociationStore createStore() { return new InMemoryConsumerAssociationStore(); } public void testCleanup() throws InterruptedException { super.testCleanup(); InMemoryConsumerAssociationStore inMemoryAssociationStore = (InMemoryConsumerAssociationStore) _associationStore; assertEquals(1, inMemoryAssociationStore.size()); } public static Test suite() { return new TestSuite(InMemoryConsumerAssociationStoreTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/consumer/ConsumerAssociationStoreTest.java0000644001501200150120000000446611034531507030701 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.openid4java.association.Association; /** * @author Marius Scurtescu */ public abstract class ConsumerAssociationStoreTest extends TestCase { ConsumerAssociationStore _associationStore; public ConsumerAssociationStoreTest(String name) { super(name); } public void setUp() throws Exception { _associationStore = createStore(); } protected abstract ConsumerAssociationStore createStore(); public void tearDown() throws Exception { _associationStore = null; } public void testSaveLoadRemove() { _associationStore.save("http://example.com", Association.generateHmacSha1("a", 60)); _associationStore.save("http://example.com", Association.generateHmacSha256("b", 60)); _associationStore.save("http://example.com", Association.generateHmacSha1("c", 60)); assertNotNull(_associationStore.load("http://example.com", "a")); assertNotNull(_associationStore.load("http://example.com", "b")); assertNotNull(_associationStore.load("http://example.com", "c")); assertNotNull(_associationStore.load("http://example.com")); _associationStore.remove("http://example.com", "b"); assertNull(_associationStore.load("http://example.com", "b")); } public void testCleanup() throws InterruptedException { _associationStore.save("http://example.com", Association.generateHmacSha1("a", 1)); _associationStore.save("http://example.com", Association.generateHmacSha256("b", 1)); _associationStore.save("http://example.com", Association.generateHmacSha1("c", 1)); _associationStore.save("http://example.net", Association.generateHmacSha1("a", 1)); _associationStore.save("http://example.net", Association.generateHmacSha256("b", 1)); _associationStore.save("http://example.net", Association.generateHmacSha1("c", 1)); Thread.sleep(2000); _associationStore.save("http://example.org", Association.generateHmacSha1("d", 1)); } public static Test suite() { return new TestSuite(InMemoryConsumerAssociationStoreTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/consumer/InMemoryNonceVerifierTest.java0000644001501200150120000000147311034531507030105 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.consumer; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Marius Scurtescu, Johnny Bufu */ public class InMemoryNonceVerifierTest extends AbstractNonceVerifierTest { public InMemoryNonceVerifierTest(String name) { super(name); } public NonceVerifier createVerifier(int maxAge) { return new InMemoryNonceVerifier(maxAge); } public void testNonceCleanup() throws Exception { super.testNonceCleanup(); InMemoryNonceVerifier inMemoryVerifier = (InMemoryNonceVerifier) _nonceVerifier; assertEquals(1, inMemoryVerifier.size()); } public static Test suite() { return new TestSuite(InMemoryNonceVerifierTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/message/0000755001501200150120000000000011627733442021762 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/message/ParameterListTest.java0000644001501200150120000001604711034531505026235 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import java.util.List; /** * @author Marius Scurtescu, Johnny Bufu */ public class ParameterListTest extends TestCase { private ParameterList _parameterList; public ParameterListTest(String name) { super(name); } public void setUp() throws Exception { _parameterList = new ParameterList(); _parameterList.set(new Parameter("key1", "value1")); _parameterList.set(new Parameter("key1", "value2")); _parameterList.set(new Parameter("key2", "value1")); } public void tearDown() throws Exception { _parameterList = null; } public void testEquals() throws Exception { ParameterList parameterList2 = new ParameterList(); parameterList2.set(new Parameter("key1", "value1")); parameterList2.set(new Parameter("key1", "value2")); parameterList2.set(new Parameter("key2", "value1")); assertEquals(_parameterList, parameterList2); assertNotSame(_parameterList, parameterList2); parameterList2 = new ParameterList(); parameterList2.set(new Parameter("key2", "value1")); parameterList2.set(new Parameter("key1", "value1")); parameterList2.set(new Parameter("key1", "value2")); parameterList2.set(new Parameter("key3", "value1")); parameterList2.set(new Parameter("key3", "value2")); parameterList2.set(new Parameter("key3", "value1")); parameterList2.removeParameters("key3"); assertEquals(_parameterList, parameterList2); assertNotSame(_parameterList, parameterList2); parameterList2 = new ParameterList(); // null not supported in compareTo() //parameterList2.set(new Parameter(null, null)); //parameterList2.set(new Parameter(null, "")); //parameterList2.set(new Parameter("", null)); parameterList2.set(new Parameter("", "")); } public void testHashCode() throws Exception { ParameterList parameterList2 = new ParameterList(); parameterList2.set(new Parameter("key1", "value1")); parameterList2.set(new Parameter("key1", "value2")); parameterList2.set(new Parameter("key2", "value1")); assertEquals(_parameterList.hashCode(), parameterList2.hashCode()); assertNotSame(_parameterList, parameterList2); parameterList2 = new ParameterList(); parameterList2.set(new Parameter("key2", "value1")); parameterList2.set(new Parameter("key1", "value1")); parameterList2.set(new Parameter("key1", "value2")); parameterList2.set(new Parameter("key3", "value1")); parameterList2.set(new Parameter("key3", "value2")); parameterList2.set(new Parameter("key3", "value1")); parameterList2.removeParameters("key3"); assertEquals(_parameterList.hashCode(), parameterList2.hashCode()); assertNotSame(_parameterList, parameterList2); } public void testCopyConstructor() { ParameterList parameterList2 = new ParameterList(_parameterList); assertEquals(2, _parameterList.getParameters().size()); assertEquals(2, parameterList2.getParameters().size()); _parameterList.removeParameters("key1"); assertEquals(1, _parameterList.getParameters().size()); assertEquals(2, parameterList2.getParameters().size()); } public void testAdd() throws Exception { assertEquals(2, _parameterList.getParameters().size()); _parameterList.set(new Parameter("key3", "value1")); assertEquals(3, _parameterList.getParameters().size()); } public void testGetParameter() throws Exception { Parameter parameter = _parameterList.getParameter("key2"); assertNotNull(parameter); assertEquals("value1", parameter.getValue()); } public void testGetParameterNull() throws Exception { Parameter parameter = _parameterList.getParameter("key3"); assertNull(parameter); } public void testGetParameterValue() throws Exception { String value = _parameterList.getParameterValue("key2"); assertNotNull(value); assertEquals("value1", value); } public void testGetParameters() throws Exception { List parameters = _parameterList.getParameters(); assertEquals(2, parameters.size()); } public void testGetParameters1Null() throws Exception { assertNull(_parameterList.getParameterValue("key3")); } public void testRemoveParameters() throws Exception { _parameterList.removeParameters("key1"); assertEquals(1, _parameterList.getParameters().size()); _parameterList.removeParameters("key2"); assertEquals(0, _parameterList.getParameters().size()); } public void testReplaceParameters() throws Exception { _parameterList.set(new Parameter("key2", "value3")); assertEquals("value3", _parameterList.getParameter("key2").getValue()); } public void testHasParameter() throws Exception { assertTrue(_parameterList.hasParameter("key1")); assertTrue(_parameterList.hasParameter("key2")); assertFalse(_parameterList.hasParameter("key3")); } public void testCreateFromQueryString() throws Exception { ParameterList createdParameterList = ParameterList.createFromQueryString("key1=value%31&key1=value2&key2=value1"); assertEquals(_parameterList, createdParameterList); createdParameterList = ParameterList.createFromQueryString("key1=value%31&key1=&key2=value1"); assertEquals("", ((Parameter) createdParameterList.getParameters() .get(0)).getValue() ); createdParameterList = ParameterList.createFromQueryString("key1=value%31&key1=&key2="); assertEquals("", createdParameterList.getParameterValue("key2")); } public void testCreateFromKeyValueForm() throws Exception { ParameterList createdParameterList = ParameterList.createFromKeyValueForm("key1:value1\nkey1:value2\nkey2:value1"); assertEquals(_parameterList, createdParameterList); createdParameterList = ParameterList.createFromKeyValueForm("key1:value1\nkey1:\nkey2:value1"); assertEquals("", ((Parameter) createdParameterList.getParameters().get(0)).getValue() ); createdParameterList = ParameterList.createFromKeyValueForm("key1:value1\nkey1:\nkey2:"); assertEquals("", createdParameterList.getParameterValue("key2")); createdParameterList = ParameterList.createFromKeyValueForm("key1:value1\nkey2:value:2"); assertEquals("value:2", createdParameterList.getParameterValue("key2")); createdParameterList = ParameterList.createFromKeyValueForm("key1:value1\nkey2:value2\n"); assertEquals("value2", createdParameterList.getParameterValue("key2")); } public static Test suite() { return new TestSuite(ParameterListTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/message/MessageTest.java0000644001501200150120000000652211034531505025042 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; /** * @author Marius Scurtescu, Johnny Bufu */ public class MessageTest extends TestCase { private Message _msg; public MessageTest(String name) { super(name); } public void setUp() throws Exception { ParameterList params = new ParameterList(); params.set(new Parameter("key1", "value1")); params.set(new Parameter("key1", "value2")); params.set(new Parameter("key2", "value1")); _msg = new Message(params); } public void tearDown() throws Exception { _msg = null; } public void testKeyValueFormEncoding() throws Exception { String keyValueForm = "key1:value2\nkey2:value1\n"; assertEquals(keyValueForm, _msg.keyValueFormEncoding()); } public void testWwwFormEncoding() throws Exception { String wwwForm = "openid.key1=value2&openid.key2=value1"; assertEquals(wwwForm, _msg.wwwFormEncoding()); } public static Test suite() { return new TestSuite(MessageTest.class); } public void testNotAllowedChars() throws Exception { Parameter param; Map parameterMap; try { // semicolon in key param = new Parameter("some:key", "value"); parameterMap = new HashMap(); parameterMap.put(param.getKey(), param.getValue()); Message.createMessage(new ParameterList(parameterMap)); fail("A MessageException should be thrown " + "if the key/values contain invalid characters"); } catch (MessageException expected) { assertTrue(true); } try { // newline in key param = new Parameter("some\nkey\n", "value"); parameterMap = new HashMap(); parameterMap.put(param.getKey(), param.getValue()); Message.createMessage(new ParameterList(parameterMap)); fail("A MessageException should be thrown " + "if the key/values contain invalid characters"); } catch (MessageException expected) { assertTrue(true); } try { // newline in value param = new Parameter("key", "val\nue"); parameterMap = new HashMap(); parameterMap.put(param.getKey(), param.getValue()); Message.createMessage(new ParameterList(parameterMap)); fail("A MessageException should be thrown " + "if the key/values contain invalid characters"); } catch (MessageException expected) { assertTrue(true); } try { // all of the above param = new Parameter("some:\nkey", "value\n"); parameterMap = new HashMap(); parameterMap.put(param.getKey(), param.getValue()); Message.createMessage(new ParameterList(parameterMap)); fail("A MessageException should be thrown " + "if the key/values contain invalid characters"); } catch (MessageException expected) { assertTrue(true); } } } openid4java-0.9.6.662/test/src/org/openid4java/message/ParameterTest.java0000644001501200150120000000674311034531505025403 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; /** * @author Marius Scurtescu, Johnny Bufu */ public class ParameterTest extends TestCase { public ParameterTest(String name) { super(name); } public void testEquals() throws Exception { Parameter parameter1 = new Parameter("key", "value"); Parameter parameter2 = new Parameter("key", "value"); assertEquals(parameter1, parameter2); assertNotSame(parameter1, parameter2); parameter1 = new Parameter("", "value"); parameter2 = new Parameter("", "value"); assertEquals(parameter1, parameter2); assertNotSame(parameter1, parameter2); parameter1 = new Parameter("", ""); parameter2 = new Parameter("", ""); assertEquals(parameter1, parameter2); assertNotSame(parameter1, parameter2); parameter1 = new Parameter(null, ""); parameter2 = new Parameter(null, ""); assertEquals(parameter1, parameter2); assertNotSame(parameter1, parameter2); parameter1 = new Parameter(null, null); parameter2 = new Parameter(null, null); assertEquals(parameter1, parameter2); assertNotSame(parameter1, parameter2); parameter1 = new Parameter("key", "value1"); parameter2 = new Parameter("key", "value2"); assertFalse(parameter1.equals(parameter2)); assertNotSame(parameter1, parameter2); } public void testHashCode() throws Exception { Parameter parameter1 = new Parameter("key", "value"); Parameter parameter2 = new Parameter("key", "value"); assertEquals(parameter1.hashCode(), parameter2.hashCode()); assertNotSame(parameter1, parameter2); parameter1 = new Parameter("", "value"); parameter2 = new Parameter("", "value"); assertEquals(parameter1.hashCode(), parameter2.hashCode()); assertNotSame(parameter1, parameter2); parameter1 = new Parameter("", ""); parameter2 = new Parameter("", ""); assertEquals(parameter1.hashCode(), parameter2.hashCode()); assertNotSame(parameter1, parameter2); parameter1 = new Parameter(null, ""); parameter2 = new Parameter(null, ""); assertEquals(parameter1.hashCode(), parameter2.hashCode()); assertNotSame(parameter1, parameter2); parameter1 = new Parameter(null, null); parameter2 = new Parameter(null, null); assertEquals(parameter1.hashCode(), parameter2.hashCode()); assertNotSame(parameter1, parameter2); } public void testGetName() throws Exception { Parameter parameter = new Parameter(null, "value"); assertNull(parameter.getKey()); parameter = new Parameter("", "value"); assertEquals("", parameter.getKey()); parameter = new Parameter("key", "value"); assertEquals("key", parameter.getKey()); } public void testGetValue() throws Exception { Parameter parameter = new Parameter("key", null); assertNull(parameter.getValue()); parameter = new Parameter("key", ""); assertEquals("", parameter.getValue()); parameter = new Parameter("key", "value"); assertEquals("value", parameter.getValue()); } public static Test suite() { return new TestSuite(ParameterTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/0000755001501200150120000000000011627733442022345 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/discovery/exampleClaimed.xml0000644001501200150120000000043411034531507025770 0ustar miguelmiguel http://specs.openid.net/auth/2.0/signon http://op.example.com openid4java-0.9.6.662/test/src/org/openid4java/discovery/html/0000755001501200150120000000000011627733442023311 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/discovery/html/identityPage-with-xml-namespace.html0000644001501200150120000000074711155267317032335 0ustar miguelmiguel openid4java-0.9.6.662/test/src/org/openid4java/discovery/html/identityPage.html0000644001501200150120000000065111155267317026626 0ustar miguelmiguel openid4java-0.9.6.662/test/src/org/openid4java/discovery/html/CyberNekoDOMHtmlParserTest.java0000644001501200150120000000443411155267317031243 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import java.io.IOException; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.openid4java.discovery.DiscoveryException; /** * @author Sutra Zhou * */ public class CyberNekoDOMHtmlParserTest extends TestCase { private CyberNekoDOMHtmlParser parser; /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); parser = new CyberNekoDOMHtmlParser(); } /** * Test method for * {@link org.openid4java.discovery.html.CyberNekoDOMHtmlParser#parseHtml(java.lang.String, org.openid4java.discovery.html.HtmlResult)} * . * * @throws IOException * @throws DiscoveryException */ public void testParseHtml() throws IOException, DiscoveryException { String htmlData = IOUtils.toString(this.getClass().getResourceAsStream( "identityPage.html")); HtmlResult result = new HtmlResult(); parser.parseHtml(htmlData, result); assertEquals("http://www.example.com:8080/openidserver/users/myusername", result .getDelegate1()); System.out.println(result.getOP1Endpoint()); assertEquals("http://www.example.com:8080/openidserver/openid.server", result .getOP1Endpoint().toExternalForm()); } /** * Test method for * {@link org.openid4java.discovery.html.CyberNekoDOMHtmlParser#parseHtml(java.lang.String, org.openid4java.discovery.html.HtmlResult)} * . * * @throws IOException * @throws DiscoveryException */ public void testParseHtmlWithXmlNamespace() throws IOException, DiscoveryException { String htmlData = IOUtils.toString(this.getClass().getResourceAsStream( "identityPage-with-xml-namespace.html")); HtmlResult result = new HtmlResult(); parser.parseHtml(htmlData, result); assertEquals("http://www.example.com:8080/openidserver/users/myusername", result .getDelegate1()); assertEquals("http://www.example.com:8080/openidserver/openid.server", result .getOP1Endpoint().toExternalForm()); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/0000755001501200150120000000000011627733442023456 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/YadisUrlTest.java0000644001501200150120000000406111034531507026704 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; /** * @author Marius Scurtescu, Johnny Bufu */ public class YadisUrlTest extends TestCase { public YadisUrlTest(String name) { super(name); } // test the string constructor public void testUrl() throws YadisException { assertNotNull(new YadisUrl("http://example.com") ); assertNotNull(new YadisUrl("HTTP://EXAMPLE.COM")); assertNotNull(new YadisUrl("http://example.com/a/b?q=1#end")); assertNotNull(new YadisUrl("https://example.com")); assertNotNull(new YadisUrl("HTTPS://EXAMPLE.COM")); assertNotNull(new YadisUrl("https://example.com/a/b?q=1#end")); assertNotNull(new YadisUrl("HttpS://Example.Com")); } public void testUrlNoProtocol() throws YadisException { try { new YadisUrl("example.com"); fail("A YadisException should be raised " + "if the protocol was not specified"); } catch (YadisException expected) { assertTrue(true); } try { new YadisUrl("example.com/a/b?q=1#end"); fail("A YadisException should be raised " + "if the protocol was not specified"); } catch (YadisException expected) { assertTrue(true); } } public void testUrlProtocol() throws YadisException { try { new YadisUrl("ftp://example.com"); new YadisUrl("nntp://example.com"); new YadisUrl("file:///tmp/somefile"); new YadisUrl("smth://example.com/a/b?q=1#end"); fail("A YadisException should be raised " + "if the protocol is not HTTP or HTTPS"); } catch (YadisException expected) { assertTrue(true); } } public static Test suite() { return new TestSuite(YadisUrlTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/CyberNekoDOMYadisHtmlParserTest.java0000644001501200150120000000304611155267317032400 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; /** * @author Sutra Zhou * */ public class CyberNekoDOMYadisHtmlParserTest extends TestCase { private CyberNekoDOMYadisHtmlParser parser; /** * {@inheritDoc} */ protected void setUp() throws Exception { super.setUp(); parser = new CyberNekoDOMYadisHtmlParser(); } /** * Test method for * {@link org.openid4java.discovery.yadis.CyberNekoDOMYadisHtmlParser#getHtmlMeta(java.lang.String)} * . * * @throws IOException * @throws YadisException */ public final void testGetHtmlMetaIssue83() throws IOException, YadisException { String htmlData = getResourceAsString("issue83.html"); String s = parser.getHtmlMeta(htmlData); assertEquals("http://edevil.livejournal.com/data/yadis", s); } /** * Read the resource as string. * * @param name * the resource name * @return a string * @throws IOException * if an I/O error occurs */ private String getResourceAsString(String name) throws IOException { InputStream inputStream = CyberNekoDOMYadisHtmlParserTest.class.getResourceAsStream(name); try { return IOUtils.toString(inputStream); } finally { inputStream.close(); } } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/YadisResolverTest.java0000644001501200150120000004221511551247204027750 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.openid4java.OpenIDException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.util.HttpCache; import org.openid4java.util.HttpFetcher; import org.openid4java.util.HttpFetcherFactory; import org.openid4java.util.HttpRequestOptions; import java.util.Collections; import java.util.List; /** * @author Marius Scurtescu, Johnny Bufu */ public class YadisResolverTest extends TestCase { private int _servletPort; private YadisResolver _resolver; public static Server _server; static { System.getProperties().put("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "trace"); } public YadisResolverTest(final String testName) throws Exception { super(testName); _servletPort = Integer.parseInt(System.getProperty("SERVLET_PORT")); } public void setUp() throws Exception { _resolver = new YadisResolver(new HttpFetcherFactory()); _server = new Server(_servletPort); Context context = new Context(_server, "/", Context.SESSIONS); context.addServlet(new ServletHolder(new YadisTestServlet()), "/*"); _server.start(); } protected void tearDown() throws Exception { _server.stop(); } /* public void printResult(YadisResult result) { System.out.println("Yadis Status: " + result.isSuccess() + " (" + result.getStatusMessage() + ")"); System.out.println("YadisURL: " + result.getYadisUrl().getUrl()); System.out.println("XRDS-Location: " + result.getXrdsLocation()); System.out.println("Content-type: " + result.getContentType()); System.out.println("XRDS:\n" + result.getXrds()); } */ public static Test suite() { return new TestSuite(YadisResolverTest.class); } // --------------------- positive tests ------------------------------------ public void testHeadersUrl() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=simpleheaders", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testHeadersUrlToXmlContentTypeDocument() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=simpleheaders_xml", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testHtmlUrl() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?html=simplehtml", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testRedirectToHeaderResponse() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=redir_simpleheaders", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testRedirectToHtmlResponse() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=redir_simplehtml", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testRedirectToXrdsResponse() throws DiscoveryException { YadisResult result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=redir_simplexrds", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } public void testIncompleteHtmlParsing() throws DiscoveryException { // stop reading from the received HTML body shortly after the Yadis tag HttpFetcher cache = new HttpCache(); HttpRequestOptions requestOptions = cache.getRequestOptions(); requestOptions.setMaxBodySize(350); cache.setDefaultRequestOptions(requestOptions); YadisResolver resolver = new YadisResolver(cache); YadisResult result = resolver.discover("http://localhost:" + _servletPort + "/?html=simplehtml", 10, Collections.singleton("http://example.com/")); assertTrue(result.getEndpoints().size() > 0); } // -------------------- error handling tests ------------------------------- public void testInvalidUrl() { try { _resolver.discover("bla.com"); fail("Should have failed with error code " + OpenIDException.YADIS_INVALID_URL); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_INVALID_URL, expected.getErrorCode()); } } public void testHeadTransportError() throws Exception { _server.stop(); try { _resolver.discover("http://localhost:" + _servletPort + "/?servertopped"); fail("Should have failed with error code " + OpenIDException.YADIS_HEAD_TRANSPORT_ERROR); } catch (YadisException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HEAD_TRANSPORT_ERROR, expected.getErrorCode()); } } //public void testMultipleXrdsLocationInHeaders() //{ // YadisResult result = _resolver.discover("http://localhost:" + // _servletPort + "/?headers=multiplexrdslocation"); // // assertEquals(result.getStatusMessage(), // OpenIDException.YADIS_HEAD_INVALID_RESPONSE, result.isSuccess()); // // // todo: jetty's HttpResponse.addHeader() doesn't actually set... // assertEquals("should fail with multiple headers error", // "Found more than one", result.getStatusMessage().substring(0,19)); //} public void testInvalidXrdsLocationInHeaders() { try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=invalidxrdslocation1"); fail("Should have failed with error code " + OpenIDException.YADIS_HEAD_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HEAD_INVALID_RESPONSE, expected.getErrorCode()); } try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=invalidxrdslocation2"); fail("Should have failed with error code " + OpenIDException.YADIS_HEAD_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HEAD_INVALID_RESPONSE, expected.getErrorCode()); } } public void testInvalidXrdsLocationInGetHeaders() { try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplehtml&getheaders=invalidxrdslocation1"); fail("Should have failed with error code " + OpenIDException.YADIS_GET_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_GET_INVALID_RESPONSE, expected.getErrorCode()); } try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplehtml&getheaders=invalidxrdslocation2"); fail("Should have failed with error code " + OpenIDException.YADIS_GET_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_GET_INVALID_RESPONSE, expected.getErrorCode()); } } public void testMultipleXrdsLocationInHtml() { try { _resolver.discover("http://localhost:" + _servletPort + "/?html=multiplexrdslocation"); fail("Should have failed with error code " + OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, expected.getErrorCode()); } } public void testHtmlHeadElementsNoHead() { try { _resolver.discover("http://localhost:" + _servletPort + "/?html=nohead"); fail("Should have failed with error code " + OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, expected.getErrorCode()); } } public void testHtmlHeadElementsTwoHeads() { try { _resolver.discover("http://localhost:" + _servletPort + "/?html=twoheads"); fail("Should have failed with error code " + OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, expected.getErrorCode()); } } public void testHtmlHeadElementsExtraHeadInBody() { try { YadisResult result = _resolver.discover("http://localhost:" +_servletPort + "/?html=extraheadinbody", 10, Collections.singleton("http://example.com/")); assertTrue("Discovery should have ignored a html/body/head; " + " we only care about spurious html/head's", result.getEndpoints().size() == 1); } catch (DiscoveryException e) { fail("Discovery should have ignored a html/body/head; " + " we only care about spurious html/head's"); } } public void testHtmlHeadNoMeta() throws DiscoveryException { List result = _resolver.discover("http://localhost:" + _servletPort + "/?html=headnometa"); assertEquals("Should have discovered no endpoints; found: " + result.size(), result.size(), 0); } public void testEmptyHtml() { try { _resolver.discover("http://localhost:" + _servletPort + "/?html=empty"); fail("Should have failed with error code " + OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_HTMLMETA_INVALID_RESPONSE, expected.getErrorCode()); } } public void testGetError() throws Exception { try { _resolver.discover("http://localhost:" + _servletPort + "/?html=nonexistantfile"); fail("Should have failed with error code " + OpenIDException.YADIS_GET_ERROR); } catch (YadisException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_GET_ERROR, expected.getErrorCode()); } } // should make the server fail for the HTTP GET // but not for the HEAD that is tried first //public void testGetTransportError() throws Exception //{ // //_server.stop(); // // YadisResult result = _resolver.discover("http://localhost:" + // _servletPort + "/?headers=simplehtml&html=failonget"); // // assertEquals(expected.getMessage(), // OpenIDException.YADIS_GET_TRANSPORT_ERROR, expected.getErrorCode()); //} public void testXrdsSizeExceeded() { HttpRequestOptions requestOptions = new HttpRequestOptions(); requestOptions.setMaxBodySize(10); HttpFetcher cache = new HttpCache(); cache.setDefaultRequestOptions(requestOptions); YadisResolver resolver = new YadisResolver(cache); try { resolver.discover("http://localhost:" + _servletPort + "/?headers=simpleheaders"); fail("Should have failed with error code " + OpenIDException.YADIS_XRDS_SIZE_EXCEEDED); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_XRDS_SIZE_EXCEEDED, expected.getErrorCode()); } } public void testMalformedXML() { try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds1"); fail("Should have failed with error code " + OpenIDException.XRDS_PARSING_ERROR); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.XRDS_PARSING_ERROR, expected.getErrorCode()); } try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds2"); fail("Should have failed with error code " + OpenIDException.XRDS_PARSING_ERROR); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.XRDS_PARSING_ERROR, expected.getErrorCode()); } } public void testMalformedXRDSServiceURI() { try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds3"); fail("Should have failed with error code " + OpenIDException.XRDS_PARSING_ERROR); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.XRDS_PARSING_ERROR, expected.getErrorCode()); } try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds4"); fail("Should have failed with error code " + OpenIDException.XRDS_PARSING_ERROR); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.XRDS_PARSING_ERROR, expected.getErrorCode()); } try { _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds5"); // "bla bla" matches xrd.xsd's URIPriorityAppendPattern type, so this one won't be a parse error; hmm... fail("Should have failed with error code " + OpenIDException.YADIS_INVALID_URL); } catch (DiscoveryException expected) { assertEquals(expected.getMessage(), OpenIDException.YADIS_INVALID_URL, expected.getErrorCode()); } } public void testXrdsOpenidDelegate() throws Exception { List result; try { result = _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=xrdsdelegate"); assertEquals("Should have discovered one endpoint: ", result.size(), 1); DiscoveryInformation info = (DiscoveryInformation) result.get(0); assertNotNull("Should have discovered an openid:Delegate.", info.getDelegateIdentifier()); } catch (DiscoveryException e) { fail("Discovery failed on xrdsdelegate: " + e.getMessage()); } } public void testEmptyUri() throws Exception { // empty string is a valid java.net.URI... YadisResult yadis = _resolver.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds6", 10, Collections.singleton("http://example.com/")); assertTrue("XRDS with an empty URI is valid; Yadis should have succeeded", yadis.getEndpoints().size() > 0); // also run through Discovery.extractDiscoveryInformation() ConsumerManager manager = new ConsumerManager(); List results = manager.discover("http://localhost:" + _servletPort + "/?headers=simplexrds&xrds=malformedxrds6"); assertEquals("No discovery information should have been returned for an empty URI", 0, results.size()); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/issue83.html0000644001501200150120000004746311155267317025664 0ustar miguelmiguel André Cruz
Home
André Cruz [entries|archive|friends|userinfo]
André Cruz

[ website | My Home ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

[Mar. 20th, 2007|04:31 pm]
Txi. Tanta publicidade...
link1 comment|post comment

Look, a title. [Jul. 17th, 2006|11:37 am]
[Tags|]

An entry.
link3 comments|post comment

Teste [Apr. 19th, 2006|04:59 pm]
Teste de post.
linkpost comment

(no subject) [Feb. 22nd, 2006|03:10 pm]
<table width=300 align=center border=1 bordercolor=black cellspacing=0 cellpadding=2>
<tr><td bgcolor=#66CCFF align=center>
<font face="Georgia, Times New Roman, Times, serif" style='color:black; font-size: 14pt;'>
<b>You Are the Reformer</b></font></td></tr>
<tr><td align=center bgcolor=#FFFFFF>
<center>
  <font color="#0000CC" size="+6">
  1
  </font>
</center>

<font color="#000000">
You're a responsible person - with a clear sense of right and wrong.

High standards are important to you, and you do everything to meet them.

You are your own worst critic, feeling ashamed if you're not perfect.

You have the highest integrity, and people expect you to be fair.
</font></td></tr></table>

<div align="center">
<a href="http://www.blogthings.com/numberquiz.html">What number are you?</a>
</div>
linkpost comment

(no subject) [Feb. 22nd, 2006|03:10 pm]


You Are the Reformer



1




You're a responsible person - with a clear sense of right and wrong.

High standards are important to you, and you do everything to meet them.

You are your own worst critic, feeling ashamed if you're not perfect.

You have the highest integrity, and people expect you to be fair.


linkpost comment

(no subject) [Jan. 24th, 2006|02:59 pm]
Isto é um teste .
link1 comment|post comment

(no subject) [Nov. 28th, 2005|03:05 pm]
Teste
link4 comments|post comment

navigation
[ viewing | most recent entries ]

Advertisement

openid4java-0.9.6.662/test/src/org/openid4java/discovery/yadis/YadisTestServlet.java0000644001501200150120000001101711034531507027565 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.yadis; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import java.io.*; /** * Simple servlet that builds up responses from varios test-data files * for testing the Yadis protocol. * * @author Marius Scurtescu, Johnny Bufu */ public class YadisTestServlet extends HttpServlet { String _testDataPath; public YadisTestServlet() throws ServletException { _testDataPath = System.getProperty("YADIS_TEST_DATA"); if (_testDataPath == null) throw new ServletException("YADIS_TEST_DATA path not initialized"); } public void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set the headers String headersFile = request.getParameter("headers"); setHeadersFromFile(headersFile, response); } /** * Builds a response based on the parameters received in the request, * with the following conventions: * * - the header name-values are extracted from a file with the name specified * by the "headers" or "getheaders" (if they need to be different * for HEAD and GET requests) parameters; * the file should contain a "headername=value" pair on each line * Status code should be given on a line with the header name "status" * * - if there is a "xrds" parameter, its value should point to a file * which is streamed for download * * - otherwise, if there is a "html" parameter, its value should point * to a file which is returned as a HTML resonse * * Headers will always be set if specified; only one of "xrds" and "html" * (in this order) will be handled. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String headersFile = request.getParameter("headers"); String getHeadersFile = request.getParameter("getheaders"); String xrdsFile = request.getParameter("xrds"); String htmlFile = request.getParameter("html"); // set the headers if (getHeadersFile != null) setHeadersFromFile(getHeadersFile, response); else if (headersFile != null) setHeadersFromFile(headersFile, response); // XRDS download if (xrdsFile != null) { BufferedInputStream input = new BufferedInputStream( new FileInputStream(_testDataPath + "/xrds/" + xrdsFile)); ServletOutputStream output = response.getOutputStream(); byte[] data = new byte[8192]; int bytesRead = input.read(data, 0, data.length); while (bytesRead > 0) { output.write(data, 0, bytesRead); bytesRead = input.read(data, 0, data.length); } input.close(); output.close(); } else if (htmlFile != null) // HTML response { BufferedReader input = new BufferedReader( new FileReader(_testDataPath + "/html/" + htmlFile)); //PrintWriter output = new PrintWriter( response.getWriter()); ServletOutputStream output = response.getOutputStream(); String line = input.readLine(); while (line != null) { output.println(line); line = input.readLine(); } input.close(); output.close(); } } private void setHeadersFromFile(String filename, HttpServletResponse response) throws IOException { BufferedReader input = new BufferedReader( new FileReader(_testDataPath + "/headers/" + filename)); String line; while ((line = input.readLine()) != null) { int equalPos = line.indexOf("="); if (equalPos > -1) { String headerName = line.substring(0, equalPos); String headerValue = line.substring(equalPos + 1); if (headerName.equals("status")) response.setStatus(Integer.parseInt(headerValue)); else { response.addHeader(headerName, headerValue); } } } } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/DiscoveryTest.java0000644001501200150120000000554411250065351026014 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import javax.servlet.ServletException; /** * @author Marius Scurtescu, Johnny Bufu */ public class DiscoveryTest extends TestCase { private String _testDataPath; private Discovery _discovery; public DiscoveryTest(String name) throws ServletException { super(name); _testDataPath = System.getProperty("TEST_DATA"); _discovery = new Discovery(); if (_testDataPath == null) throw new ServletException("TEST_DATA path not initialized"); } public void testParseUrl() throws DiscoveryException { assertTrue(_discovery.parseIdentifier("http://example.com") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("HTTP://EXAMPLE.COM") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("http://example.com/a/b?q=1#end") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("https://example.com") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("HTTPS://EXAMPLE.COM") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("https://example.com/a/b?q=1#end") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("HttpS://Example.Com") instanceof UrlIdentifier); } public void testParseUrlNoProtocol() throws DiscoveryException { assertTrue(_discovery.parseIdentifier("example.com") instanceof UrlIdentifier); assertTrue(_discovery.parseIdentifier("example.com/a/b?q=1#end") instanceof UrlIdentifier); UrlIdentifier identifier = (UrlIdentifier) _discovery.parseIdentifier("example.com"); assertEquals("http", identifier.getUrl().getProtocol()); } public void testParseXri() throws DiscoveryException { assertTrue(_discovery.parseIdentifier("xri://=example") instanceof XriIdentifier); assertTrue(_discovery.parseIdentifier("xri://example") instanceof UrlIdentifier); } public void testParseXriNoProtocol() throws DiscoveryException { assertTrue(_discovery.parseIdentifier("=example") instanceof XriIdentifier); assertTrue(_discovery.parseIdentifier("@example") instanceof XriIdentifier); assertTrue(_discovery.parseIdentifier("$example") instanceof XriIdentifier); assertTrue(_discovery.parseIdentifier("+example") instanceof XriIdentifier); assertTrue(_discovery.parseIdentifier("!!1234") instanceof XriIdentifier); } //todo: tests for multiple discovered services / priorities //todo: XRI path+query / service selection //http://openid.net/pipermail/general/2006-October/000512.html public static Test suite() { return new TestSuite(DiscoveryTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/exampleDelegate.xml0000644001501200150120000000052611034531507026146 0ustar miguelmiguel http://specs.openid.net/auth/2.0/signon http://op.example.com http://op.example.com/user openid4java-0.9.6.662/test/src/org/openid4java/discovery/exampleDelegate1.xml0000644001501200150120000000060611034531507026226 0ustar miguelmiguel http://openid.net/signon/1.0 http://op.example.com http://op.example.com/user openid4java-0.9.6.662/test/src/org/openid4java/discovery/NormalizationTest.java0000644001501200150120000000562311551247205026675 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery; import junit.framework.TestCase; /** * @author Marius Scurtescu, Johnny Bufu */ public class NormalizationTest extends TestCase { private Discovery _discovery; public NormalizationTest(String membersitePath) { super(membersitePath); _discovery = new Discovery(); } public void testCaseNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/"); assertEquals("http://example.com/", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/A/B?Q=Z#END"); assertEquals("http://example.com/A/B?Q=Z#END", identifier.getIdentifier()); } public void testPercentCaseNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/%3d"); assertEquals("http://example.com/%3D", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/a?%3d"); assertEquals("http://example.com/a?%3D", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/a?q#%3d"); assertEquals("http://example.com/a?q#%3D", identifier.getIdentifier()); } public void testPercentNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM/%63"); assertEquals("http://example.com/c", identifier.getIdentifier()); } public void testPortNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("HTTP://EXAMPLE.COM:80/A/B?Q=Z#"); assertEquals("http://example.com/A/B?Q=Z#", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("https://example.com:443"); assertEquals("https://example.com/", identifier.getIdentifier()); } public void testPathNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("http://example.com//a/./b/../b/c/"); assertEquals("http://example.com/a/b/c/", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("http://example.com"); assertEquals("http://example.com/", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("http://example.com?bla"); assertEquals("http://example.com/?bla", identifier.getIdentifier()); identifier = _discovery.parseIdentifier("http://example.com#bla"); assertEquals("http://example.com/#bla", identifier.getIdentifier()); } public void testFragmentNormalization() throws DiscoveryException { Identifier identifier = _discovery.parseIdentifier("http://example.com/#123"); assertEquals("http://example.com/#123", identifier.getIdentifier()); } } openid4java-0.9.6.662/test/src/org/openid4java/discovery/exampleOP.xml0000644001501200150120000000043511034531507024751 0ustar miguelmiguel http://specs.openid.net/auth/2.0/server http://op.example.com openid4java-0.9.6.662/test/src/org/openid4java/discovery/xrds/0000755001501200150120000000000011627733442023325 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/discovery/xrds/XrdsParserTest.java0000644001501200150120000001034311140116772027115 0ustar miguelmiguelpackage org.openid4java.discovery.xrds; import junit.framework.TestCase; import org.openid4java.discovery.DiscoveryInformation; /** * @author jbufu */ public class XrdsParserTest extends TestCase { public void testXrdsParse() throws Exception { XrdsParser parser = new XrdsParserImpl(); parser.parseXrds(XRD, DiscoveryInformation.OPENID_OP_TYPES); } public static final String XRD = "\n" + "\n" + // "\n" + " \n" + "\n" + " *foo\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " 2005-05-30T09:30:10Z\n" + "\n" + " xri://(tel:+1-201-555-0123)\n" + "\n" + " *baz\n" + "\n" + " https://example.com/example/resource/\n" + "\n" + " xri://(tel:+1-201-555-0123)!1234\n" + "\n" + " \n" + "\n" + " xri://=!4a76!c2f7!9033.78bd\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " \n" + " xri://(tel:+1-201-555-0123)!1234\n" + "\n" + " \n" + "\n" + " xri://$res*auth*($v*2.0)\n" + "\n" + " application/xrds+xml\n" + "\n" + " http://resolve.example.com\n" + "\n" + " http://resolve2.example.com\n" + "\n" + " https://resolve.example.com\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " \n" + " xri://(tel:+1-201-555-0123)!1234\n" + "\n" + " \n" + "\n" + " xri://$res*auth*($v*2.0)\n" + "\n" + " application/xrds+xml;https=true\n" + "\n" + " https://resolve.example.com\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " \n" + "\n" + " /media/pictures\n" + "\n" + " image/jpeg\n" + "\n" + " http://pictures.example.com\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " \n" + "\n" + " /media/videos\n" + "\n" + " video/mpeg\n" + "\n" + " http://videos.example.com\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " xri://!!1000!1234.5678\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " http://example.com/local\n" + "\n" + " \n" + "\n" + " \n" + "\n" + " http://example.com/some/service/v3.1\n" + "\n" + " http://example.com/some/service/endpoint\n" + "\n" + " https://example.com/example/resource/\n" + "\n" + " \n" + "\n" + " \n" + "\n" + ""; }openid4java-0.9.6.662/test/src/org/openid4java/server/0000755001501200150120000000000011627733442021644 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/server/RealmVerifierTest.java0000644001501200150120000000661611352263620026103 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.util.HttpFetcherFactory; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; /** * @author Marius Scurtescu, Johnny Bufu */ public class RealmVerifierTest extends TestCase { private static final String TEST_DATA_FILE = "RealmTestData.xml"; private static final Map _resultCodes = new HashMap(); private String _testDataPath; static { _resultCodes.put("OK", new Integer(RealmVerifier.OK)); _resultCodes.put("DENIED_REALM", new Integer(RealmVerifier.DENIED_REALM)); _resultCodes.put("MALFORMED_REALM", new Integer(RealmVerifier.MALFORMED_REALM)); _resultCodes.put("MALFORMED_RETURN_TO_URL", new Integer(RealmVerifier.MALFORMED_RETURN_TO_URL)); _resultCodes.put("FRAGMENT_NOT_ALLOWED", new Integer(RealmVerifier.FRAGMENT_NOT_ALLOWED)); _resultCodes.put("PROTOCOL_MISMATCH", new Integer(RealmVerifier.PROTOCOL_MISMATCH)); _resultCodes.put("PORT_MISMATCH", new Integer(RealmVerifier.PORT_MISMATCH)); _resultCodes.put("PATH_MISMATCH", new Integer(RealmVerifier.PATH_MISMATCH)); _resultCodes.put("DOMAIN_MISMATCH", new Integer(RealmVerifier.DOMAIN_MISMATCH)); } private RealmVerifier _realmVerifier; public RealmVerifierTest(String name) throws ServletException { super(name); _testDataPath = System.getProperty("TEST_DATA"); if (_testDataPath == null) throw new ServletException("TEST_DATA path not initialized"); } public void setUp() throws Exception { _realmVerifier = new RealmVerifier(false, new YadisResolver(new HttpFetcherFactory())); } public void testXmlFile() throws IOException, JDOMException { InputStream in = new BufferedInputStream( new FileInputStream(_testDataPath + "/server/" + TEST_DATA_FILE)); assertNotNull("XML data file could not be loaded: " + TEST_DATA_FILE, in); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(in); Element testSuite = document.getRootElement(); List tests = testSuite.getChildren("test"); for (int i = 0; i < tests.size(); i++) { Element test = (Element) tests.get(i); String result = test.getAttributeValue("result"); String realm = test.getAttributeValue("realm"); String returnTo = test.getAttributeValue("returnTo"); String message = test.getAttributeValue("message"); Integer resultCode = (Integer) _resultCodes.get(result); if (message == null) assertEquals(resultCode.intValue(), _realmVerifier.match(realm, returnTo)); else assertEquals(message, resultCode.intValue(), _realmVerifier.match(realm, returnTo)); } } public static Test suite() { return new TestSuite(RealmVerifierTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/server/RealmTestData.xml0000644001501200150120000001602311140116772025051 0ustar miguelmiguel openid4java-0.9.6.662/test/src/org/openid4java/server/AbstractNonceGeneratorTest.java0000644001501200150120000000334011034531506027731 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import java.util.Set; import java.util.HashSet; import java.util.Date; import java.text.ParseException; import org.openid4java.util.InternetDateFormat; /** * @author Marius Scurtescu, Johnny Bufu */ public abstract class AbstractNonceGeneratorTest extends TestCase { protected InternetDateFormat _dateFormat = new InternetDateFormat(); protected NonceGenerator _nonceGenerator; public AbstractNonceGeneratorTest(String name) { super(name); } public void setUp() throws Exception { _nonceGenerator = createGenerator(); } public abstract NonceGenerator createGenerator(); public void testUniqueLoop() { Set seen = new HashSet(); for (int i = 0; i < 100; i++) { String nonce = _nonceGenerator.next(); if (seen.contains(nonce)) fail("Double nonce!"); seen.add(nonce); } } public void testUniqueSequential() { String nonce1 = _nonceGenerator.next(); String nonce2 = _nonceGenerator.next(); String nonce3 = _nonceGenerator.next(); assertFalse(nonce1.equals(nonce2)); assertFalse(nonce2.equals(nonce3)); } public void testTimestamp() throws ParseException { String nonce = _nonceGenerator.next(); Date nonceDate = _dateFormat.parse(nonce); assertNotNull(nonceDate); assertTrue(nonceDate.before(new Date())); } public static Test suite() { return new TestSuite(AbstractNonceGeneratorTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/server/InMemoryServerAssociationStoreTest.java0000644001501200150120000000172111034531506031475 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import junit.framework.Test; import junit.framework.TestSuite; import org.openid4java.association.AssociationException; /** * @author Marius Scurtescu, Johnny Bufu */ public class InMemoryServerAssociationStoreTest extends AbstractServerAssociationStoreTest { public InMemoryServerAssociationStoreTest(String name) { super(name); } public ServerAssociationStore createStore() { return new InMemoryServerAssociationStore(); } public void testCleanup() throws AssociationException, InterruptedException { super.testCleanup(); InMemoryServerAssociationStore inMemoryAssociationStore = (InMemoryServerAssociationStore) _associationStore; assertEquals(1, inMemoryAssociationStore.size()); } public static Test suite() { return new TestSuite(InMemoryServerAssociationStoreTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/server/AbstractServerAssociationStoreTest.java0000644001501200150120000000613611034531506031506 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; /** * @author Marius Scurtescu, Johnny Bufu */ public abstract class AbstractServerAssociationStoreTest extends TestCase { protected ServerAssociationStore _associationStore; public AbstractServerAssociationStoreTest(String name) { super(name); } public void setUp() throws Exception { _associationStore = createStore(); } public abstract ServerAssociationStore createStore(); public void testGenerate() throws AssociationException { Association association = _associationStore.generate(Association.TYPE_HMAC_SHA1, 60); assertNotNull(association); assertSame(association, _associationStore.load(association.getHandle())); association = _associationStore.generate(Association.TYPE_HMAC_SHA256, 60); assertNotNull(association); assertSame(association, _associationStore.load(association.getHandle())); } public void testGenerateBadType() { try { String badType = "xyz"; _associationStore.generate(badType, 60); fail("Should throw exception for bad associtation type: " + badType); } catch (AssociationException e) { } } public void testLoad() throws AssociationException { assertNull(_associationStore.load(null)); assertNull(_associationStore.load("")); assertNull(_associationStore.load("xyz")); String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 60).getHandle(); assertNotNull(_associationStore.load(handle)); assertNotNull(_associationStore.load(handle)); } public void testExpiry() throws AssociationException, InterruptedException { String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 1).getHandle(); assertNotNull(_associationStore.load(handle)); Thread.sleep(2000); assertNull(_associationStore.load(handle)); } public void testRemove() throws AssociationException { String handle = _associationStore.generate(Association.TYPE_HMAC_SHA1, 1).getHandle(); assertNotNull(_associationStore.load(handle)); _associationStore.remove(handle); assertNull(_associationStore.load(handle)); } public void testCleanup() throws AssociationException, InterruptedException { _associationStore.generate(Association.TYPE_HMAC_SHA1, 1); _associationStore.generate(Association.TYPE_HMAC_SHA1, 1); _associationStore.generate(Association.TYPE_HMAC_SHA1, 1); _associationStore.generate(Association.TYPE_HMAC_SHA1, 1); Thread.sleep(2000); _associationStore.generate(Association.TYPE_HMAC_SHA1, 1); } public static Test suite() { return new TestSuite(AbstractServerAssociationStoreTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/server/IncrementalNonceGeneratorTest.java0000644001501200150120000000111411034531506030424 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.server; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Marius Scurtescu, Johnny Bufu */ public class IncrementalNonceGeneratorTest extends AbstractNonceGeneratorTest { public IncrementalNonceGeneratorTest(String name) { super(name); } public NonceGenerator createGenerator() { return new IncrementalNonceGenerator(); } public static Test suite() { return new TestSuite(IncrementalNonceGeneratorTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/infocard/0000755001501200150120000000000011627733442022123 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/infocard/OpenIDTokenTest.java0000644001501200150120000000412311034531506025732 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.infocard; import junit.framework.TestCase; public class OpenIDTokenTest extends TestCase { public OpenIDTokenTest(String name) { super(name); } public void setUp() throws Exception { } public void testCreateFromXmlToken() throws Exception { String xmlToken ="" + "openid.ns:http://specs.openid.net/auth/2.0\n" + "\n" + "openid.mode:id_res\n" + "\n" + "openid.op_endpoint:https://example-op.com/openid-server/\n" + "\n" + "openid.claimed_id:https://example-op.com/johndoe/\n" + "\n" + "openid.identity:https://example-op.com/johndoe/\n" + "\n" + "openid.return_to:https://example-rp.com/openid-infocard-endpoint/\n" + "\n" + "openid.response_nonce:2007-06-28T22:16:58Z0\n" + "\n" + "openid.assoc_handle:d38f38e8166443cb\n" + "\n" + "openid.signed:op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle\n" + "\n" + "openid.sig:PZNucb3/5KnEHsOXEMFkg1FJAnGD+UbGR1LqsscVvEc=\n" + "\n" + "openid.ns.ext1:http://openid.net/srv/ax/1.0\n" + "\n" + "openid.ext1.mode:fetch_response\n" + "\n" + "openid.ext1.type.FirstName:http://axschema.org/namePerson/first\n" + "\n" + "openid.ext1.value.FirstName:John\n" + "\n" + "openid.ext1.type.LastName:http://axschema.org/namePerson/last\n" + "\n" + "openid.ext1.value.LastName:Doe\n" + "\n" + "openid.ext1.type.email:http://axschema.org/contact/email\n" + "\n" + "openid.ext1.value.email:johndoe@example.com" + ""; OpenIDToken token = OpenIDToken.createFromXmlToken(xmlToken); assertNotNull(token); } } openid4java-0.9.6.662/test/src/org/openid4java/util/0000755001501200150120000000000011627733442021313 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/util/InternetDateFormatTest.java0000644001501200150120000000205211034531510026534 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.util; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import java.util.Date; import java.text.ParseException; /** * @author Marius Scurtescu, Johnny Bufu */ public class InternetDateFormatTest extends TestCase { InternetDateFormat _dateFormat; public InternetDateFormatTest(String name) { super(name); } protected void setUp() throws Exception { _dateFormat = new InternetDateFormat(); } public void testFormat() { Date date0 = new Date(0); assertEquals("1970-01-01T00:00:00Z", _dateFormat.format(date0)); } public void testParse() throws ParseException { Date date0 = new Date(0); assertEquals(date0, _dateFormat.parse("1970-01-01T00:00:00Z")); assertEquals(date0, _dateFormat.parse("1970-01-01t00:00:00z")); } public static Test suite() { return new TestSuite(InternetDateFormatTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/samples/0000755001501200150120000000000011627733442022002 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/samples/LoginServlet.java0000644001501200150120000000217711034531506025256 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openid4java.consumer.SampleConsumer; public class LoginServlet extends HttpServletSupport { private static final long serialVersionUID = 1L; private SampleConsumer consumer_; public LoginServlet(SampleConsumer consumer) { consumer_ = consumer; } protected void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception { if (req.getParameter("openid_identifier") != null) { logger_.info("openind_identifier set => try to consume"); consumer_.authRequest(req.getParameter("openid_identifier"), req, resp); } else { logger_.info("display form"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("
"); } } } openid4java-0.9.6.662/test/src/org/openid4java/samples/UserInfoServlet.java0000644001501200150120000000331211140116772025732 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserInfoServlet extends HttpServletSupport { private static final long serialVersionUID = 1L; protected void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception { String serverUrl = "http://" + req.getServerName() + ":" + req.getServerPort() + "/provider"; String back; if ("html".equals(req.getParameter("format"))) { resp.setContentType("text/html"); back = "\n" + "\n" + "in html" ; } else { resp.setContentType("application/xrds+xml"); back = "\n" + "\n" + " \n" + " \n" + " http://openid.net/signon/1.0\n" + " http://" + req.getServerName() + ":" + req.getServerPort() + "/provider\n" + " \n" + " \n" + "" ; } PrintWriter out = resp.getWriter(); out.write(back); } } openid4java-0.9.6.662/test/src/org/openid4java/samples/ConsumerAndProviderTest.java0000644001501200150120000001125111275161465027435 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.util.ArrayList; import java.util.List; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; import org.openid4java.consumer.SampleConsumer; import org.openid4java.message.ParameterList; import org.openid4java.server.SampleServer; import org.openid4java.server.ServerException; import net.sourceforge.jwebunit.junit.WebTester; //import com.gargoylesoftware.htmlunit.Page; //import com.gargoylesoftware.htmlunit.WebClient; //import com.gargoylesoftware.htmlunit.html.HtmlForm; //import com.gargoylesoftware.htmlunit.html.HtmlPage; //import com.meterware.httpunit.HttpInternalErrorException; //import com.meterware.httpunit.WebConversation; //import com.meterware.httpunit.WebForm; //import com.meterware.httpunit.WebResponse; import junit.framework.TestCase; public class ConsumerAndProviderTest extends TestCase { static { System.getProperties().put("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "trace"); } private Server _server; private String _baseUrl; public ConsumerAndProviderTest(final String testName) throws Exception { super(testName); int servletPort = Integer.parseInt(System.getProperty("SERVLET_PORT", "8989")); _server = new Server(servletPort); Context context = new Context(_server, "/", Context.SESSIONS); _baseUrl = "http://localhost:" + servletPort; // + // context.getContextPath(); SampleConsumer consumer = new SampleConsumer(_baseUrl + "/loginCallback"); context.addServlet(new ServletHolder(new LoginServlet(consumer)), "/login"); context.addServlet(new ServletHolder(new LoginCallbackServlet(consumer)), "/loginCallback"); context.addServlet(new ServletHolder(new UserInfoServlet()), "/user"); SampleServer server = new SampleServer(_baseUrl + "/provider") { protected List userInteraction(ParameterList request) throws ServerException { List back = new ArrayList(); back.add("userSelectedClaimedId"); // userSelectedClaimedId back.add(Boolean.TRUE); // authenticatedAndApproved back.add("user@example.com"); // email return back; } }; context.addServlet(new ServletHolder(new ProviderServlet(server)), "/provider"); } public void setUp() throws Exception { _server.start(); } protected void tearDown() throws Exception { _server.stop(); _server.join(); } public void testCycleWithXrdsUser() throws Exception { HttpServletSupport.lastException = null; HttpServletSupport.count_ = 0; WebTester wc = new WebTester(); try { wc.setScriptingEnabled(false); wc.beginAt(_baseUrl + "/login"); wc.setTextField("openid_identifier", _baseUrl + "/user"); wc.submit(); wc.clickLink("login"); wc.assertTextPresent("success"); wc.assertTextPresent("emailFromFetch:user@example.com"); wc.assertTextPresent("emailFromSReg:user@example.com"); } catch (Exception exc) { System.err.println("last page before exception :" + wc.getPageSource()); if (HttpServletSupport.lastException != null) { throw HttpServletSupport.lastException; } else { throw exc; } } } public void testCycleWithHtmlUser() throws Exception { HttpServletSupport.lastException = null; HttpServletSupport.count_ = 0; WebTester wc = new WebTester(); try { wc.setScriptingEnabled(false); wc.beginAt(_baseUrl + "/login"); wc.setTextField("openid_identifier", _baseUrl + "/user?format=html"); wc.submit(); wc.clickLink("login"); wc.assertTextPresent("success"); wc.assertTextPresent("emailFromFetch:user@example.com"); wc.assertTextPresent("emailFromSReg:user@example.com"); } catch (Exception exc) { System.err.println("last page before exception :" + wc.getPageSource()); if (HttpServletSupport.lastException != null) { throw HttpServletSupport.lastException; } else { throw exc; } } } } openid4java-0.9.6.662/test/src/org/openid4java/samples/LoginCallbackServlet.java0000644001501200150120000000336111034531506026667 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openid4java.consumer.SampleConsumer; public class LoginCallbackServlet extends HttpServletSupport { private static final long serialVersionUID = 1L; private SampleConsumer consumer_; public LoginCallbackServlet(SampleConsumer consumer) { consumer_ = consumer; } protected void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception { if (req.getParameterMap().isEmpty()) { logger_.info("no parameter => display required (with only a title tag)"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("login callback"); } else { logger_.info("verify response"); resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); if (consumer_.verifyResponse(req) != null) { logger_.info("success"); out.print("success{"); out.print("openid_identifier:" + req.getSession().getAttribute("openid_identifier")); out.print("emailFromFetch:" + req.getSession().getAttribute("emailFromFetch")); out.print(", emailFromSReg:" + req.getSession().getAttribute("emailFromSReg")); out.print("}"); } else { logger_.info("failure"); out.println("failed"); } out.flush(); } } } openid4java-0.9.6.662/test/src/org/openid4java/samples/ProviderServlet.java0000644001501200150120000000220111034531506025764 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openid4java.server.SampleServer; public class ProviderServlet extends HttpServletSupport { private static final long serialVersionUID = 1L; private SampleServer server_; public ProviderServlet(SampleServer server) { server_ = server; } protected void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception { logger_.info("start processing..."); String back = server_.processRequest(req, resp); if (back != null) { logger_.info("processing not null :" + back); PrintWriter out = resp.getWriter(); if (back.startsWith("http")) { resp.setContentType("text/html"); out.write("Login"); } else { out.write(back); } } } } openid4java-0.9.6.662/test/src/org/openid4java/samples/HttpServletSupport.java0000644001501200150120000000272511034531506026521 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.samples; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.NDC; public abstract class HttpServletSupport extends HttpServlet { protected static final long serialVersionUID = 1L; protected static Exception lastException; protected static int count_; protected Logger logger_; public HttpServletSupport() { logger_ = Logger.getLogger(getClass()); } protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { count_++; String ndcName = getClass().getName(); ndcName = ndcName.substring(ndcName.lastIndexOf('.')+1); NDC.push(ndcName); NDC.push("call-" + count_); logger_.info("begin onService"); try { onService(req, resp); } catch (Exception exc) { lastException = exc; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { logger_.info("end onService"); NDC.pop(); NDC.pop(); } } protected abstract void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception; } openid4java-0.9.6.662/test/src/org/openid4java/association/0000755001501200150120000000000011627733442022652 5ustar miguelmiguelopenid4java-0.9.6.662/test/src/org/openid4java/association/DiffieHellmanSessionTestData.xml0000644001501200150120000001010011034531510031031 0ustar miguelmiguel openid4java-0.9.6.662/test/src/org/openid4java/association/DiffieHellmanSessionTest.java0000644001501200150120000002057311034531510030377 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import javax.crypto.spec.DHParameterSpec; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.interfaces.DHPrivateKey; import java.security.KeyPair; import java.security.GeneralSecurityException; import java.math.BigInteger; import org.apache.commons.codec.binary.Base64; /** * @author Marius Scurtescu, Johnny Bufu */ public class DiffieHellmanSessionTest extends TestCase { public DiffieHellmanSessionTest(String name) { super(name); } public void testGetDefaultParameterSha1() throws Exception { DHParameterSpec parameterSpec = DiffieHellmanSession.getDefaultParameter(); assertNotNull(parameterSpec); assertEquals(2, parameterSpec.getG().intValue()); assertEquals(DiffieHellmanSession.DEFAULT_MODULUS_HEX.length() * 4, parameterSpec.getP().bitLength()); } public void testGetDefaultParameterSha256() throws Exception { DHParameterSpec parameterSpec = DiffieHellmanSession.getDefaultParameter(); assertNotNull(parameterSpec); assertEquals(2, parameterSpec.getG().intValue()); assertEquals(DiffieHellmanSession.DEFAULT_MODULUS_HEX.length() * 4, parameterSpec.getP().bitLength()); } public void testGenerateRandomParameterSha1() throws Exception { DHParameterSpec parameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); assertNotNull(parameterSpec); assertEquals(512, parameterSpec.getP().bitLength()); } public void testGenerateRandomParameterSha256() throws Exception { DHParameterSpec parameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); assertNotNull(parameterSpec); assertEquals(512, parameterSpec.getP().bitLength()); } public void testGenerateKeyPairSha1Default() { DHParameterSpec parameterSpec = DiffieHellmanSession.getDefaultParameter(); KeyPair keyPair = DiffieHellmanSession.generateKeyPair(parameterSpec); assertNotNull(keyPair); } public void testGenerateKeyPairSha256Default() { DHParameterSpec parameterSpec = DiffieHellmanSession.getDefaultParameter(); KeyPair keyPair = DiffieHellmanSession.generateKeyPair(parameterSpec); assertNotNull(keyPair); } public void testGenerateKeyPairSha1Random() { DHParameterSpec parameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); KeyPair keyPair = DiffieHellmanSession.generateKeyPair(parameterSpec); assertNotNull(keyPair); } public void testGenerateKeyPairSha256Random() { DHParameterSpec parameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); KeyPair keyPair = DiffieHellmanSession.generateKeyPair(parameterSpec); assertNotNull(keyPair); } public void testPublicKeyConversion() throws AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter(); DiffieHellmanSession diffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA1, dhParameterSpec); String publicKeyBase64 = diffieHellmanSession.getPublicKey(); assertNotNull(publicKeyBase64); DHPublicKey publicKey = diffieHellmanSession.stringToPublicKey(publicKeyBase64); assertNotNull(publicKey); assertEquals(publicKeyBase64, DiffieHellmanSession.publicKeyToString(publicKey)); } public void testEncryptDecryptMacKeySha1() throws GeneralSecurityException, AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter(); assertNotNull(dhParameterSpec); DiffieHellmanSession consumerDiffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA1, dhParameterSpec); byte[] macKey = Association.generateMacKey(Association.HMAC_SHA1_ALGORITHM, Association.HMAC_SHA1_KEYSIZE).getEncoded(); testEncryptDecryptMacKey(consumerDiffieHellmanSession, macKey); } public void testEncryptDecryptMacKeySha1Random() throws GeneralSecurityException, AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); assertNotNull(dhParameterSpec); DiffieHellmanSession consumerDiffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA1, dhParameterSpec); byte[] macKey = Association.generateMacKey(Association.HMAC_SHA1_ALGORITHM, Association.HMAC_SHA1_KEYSIZE).getEncoded(); testEncryptDecryptMacKey(consumerDiffieHellmanSession, macKey); } public void testEncryptDecryptMacKeySha256() throws GeneralSecurityException, AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter(); assertNotNull(dhParameterSpec); DiffieHellmanSession consumerDiffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA256, dhParameterSpec); byte[] macKey = Association.generateMacKey(Association.HMAC_SHA256_ALGORITHM, Association.HMAC_SHA256_KEYSIZE).getEncoded(); testEncryptDecryptMacKey(consumerDiffieHellmanSession, macKey); } public void testEncryptDecryptMacKeySha256Random() throws GeneralSecurityException, AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.generateRandomParameter(512, 256); assertNotNull(dhParameterSpec); DiffieHellmanSession consumerDiffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA256, dhParameterSpec); byte[] macKey = Association.generateMacKey(Association.HMAC_SHA256_ALGORITHM, Association.HMAC_SHA256_KEYSIZE).getEncoded(); testEncryptDecryptMacKey(consumerDiffieHellmanSession, macKey); } private void testEncryptDecryptMacKey(DiffieHellmanSession consumerDiffieHellmanSession, byte[] macKey) throws AssociationException { AssociationSessionType type = consumerDiffieHellmanSession.getType(); String modulusBase64 = consumerDiffieHellmanSession.getModulus(); String generatorBase64 = consumerDiffieHellmanSession.getGenerator(); String consumerPublicKeyBase64 = consumerDiffieHellmanSession.getPublicKey(); String consumerPrivateKeyBase64 = privateKeyToString(consumerDiffieHellmanSession.getPrivateKey()); DiffieHellmanSession serverDiffieHellmanSession = DiffieHellmanSession.create(type, modulusBase64, generatorBase64); assertEquals(type, serverDiffieHellmanSession.getType()); assertEquals(modulusBase64, serverDiffieHellmanSession.getModulus()); assertEquals(generatorBase64, serverDiffieHellmanSession.getGenerator()); String serverPublicKeyBase64 = serverDiffieHellmanSession.getPublicKey(); String serverPrivateKeyBase64 = privateKeyToString(serverDiffieHellmanSession.getPrivateKey()); String macKeyBase64 = new String(Base64.encodeBase64(macKey)); String encMacBase64 = serverDiffieHellmanSession.encryptMacKey(macKey, consumerPublicKeyBase64); byte[] macKey2 = consumerDiffieHellmanSession.decryptMacKey(encMacBase64, serverPublicKeyBase64); assertEquals(macKey.length, macKey2.length); for (int i = 0; i < macKey.length; i++) { assertEquals(macKey[i], macKey2[i]); } } public void testPublicKey() throws AssociationException { DHParameterSpec dhParameterSpec = DiffieHellmanSession.getDefaultParameter(); DiffieHellmanSession diffieHellmanSession = DiffieHellmanSession.create(AssociationSessionType.DH_SHA1, dhParameterSpec); String dhPublicKeyBase64 = diffieHellmanSession.getPublicKey(); DHPublicKey dhPublicKey = diffieHellmanSession.stringToPublicKey(dhPublicKeyBase64); BigInteger two = new BigInteger("2"); BigInteger y = dhPublicKey.getY(); BigInteger p = dhParameterSpec.getP(); assertTrue(y.compareTo(two) != -1); assertTrue(y.compareTo(p) == -1); } private static String privateKeyToString(DHPrivateKey dhPrivateKey) { return new String(Base64.encodeBase64(dhPrivateKey.getX().toByteArray())); } public static Test suite() { return new TestSuite(DiffieHellmanSessionTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/association/AssociationTest.java0000644001501200150120000000463011034531510026614 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.association; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * @author Marius Scurtescu, Johnny Bufu */ public class AssociationTest extends TestCase { public AssociationTest(String name) { super(name); } public void testGenerateSha1() { SecretKey secretKey = Association.generateMacSha1Key(); assertNotNull(secretKey); assertTrue(secretKey instanceof SecretKeySpec); SecretKeySpec secretKeySpec = (SecretKeySpec) secretKey; assertEquals(Association.HMAC_SHA1_ALGORITHM.toUpperCase(), secretKeySpec.getAlgorithm().toUpperCase()); assertEquals(20, secretKeySpec.getEncoded().length); } public void testGenerateSha256() { if (Association.isHmacSha256Supported()) { SecretKey secretKey = Association.generateMacSha256Key(); assertNotNull(secretKey); assertTrue(secretKey instanceof SecretKeySpec); SecretKeySpec secretKeySpec = (SecretKeySpec) secretKey; assertEquals(Association.HMAC_SHA256_ALGORITHM.toUpperCase(), secretKeySpec.getAlgorithm().toUpperCase()); assertEquals(32, secretKeySpec.getEncoded().length); } } public void testSignSha1() throws AssociationException { Association association = Association.generate(Association.TYPE_HMAC_SHA1, "test", 100); String macKeyBase64 = new String(Base64.encodeBase64(association.getMacKey().getEncoded())); String text = "key1:value1\nkey2:value2\n"; String signature = association.sign(text); assertTrue(association.verifySignature(text, signature)); } public void testSignSha256() throws AssociationException { Association association = Association.generate(Association.TYPE_HMAC_SHA256, "test", 100); String macKeyBase64 = new String(Base64.encodeBase64(association.getMacKey().getEncoded())); String text = "key1:value1\nkey2:value2\n"; String signature = association.sign(text); assertTrue(association.verifySignature(text, signature)); } public static Test suite() { return new TestSuite(AssociationTest.class); } } openid4java-0.9.6.662/test/src/org/openid4java/association/AssociationTestData.xml0000644001501200150120000000065111034531510027264 0ustar miguelmiguel key1:value1 key2:value2 key1:value1 key2:value2 openid4java-0.9.6.662/test/src/log4j.properties0000644001501200150120000000140711140116773020472 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # log4j.rootLogger=INFO, File, Console log4j.logger.org.openid4java=DEBUG #log4j.logger.org.openid4java=WARN log4j.logger.org.openid4java.samples=DEBUG log4j.appender.File=org.apache.log4j.FileAppender log4j.appender.File.File=build/test/testLog.txt log4j.appender.File.layout=org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern=[%-5p] %d{ABSOLUTE} [%-40F:%4L] %-20x : %m%n log4j.appender.File.append=false log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Threshold=DEBUG #log4j.appender.Console.Target=System.out log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%-5p] %d{ABSOLUTE} [%-40F:%4L] %-20x : %m%n openid4java-0.9.6.662/test/yadisdata/0000755001501200150120000000000011034531504016502 5ustar miguelmiguelopenid4java-0.9.6.662/test/yadisdata/headers/0000755001501200150120000000000011627733442020132 5ustar miguelmiguelopenid4java-0.9.6.662/test/yadisdata/headers/invalidxrdslocation10000644001501200150120000000016611034531505024205 0ustar miguelmiguelstatus=200 X-XRDS-Location=ftp://localhost:SERVLET_PORT/?xrds=simplexrds&headers=simplexrds Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/headers/redir_simplexrds0000644001501200150120000000016111034531505023416 0ustar miguelmiguelstatus=302 Location=http://localhost:SERVLET_PORT/?headers=simplexrds&xrds=simplexrds Content-Type=text/plain openid4java-0.9.6.662/test/yadisdata/headers/multiplexrdslocation0000644001501200150120000000026711034531505024333 0ustar miguelmiguelstatus=200 X-XRDS-Location=http://localhost:SERVLET_PORT/?xrds=simplexrds&headers=simplexrds X-XRDS-Location=http://localhost:SERVLET_PORT/?xrds=simplexrds Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/headers/simpleheaders_xml0000644001501200150120000000016611130536342023552 0ustar miguelmiguelstatus=200 X-XRDS-Location=http://localhost:SERVLET_PORT/?xrds=simplexrds&headers=simplexml Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/headers/redir_simpleheaders0000644001501200150120000000014411034531505024052 0ustar miguelmiguelstatus=302 Location=http://localhost:SERVLET_PORT/?headers=simpleheaders Content-Type=text/plain openid4java-0.9.6.662/test/yadisdata/headers/invalidxrdslocation20000644001501200150120000000026011034531505024201 0ustar miguelmiguelstatus=200 X-XRDS-Location=http://localhost:SERVLET_PORT/?xrds=simplexrds&headers=simplexrds X-XRDS-Location=localhost:SERVLET_PORT/?xrds=simplexrds Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/headers/simplexrds0000644001501200150120000000005711034531505022235 0ustar miguelmiguelstatus=200 Content-Type=application/xrds+xml openid4java-0.9.6.662/test/yadisdata/headers/redir_simplehtml0000644001501200150120000000013611034531505023404 0ustar miguelmiguelstatus=302 Location=http://localhost:SERVLET_PORT/?html=simplehtml Content-Type=text/plain openid4java-0.9.6.662/test/yadisdata/headers/simplexml0000644001501200150120000000004311130536342022051 0ustar miguelmiguelstatus=200 Content-Type=text/xml openid4java-0.9.6.662/test/yadisdata/headers/simpleheaders0000644001501200150120000000016711034531505022672 0ustar miguelmiguelstatus=200 X-XRDS-Location=http://localhost:SERVLET_PORT/?xrds=simplexrds&headers=simplexrds Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/headers/simplehtml0000644001501200150120000000004411034531505022215 0ustar miguelmiguelstatus=200 Content-Type=text/html openid4java-0.9.6.662/test/yadisdata/html/0000755001501200150120000000000011627733442017463 5ustar miguelmiguelopenid4java-0.9.6.662/test/yadisdata/html/nohead0000644001501200150120000000014711034531504020631 0ustar miguelmiguel

Joe Schmoe's Homepage

Blah blah blah blah blah blah blah

openid4java-0.9.6.662/test/yadisdata/html/multiplexrdslocation0000644001501200150120000000055011034531504023656 0ustar miguelmiguel Joe Schmoe's Homepage

Joe Schmoe's Homepage

Blah blah blah blah blah blah blah

openid4java-0.9.6.662/test/yadisdata/html/empty0000644001501200150120000000000011034531504020515 0ustar miguelmiguelopenid4java-0.9.6.662/test/yadisdata/html/headnometa0000644001501200150120000000065511130536342021506 0ustar miguelmiguel Joe Schmoe's Homepage

Joe Schmoe's larger than 350 bytes Homepage

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

openid4java-0.9.6.662/test/yadisdata/html/simplehtml0000644001501200150120000000103511034531504021546 0ustar miguelmiguel Joe Schmoe's Homepage

Joe Schmoe's larger than 350 bytes Homepage

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

Blah blah blah blah blah blah blah

openid4java-0.9.6.662/test/yadisdata/html/extraheadinbody0000644001501200150120000000047611034532367022562 0ustar miguelmiguel Joe Schmoe's Homepage

Joe Schmoe's Homepage

Blah blah blah blah blah blah blah

some other head, inside the html body openid4java-0.9.6.662/test/yadisdata/html/twoheads0000644001501200150120000000045211034531504021210 0ustar miguelmiguel Joe Schmoe's Homepage some other head..

Joe Schmoe's Homepage

Blah blah blah blah blah blah blah

openid4java-0.9.6.662/test/yadisdata/xrds/0000755001501200150120000000000011627733442017477 5ustar miguelmiguelopenid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds30000644001501200150120000000043011034531504022334 0ustar miguelmiguel http://example.com/ : openid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds40000644001501200150120000000043411034531504022341 0ustar miguelmiguel http://example.com/ http: openid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds60000644001501200150120000000042711034531504022345 0ustar miguelmiguel http://example.com/ openid4java-0.9.6.662/test/yadisdata/xrds/simplexrds0000644001501200150120000000046411034531504021603 0ustar miguelmiguel http://example.com/ http://www.openidenabled.com/ openid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds20000644001501200150120000000044511034531504022341 0ustar miguelmiguel http://example.com/ http://www.openidenabled.com/ openid4java-0.9.6.662/test/yadisdata/xrds/xrdsdelegate0000644001501200150120000000066311200624345022066 0ustar miguelmiguel http://openid.net/signon/1.1 http://www.openidenabled.com/ http://example.com/delegate/ openid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds10000644001501200150120000000042711034531504022340 0ustar miguelmiguel http://example.com/ http://www.openidenabled.com/ openid4java-0.9.6.662/test/yadisdata/xrds/malformedxrds50000644001501200150120000000046211140116772022347 0ustar miguelmiguel http://specs.openid.net/auth/2.0/signon bla bla openid4java-0.9.6.662/lib/0000755001501200150120000000000011627733442014343 5ustar miguelmiguelopenid4java-0.9.6.662/apidoc/0000755001501200150120000000000011627733441015033 5ustar miguelmiguelopenid4java-0.9.6.662/pom.xml0000644001501200150120000003125711551252241015107 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 maven2/pom.xml openid4java-nodeps jar OpenID4Java no dependencies UTF-8 6.0.2 ${test.data} ${basedir}/target/test-data ${basedir}/src ${basedir}/src **/*.properties **/*.xsd ${basedir}/test/src ${basedir}/test/src **/*.properties **/*.html org.apache.maven.plugins maven-compiler-plugin ${jvm.ver} ${jvm.ver} true true org.codehaus.mojo properties-maven-plugin 1.0-alpha-2 initialize read-project-properties project.properties cobertura-maven-plugin org.codehaus.mojo 2.0 clean org.apache.maven.plugins maven-antrun-plugin process-test-resources run org.apache.maven.plugins maven-surefire-plugin YADIS_TEST_DATA ${test.data.build} SERVLET_PORT ${test.servlet.port} TEST_DATA ${basedir}/test/src/org/openid4java/ ${basedir}/maven2/target/site/${project.artifactId}/ maven-project-info-reports-plugin maven-javadoc-plugin 128m 512m ${encoding} ${encoding} ${encoding} maven-jxr-plugin ${encoding} ${encoding} true apidocs org.codehaus.mojo taglist-maven-plugin TODO FIXME @todo @deprecated org.codehaus.mojo cobertura-maven-plugin 2.0 maven-surefire-report-plugin false report-only org.apache.maven.plugins maven-checkstyle-plugin 2.6 ${basedir}/openid4java_checks.xml org.codehaus.mojo findbugs-maven-plugin maven-pmd-plugin true ${encoding} 100 ${jvm.ver} pmd cpd org.codehaus.mojo rat-maven-plugin 1.0-alpha-3 commons-logging commons-logging 1.1.1 org.apache.httpcomponents httpclient provided net.sourceforge.nekohtml nekohtml provided org.openxri openxri-syntax provided org.openxri openxri-client provided com.google.code.guice guice 2.0 net.sf.ehcache ehcache 1.3.0 provided org.eclipse.higgins higgins-configuration-api provided org.eclipse.higgins higgins-sts-api provided org.eclipse.higgins higgins-sts-common provided org.eclipse.higgins higgins-sts-server-token-handler provided org.eclipse.higgins higgins-sts-spi provided xerces xercesImpl 2.8.1 provided xml-security xmlsec 1.3.0 provided org.apache.ws.commons.axiom axiom-api provided org.eclipse.higgins higgins-configuration-api provided org.eclipse.higgins higgins-sts-api provided org.eclipse.higgins higgins-sts-common provided org.eclipse.higgins higgins-sts-server-token-handler provided org.eclipse.higgins higgins-sts-spi provided org.springframework spring-jdbc provided javax.servlet servlet-api provided junit junit 3.8.2 test jdom jdom 1.0 test jetty jetty ${jetty.version} test jetty jetty-util ${jetty.version} test log4j log4j 1.2.14 test net.sourceforge.jwebunit jwebunit-htmlunit-plugin 1.4.1 test javax.servlet servlet-api nekohtml nekohtml scm:svn:http://openid4java.googlecode.com/svn/trunk/ scm:svn:https://openid4java.googlecode.com/svn/trunk/ HEAD http://openid4java.googlecode.com/svn/trunk/ guice http://guice-maven.googlecode.com/svn/trunk openid4java-0.9.6.662/maven2/0000755001501200150120000000000011627733442014765 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/repo-adds/0000755001501200150120000000000011627733442016643 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/repo-adds/higgins-sts-api-pom.xml0000644001501200150120000000142411034531521023147 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgings-parent SNAPSHOT org.eclipse.higgins higgins-sts-api SNAPSHOT jar org.apache.ws.commons.axiom axiom-api openid4java-0.9.6.662/maven2/repo-adds/higgins-sts-spi-pom.xml0000644001501200150120000000142611034531521023173 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgins-parent SNAPSHOT org.eclipse.higgins higgins-sts-spi SNAPSHOT jar org.apache.ws.commons.axiom axiom-api openid4java-0.9.6.662/maven2/repo-adds/higgins-parent-pom.xml0000644001501200150120000000162511034531521023063 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgins-parent pom SNAPSHOT http://www.eclipse.org/higgins/ higgins jar get from https://forgesvn1.novell.com/svn/bandit/trunk/solutions/ @ rev671, need by openid4java-infocard, and info get from http://wiki.eclipse.org/Components#Security_Token_Service org.apache.ws.commons.axiom axiom-api 1.2.2 openid4java-0.9.6.662/maven2/repo-adds/deploy.sh0000644001501200150120000000130711034531521020456 0ustar miguelmiguel#! /bin/sh # deployement with mvn deploy:deploy-file # !! require explicit groupId, artifactId, version and packaging in the pom.xml (doesn't support inherit from parent) !! LIB_DIR=../../lib/infocard/ REPO_ID=alchim.sf.net REPO_URL=scp://alchim.sf.net/home/groups/a/al/alchim/htdocs/download/snapshots DEPLOY_OPTS="-DrepositoryId=$REPO_ID -Durl=$REPO_URL -DuniqueVersion=false" mvn deploy:deploy-file -DpomFile=higgins-parent-pom.xml -Dfile=higgins-parent-pom.xml $DEPLOY_OPTS for LIB in higgins-configuration-api higgins-sts-api higgins-sts-common higgins-sts-server-token-handler higgins-sts-spi ; do echo $LIB mvn deploy:deploy-file -DpomFile=$LIB-pom.xml -Dfile=$LIB_DIR/$LIB.jar $DEPLOY_OPTS done openid4java-0.9.6.662/maven2/repo-adds/higgins-configuration-api-pom.xml0000644001501200150120000000105711034531521025207 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgins-parent SNAPSHOT org.eclipse.higgins higgins-configuration-api SNAPSHOT jar openid4java-0.9.6.662/maven2/repo-adds/higgins-sts-server-token-handler-pom.xml0000644001501200150120000000111611034531521026433 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgins-parent SNAPSHOT org.eclipse.higgins higgins-sts-server-token-handler SNAPSHOT jar openid4java-0.9.6.662/maven2/repo-adds/higgins-sts-common-pom.xml0000644001501200150120000000227511034531521023673 0ustar miguelmiguel 4.0.0 org.eclipse.higgins higgins-parent SNAPSHOT org.eclipse.higgins higgins-sts-common SNAPSHOT jar org.apache.ws.commons.axiom axiom-api stax stax-api 1.0.1 commons-logging commons-logging 1.1 xml-security xmlsec 1.3.0 openid4java-0.9.6.662/maven2/openid4java/0000755001501200150120000000000011627733442017171 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java/pom.xml0000644001501200150120000000272211551251741020502 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java pom OpenID4Java ../target/site/${artifactId}/ ${groupId} openid4java-consumer ${version} ${groupId} openid4java-server ${version} ${groupId} openid4java-server-JdbcServerAssociationStore ${version} ${groupId} openid4java-consumer-SampleConsumer ${version} ${groupId} openid4java-server-SampleServer ${version} openid4java-0.9.6.662/maven2/openid4java-server/0000755001501200150120000000000011627733442020475 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-server/pom.xml0000644001501200150120000000206511551251741022006 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-server pom OpenID4Java Server ../target/site/${project.artifactId}/ ${groupId} openid4java-nodeps ${version} net.sourceforge.nekohtml nekohtml org.apache.httpcomponents httpclient openid4java-0.9.6.662/maven2/openid4java-server-JdbcServerAssociationStore/0000755001501200150120000000000011627733442025736 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-server-JdbcServerAssociationStore/pom.xml0000644001501200150120000000266211551251741027252 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-server-JdbcServerAssociationStore pom OpenID4Java Server JdbcServerAssociationStore ../../src org.apache.maven.plugins maven-compiler-plugin org/openid4java/server/JdbcServerAssociationStore.java ../target/site/${project.artifactId}/ ${groupId} openid4java-server ${version} org.springframework spring-jdbc openid4java-0.9.6.662/maven2/openid4java-consumer/0000755001501200150120000000000011627733442021022 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-consumer/pom.xml0000644001501200150120000000206711551251741022335 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-consumer pom OpenID4Java Consumer ../target/site/${project.artifactId}/ ${groupId} openid4java-nodeps ${version} org.apache.httpcomponents httpclient net.sourceforge.nekohtml nekohtml openid4java-0.9.6.662/maven2/pom.xml0000644001501200150120000002715011551251741016300 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 pom .. openid4java openid4java-consumer openid4java-server openid4java-infocard openid4java-xri openid4java-full openid4java-consumer-JdbcConsumerAssociationStore openid4java-consumer-JdbcNonceVerifier openid4java-server-JdbcServerAssociationStore openid4java-consumer-SampleConsumer openid4java-server-SampleServer maven-assembly-plugin src bin jar-with-dependencies org.apache.maven.plugins maven-source-plugin attach-sources jar org.apache.maven.plugins maven-site-plugin 2.2 org.apache.maven.plugins maven-eclipse-plugin 2.8 true true OpenID4Java Parent OpenID4Java library offers support for OpenID-enabling a consumer site or implementing an OpenID Provider server. http://code.sxip.com/openid4java Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo Apache License 2.0 Sxip http://code.sxip.com/ dick.hardt dick.hardt http://code.google.com/u/dick.hardt/ owner dhuska dhuska http://code.google.com/u/dhuska/ owner tim.baur tim.baur http://code.google.com/u/tim.baur/ owner marius.scurtescu marius.scurtescu http://code.google.com/u/marius.scurtescu/ owner Johnny.Bufu Johnny.Bufu http://code.google.com/u/Johnny.Bufu/ owner rowan0 rowan0 http://code.google.com/u/rowan0/ owner zhoushuqun Sutra zhoushuqun@gmail.com http://code.google.com/u/zhoushuqun/ member +8 sappenin sappenin http://code.google.com/u/sappenin/ member gwachob gwachob http://code.google.com/u/gwachob/ member ibussed ibussed http://code.google.com/u/ibussed/ member justen.stepka justen.stepka http://code.google.com/u/justen.stepka/ member shihab shihab http://code.google.com/u/shihab/ member David Bernard Alchim31 http://alchim.sf.net/ maven deployment OpenID4Java openid4java@googlegroups.com openid4java-unsubscribe@googlegroups.com openid4java@googlegroups.com http://groups.google.com/group/openid4java Google Code Issue http://code.google.com/p/openid4java/issues/list scm:svn:http://openid4java.googlecode.com/svn/trunk/ http://fisheye2.cenqua.com/browse/openid4java/ alchim.snapshots Achim Repository Snapshots http://alchim.sf.net/download/snapshots org.openxri openxri-syntax 1.2.0 log4j log4j org.openxri openxri-client 1.2.0 log4j log4j log4j log4j 1.2.14 javax.servlet servlet-api 2.3 provided commons-codec commons-codec 1.3 org.apache.httpcomponents httpclient 4.0 org.springframework spring-jdbc 2.0.6 net.sourceforge.nekohtml nekohtml 1.9.10 xerces xercesImpl 2.8.1 xml-security xmlsec 1.3.0 org.apache.ws.commons.axiom axiom-api 1.2.5 org.eclipse.higgins higgins-configuration-api SNAPSHOT org.eclipse.higgins higgins-sts-api SNAPSHOT org.eclipse.higgins higgins-sts-common SNAPSHOT org.eclipse.higgins higgins-sts-server-token-handler SNAPSHOT org.eclipse.higgins higgins-sts-spi SNAPSHOT openid4java-staging OpenID4Java Staging Repository http://oss.sonatype.org/service/local/staging/deploy/maven2/ openid4java-snapshots OpenID4Java Snapshot Repository http://oss.sonatype.org/content/repositories/openid4java-snapshots/ alchim-deploy alchim.sf.net sourceforge scp://alchim.sf.net/home/groups/a/al/alchim/htdocs/download/releases alchim.sf.net sourceforge scp://alchim.sf.net/home/groups/a/al/alchim/htdocs/download/snapshots false alchim.sf.net sourceforge scp://alchim.sf.net/home/groups/a/al/alchim/htdocs/openid4java release org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign mvn3 org.apache.maven.plugins maven-site-plugin 3.0-beta-3 openid4java-0.9.6.662/maven2/openid4java-consumer-SampleConsumer/0000755001501200150120000000000011627733442023755 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-consumer-SampleConsumer/pom.xml0000644001501200150120000000260511551251741025266 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-consumer-SampleConsumer pom OpenID4Java Consumer SampleConsumer ../../src org.apache.maven.plugins maven-compiler-plugin org/openid4java/consumer/SampleConsumer.java ../target/site/${project.artifactId}/ ${groupId} openid4java-consumer ${version} javax.servlet servlet-api provided openid4java-0.9.6.662/maven2/openid4java-infocard/0000755001501200150120000000000011627733442020754 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-infocard/pom.xml0000644001501200150120000000356111551251741022267 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-infocard pom OpenID4Java Infocard ../target/site/${project.artifactId}/ ${groupId} openid4java-nodeps ${version} org.apache.ws.commons.axiom axiom-api commons-codec commons-codec org.springframework spring-jdbc org.eclipse.higgins higgins-configuration-api org.eclipse.higgins higgins-sts-api org.eclipse.higgins higgins-sts-common org.eclipse.higgins higgins-sts-server-token-handler org.eclipse.higgins higgins-sts-spi openid4java-0.9.6.662/maven2/openid4java-server-SampleServer/0000755001501200150120000000000011627733442023103 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-server-SampleServer/pom.xml0000644001501200150120000000256711551251741024423 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-server-SampleServer pom OpenID4Java Server SampleServer ../../src org.apache.maven.plugins maven-compiler-plugin org/openid4java/server/SampleServer.java ../target/site/${project.artifactId}/ ${groupId} openid4java-server ${version} javax.servlet servlet-api provided openid4java-0.9.6.662/maven2/openid4java-xri/0000755001501200150120000000000011627733442017771 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-xri/pom.xml0000644001501200150120000000203611551251741021300 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-xri pom OpenID4Java XRI ../target/site/${project.artifactId}/ ${groupId} openid4java-nodeps ${version} org.openxri openxri-syntax org.openxri openxri-client openid4java-0.9.6.662/maven2/openid4java-consumer-JdbcConsumerAssociationStore/0000755001501200150120000000000011627733442026610 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-consumer-JdbcConsumerAssociationStore/pom.xml0000644001501200150120000000176411551251741030126 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-consumer-JdbcConsumerAssociationStore pom OpenID4Java Consumer JdbcConsumerAssociationStore ../target/site/${project.artifactId}/ ${groupId} openid4java-consumer ${version} org.springframework spring-jdbc openid4java-0.9.6.662/maven2/openid4java-consumer-JdbcNonceVerifier/0000755001501200150120000000000011627733442024341 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-consumer-JdbcNonceVerifier/pom.xml0000644001501200150120000000173611551251741025656 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-consumer-JdbcNonceVerifier pom OpenID4Java Consumer JdbcNonceVerifier ../target/site/${project.artifactId}/ ${groupId} openid4java-consumer ${version} org.springframework spring-jdbc openid4java-0.9.6.662/maven2/openid4java-full/0000755001501200150120000000000011627733442020131 5ustar miguelmiguelopenid4java-0.9.6.662/maven2/openid4java-full/pom.xml0000644001501200150120000000315711551251741021445 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-parent 0.9.6 openid4java-full pom OpenID4Java Full ../target/site/${artifactId}/ ${groupId} openid4java ${version} ${groupId} openid4java-infocard ${version} ${groupId} openid4java-xri ${version} ${groupId} openid4java-server-JdbcServerAssociationStore ${version} ${groupId} openid4java-consumer-SampleConsumer ${version} ${groupId} openid4java-server-SampleServer ${version} openid4java-0.9.6.662/maven2/README.txt0000644001501200150120000000432211201116452016444 0ustar miguelmiguelOpenID4Java Maven2 Scripts OpenID4Java is using ant(http://ant.apache.org/) to build. The maven2(http://maven.apache.org/) scripts are the another choice for maven users. Sub projects: openid4java: Official OpenID4Java distribution. openid4java-consumer: OpenID consumer / Relying Party. openid4java-server: OpenID server / OpenID Provider. openid4java-infocard: OpenID4Java distribution with OpenID-Infocard support. openid4java-xri: OpenID4Java distribution with local XRI resolver support. openid4java-full: Complete OpenID4Java distribution with local XRI resolver and OpenID-Infocard support. openid4java-server-JdbcServerAssociationStore: An association store implementention with springframework(http://www.springframework.org/) jdbc. openid4java-consumer-SampleConsumer: Sample code of consumer / Relying Party. openid4java-server-SampleServer: Sample code of server / OpenID Provider. openid4java-nodeps Holds all java source of OpenID4Java, but without any dependencies. This a private project for openid4java itself to use. Build: $ mvn package Install to your local repository: $ mvn install As default, openid4java will be installed into ~/.m2/repository/org/openid4java/. Generate site documentation(contains javadoc etc): $ mvn site Generates site documentation in target/site/. Clean up: $ mvn clean Use it by adding following to your project's pom.xml in section dependencies: org.openid4java openid4java 0.9.3 You can use a sub project if you only need a part of it: org.openid4java openid4java-consumer 0.9.3 or org.openid4java openid4java-server 0.9.3 ... org.openid4java openid4java-infocard 0.9.3 openid4java-0.9.6.662/build.xml0000644001501200150120000002632611352263626015424 0ustar miguelmiguel Version: ${version}
OpenID4Java Library Copyright 2006-2008 Sxip Identity Corporation]]> set version to ${component.ver}
openid4java-0.9.6.662/CHANGELOG0000644001501200150120000000764711553421060015011 0ustar miguelmiguel.... OpenID4Java Library - CHANGELOG ======================================================================== This document highlights the major changes in the OpenID4Java library. Please see the TODO file for outstanding items. For the detailed logs please see the commit comments at: - http://code.google.com/p/openid4java 20110413: Notable changes since the previous release: HttpClient upgraded to 4.0. HttpClient is injectable, making Google AppEngine deployments possible. HttpCache supports configurable TTL. Attribute Exchange extension parameters are required to be signed. Java 1.5 for source and distributed bytecode. And a handful of bug fixes. 20090614: A number of related specifications have been finalized since the previous official release in November 2007, and are supported by OpenID4Java: * OpenID Authentication 2.0 * Attribute Exchange 1.0 * PAPE 1.0 * Java 1.5 binaries are now released; source still compilable with Java 1.4 Under the hood: * internal XRDS parsing to ensure correct identity data is discovered * discovery code has been revised to be more robust * discovery HTTP requests are transparently cached for increased performance * a minimal set of library dependencies are packaged with the official release * alternative packages are released with optional / extra functionality * proxy XRI resolver delegating to the service provided by XRI.net * local XRI resolver updated to use the latest openXRI 1.2.0 library * JDBC implementations for nonces and associations stores 20071113: - Renamed AuthSuccess.setSignExtension() to AuthSuccess.addSignExtension() to better reflect the operation performed. 20071025: - Documented Relying Party Discovery requirements; see INSTALL : Relying Party Discovery section 20070913: - Improved error reporting and message validation. 20070907: - Draft 12 compliant - Implemented identifier recycling - Implemented return URL validation against endpoints discovered from the RP's realm 20070905: - Updated to OpenID Attribute Exchange draft 7 20070821: - Added support for OpenID Information Cards 1.0, draft 1 - Added (OpenID-Infocard) DemoRP and InfocardOP sample/demo projects 20070626: - Implemented OpenID Provider Authentication Policy Extension 1.0, draft 1 http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html 20070530: - API change in SRegResponse: method public SRegResponse createFetchResponse(SRegRequest req, Map userData) throws MessageException replaced with factory method public static SRegResponse createSRegResponse(SRegRequest req, Map userData) throws MessageException 20070407: - Implemented OpenID Simple Registration 1.0 and 1.1 20070403: - Added deployable JSP-only Relying Party and OpenID Provider 20070321: - Added forward-proxy support for consumers. 20070304: - Added logging. 20070212: - Message.getDestinationUrl() replaces the following: AuthRequest.getRedirectUrl() AuthSuccess.getRedirectUrl() IndirectError.getReturnTo() 20070208: - supports OpenID Attribute Exchange draft 4 20070115: - supports OpenID Authentication 2.0 draft 11 20061203: First public release, version 0.9.1.x - supports OpenID Authentication 2.0, draft 10: http://openid.net/specs/openid-authentication-2_0-10.html - supports OpenID Attribute Exhcange 1.0, draft 3 - (few outstanding spec issues remain) ======================================================================== Copyright 2006-2008 Sxip Identity Corporation Project home page and package distribution: => http://code.google.com/p/openid4java => http://code.google.com/p/openid4java/downloads/ For support, please visit the wiki and join the Google Groups! => http://groups.google.com/group/openid4java/ => http://code.google.com/p/openid4java/w/ OpenID => http://openid.net/ Released under the Apache License 2.0 => see LICENSE openid4java-0.9.6.662/samples/0000755001501200150120000000000011627733442015241 5ustar miguelmiguelopenid4java-0.9.6.662/samples/formredirection/0000755001501200150120000000000011627733442020434 5ustar miguelmiguelopenid4java-0.9.6.662/samples/formredirection/formredirection.jsp0000644001501200150120000000142111205322263024326 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> OpenID HTML FORM Redirection
openid4java-0.9.6.662/samples/simple-openid/0000755001501200150120000000000011627733442020006 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/0000755001501200150120000000000011034531630020560 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/main/0000755001501200150120000000000011034531630021504 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/main/webapp/0000755001501200150120000000000011627733442022777 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/main/webapp/WEB-INF/0000755001501200150120000000000011627733442024026 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/main/webapp/WEB-INF/lib/0000755001501200150120000000000011140117010024545 5ustar miguelmiguelopenid4java-0.9.6.662/samples/simple-openid/src/main/webapp/WEB-INF/web.xml0000644001501200150120000000032711034531631025313 0ustar miguelmiguel Archetype Created Web Application openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/provider.jsp0000644001501200150120000001271111034531631025335 0ustar miguelmiguel<%@ page session="true" %><%@ page import="java.util.List, org.openid4java.message.AuthSuccess, org.openid4java.server.InMemoryServerAssociationStore, org.openid4java.message.DirectError,org.openid4java.message.Message,org.openid4java.message.ParameterList, org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.server.ServerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.VerificationResult" %><% // There must be NO newlines allowed at beginning or ending of this JSP // because the output of this jsp is passed directly // (during associate response) to client ParameterList object which barfs on // blank lines. // README: // Set the OPEndpointUrl to the absolute URL of this provider.jsp Object o = pageContext.getAttribute("servermanager", PageContext.APPLICATION_SCOPE); if (o == null) { ServerManager newmgr=new ServerManager(); newmgr.setSharedAssociations(new InMemoryServerAssociationStore()); newmgr.setPrivateAssociations(new InMemoryServerAssociationStore()); newmgr.setOPEndpointUrl(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/simple-openid/provider.jsp"); pageContext.setAttribute("servermanager", newmgr, PageContext.APPLICATION_SCOPE); // The attribute com.mycompany.name1 may not have a value or may have the value null } ServerManager manager=(ServerManager) pageContext.getAttribute("servermanager", PageContext.APPLICATION_SCOPE); ParameterList requestp; if ("complete".equals(request.getParameter("_action"))) // Completing the authz and authn process by redirecting here { requestp=(ParameterList) session.getAttribute("parameterlist"); // On a redirect from the OP authn & authz sequence } else { requestp = new ParameterList(request.getParameterMap()); } String mode = requestp.hasParameter("openid.mode") ? requestp.getParameterValue("openid.mode") : null; Message responsem; String responseText; if ("associate".equals(mode)) { // --- process an association request --- responsem = manager.associationResponse(requestp); responseText = responsem.keyValueFormEncoding(); } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) { // interact with the user and obtain data needed to continue //List userData = userInteraction(requestp); String userSelectedId = null; String userSelectedClaimedId = null; Boolean authenticatedAndApproved = Boolean.FALSE; if ((session.getAttribute("authenticatedAndApproved") == null) || (((Boolean)session.getAttribute("authenticatedAndApproved")) == Boolean.FALSE) ) { session.setAttribute("parameterlist", requestp); response.sendRedirect("provider_authorization.jsp"); } else { userSelectedId = (String) session.getAttribute("openid.claimed_id"); userSelectedClaimedId = (String) session.getAttribute("openid.identity"); authenticatedAndApproved = (Boolean) session.getAttribute("authenticatedAndApproved"); // Remove the parameterlist so this provider can accept requests from elsewhere session.removeAttribute("parameterlist"); session.setAttribute("authenticatedAndApproved", Boolean.FALSE); // Makes you authorize each and every time } // --- process an authentication request --- responsem = manager.authResponse(requestp, userSelectedId, userSelectedClaimedId, authenticatedAndApproved.booleanValue()); // caller will need to decide which of the following to use: // - GET HTTP-redirect to the return_to URL // - HTML FORM Redirection //responseText = response.wwwFormEncoding(); if (responsem instanceof AuthSuccess) { response.sendRedirect(((AuthSuccess) responsem).getDestinationUrl(true)); return; } else { responseText="
"+responsem.keyValueFormEncoding()+"
"; } } else if ("check_authentication".equals(mode)) { // --- processing a verification request --- responsem = manager.verify(requestp); responseText = responsem.keyValueFormEncoding(); } else { // --- error response --- responsem = DirectError.createDirectError("Unknown request"); responseText = responsem.keyValueFormEncoding(); } // make sure there are no empty lines at the end of this file: // they will end up in direct responses and thus compromise them %><%=responseText%>openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/consumer_returnurl.jsp0000644001501200150120000000521511034531631027461 0ustar miguelmiguel<%@ page session="true" %> <%@ page import="org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.consumer.ConsumerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.VerificationResult" %> <% ConsumerManager manager=(ConsumerManager) pageContext.getAttribute("consumermanager", PageContext.APPLICATION_SCOPE); try { // --- processing the authentication response // extract the parameters from the authentication response // (which comes in as a HTTP request from the OpenID provider) ParameterList responselist = new ParameterList(request.getParameterMap()); // retrieve the previously stored discovery information DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disco"); // 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; ConsumerManager needs to be the same // (static) instance used to place the authentication request VerificationResult verification = manager.verify( receivingURL.toString(), responselist, discovered); // examine the verification result and extract the verified identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse(); session.setAttribute("openid", authSuccess.getIdentity()); session.setAttribute("openid-claimed", authSuccess.getClaimed()); response.sendRedirect("."); // success } else { %> Failed to login! <% } } catch (OpenIDException e) { %> Login error! <% // present error to the user } %> openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/provider_authorization.jsp0000644001501200150120000000513711034531631030321 0ustar miguelmiguel<%@ page session="true" %> <%@ page import="java.util.List, org.openid4java.message.AuthSuccess, org.openid4java.server.InMemoryServerAssociationStore, org.openid4java.message.DirectError,org.openid4java.message.Message,org.openid4java.message.ParameterList, org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.server.ServerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.VerificationResult" %> <% // HOWTO: // the session var parameterlist contains openid authreq message parameters // this JSP should set the session attribute var "authenticatedAndApproved" and // redirect to provider.jsp?_action=complete ParameterList requestp=(ParameterList) session.getAttribute("parameterlist"); String openidrealm=requestp.hasParameter("openid.realm") ? requestp.getParameterValue("openid.realm") : null; String openidreturnto=requestp.hasParameter("openid.return_to") ? requestp.getParameterValue("openid.return_to") : null; String openidclaimedid=requestp.hasParameter("openid.claimed_id") ? requestp.getParameterValue("openid.claimed_id") : null; String openididentity=requestp.hasParameter("openid.identity") ? requestp.getParameterValue("openid.identity") : null; %>

Provider Authentication and Authorization

Right now, this doesn't provide a fancy interface - authenticate the user (not done, do whatever authn you want), do some presentation about whats being asked of the user, and then go back to the provider.jsp.

This JSP just asks you to click a link without authentication.

<% if (request.getParameter("action") == null) { String site=(String) (openidrealm == null ? openidreturnto : openidrealm); %> ClaimedID:

<%= openidclaimedid%>

Identity:
<%= openididentity %> 

Site:
 <%= site %>

Click To become logged in and authorize <% } else // Logged in { session.setAttribute("authenticatedAndApproved", Boolean.TRUE); // No need to change openid.* session vars response.sendRedirect("provider.jsp?_action=complete"); } %> openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/index.jsp0000644001501200150120000000105511034531631024611 0ustar miguelmiguel<%@ page session="true" %> <% if (request.getParameter("logout")!=null) { session.removeAttribute("openid"); session.removeAttribute("openid-claimed"); %> Logged out!

<% } if (session.getAttribute("openid")==null) { %>

OpenID:
<% } else { %> Logged in as <%= session.getAttribute("openid") %>

Log out <% } %> openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/consumer_redirect.jsp0000644001501200150120000001126011225246147027224 0ustar miguelmiguel<%@ page session="true" %> <%@ page import="java.util.Map,java.util.Iterator,org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.consumer.ConsumerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.InMemoryNonceVerifier" %> <% // README: // Set the returnToUrl string to the appropriate value for this JSP // Since you may be deployed behind apache, etc, the jsp has no real idea what the // absolute URI is to get back here. Object o = pageContext.getAttribute("consumermanager", PageContext.APPLICATION_SCOPE); if (o == null) { ConsumerManager newmgr=new ConsumerManager(); newmgr.setAssociations(new InMemoryConsumerAssociationStore()); newmgr.setNonceVerifier(new InMemoryNonceVerifier(5000)); pageContext.setAttribute("consumermanager", newmgr, PageContext.APPLICATION_SCOPE); } ConsumerManager manager=(ConsumerManager) pageContext.getAttribute("consumermanager", PageContext.APPLICATION_SCOPE); String openid=request.getParameter("openid"); try { // determine a return_to URL where your application will receive // the authentication responses from the OpenID provider // YOU SHOULD CHANGE THIS TO GO TO THE String returnToUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/simple-openid/consumer_returnurl.jsp"; // perform discovery on the user-supplied identifier List discoveries = manager.discover(openid); // attempt to associate with an OpenID provider // and retrieve one service endpoint for authentication DiscoveryInformation discovered = manager.associate(discoveries); // store the discovery information in the user's session session.setAttribute("openid-disco", 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 response.sendRedirect(authReq.getDestinationUrl(true)); } else { // Option 2: HTML FORM Redirection // Allows payloads > 2048 bytes //

// see samples/formredirection.jsp for a JSP example //authReq.getOPEndpoint(); // build a HTML FORM with the message parameters //authReq.getParameterMap(); %> OpenID HTML FORM Redirection <% Map pm=authReq.getParameterMap(); Iterator keyit=pm.keySet().iterator(); Object key; Object value; while (keyit.hasNext()) { key=keyit.next(); value=pm.get(key); %> <% } %>
<% } } catch (OpenIDException e) { // present error to the user response.sendError(500); } %> openid4java-0.9.6.662/samples/simple-openid/src/main/webapp/user.jsp0000644001501200150120000000072211034531631024460 0ustar miguelmiguel<%@ page contentType="application/xrds+xml"%> http://openid.net/signon/1.0 <%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()%>/simple-openid/provider.jsp openid4java-0.9.6.662/samples/simple-openid/log4j.properties0000644001501200150120000000055211034531631023131 0ustar miguelmiguellog4j.rootLogger = INFO, stdout log4j.logger.org.openid4java=DEBUG log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Threshold = DEBUG log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{ABSOLUTE} [%C : %F : %L] : %m%n openid4java-0.9.6.662/samples/simple-openid/pom.xml0000644001501200150120000000420711551252217021316 0ustar miguelmiguel org.openid4java openid4java-samples 0.9.6 ../pom.xml 4.0.0 simple-openid war Simple Openid4Java Consumer and Provider http://maven.apache.org javax.servlet jstl 1.1.2 junit junit 3.8.1 test commons-httpclient commons-httpclient 3.0.1 junit junit org.openid4java openid4java ${version} simple-openid org.mortbay.jetty maven-jetty-plugin 6.0.2 10 java.endorsed.dirs ${basedir}/target/simple-openid/WEB-INF/lib/ org.apache.commons.logging.Log org.apache.commons.logging.impl.SimpleLog openid4java-0.9.6.662/samples/simple-openid/README.txt0000644001501200150120000000451711034531631021477 0ustar miguelmiguel ************ INTRODUCTION ************ This is a demo consumer and provider using only JSPs. It uses only in-memory stores for nonces and associations, and the provider does no user authentication, though it should be obvious in provider.jsp how to do user authentication using standard web authentication methods. This demo *requires* apache Maven2 to build. The index.jsp and consumer_*.jsp files comprise the consumer. The provider_*.jsp files comprise the provider. The user.jsp produces a XRDS file which points to the provider. There are hardcoded URLs in each of the JSP files - a README at the top indicates what you need to change to deploy this to other than http://localhost:8080/simple-openid There are no dependencies between consumer and provider. To install these JSPs in another project/jsp container, you should make sure to see the pom.xml file which documents dependencies, and note the xalan files which must go in an endorsed libs directory (xercesImpl*.jar and xml-apis*.jar) The mvn war:war task should create a war file which can be deployed by copying the war file - but this does not deploy the above mentioned jars into an endorsed lib directory (such as $CATALINA_HOME/common/endorsed) **************** RUNNING THE DEMO **************** To run this as a demo, install the maven2 tool and run the following command in the simple-openid directory: mvn jetty:run DEMO CONSUMER ------------- Visit the demo consumer at: http://localhost:8080/simple-openid You can use an IName, or any HTTP URL which acts as an openid. DEMO PROVIDER ------------- To visit the demo provider, visit the consumer at: http://localhost:8080/simple-openid And login with the following URL: http://localhost:8080/simple-openid/user.jsp You'll be prompted to approve the OP request (no authenticatinon) ******* LOGGING ******* You can tweak the incldued log4j.properties file and instruct maven to run the demo with various levels of logging. Example: mvn -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger -Dlog4j.configuration=file:log4j.properties jetty:run **** TODO **** Lots. Error handling is almost nonexistent. Authentication of the user is an excercise left to the reader. There are probably better ways to manage the ConsumerManager and ServerManager objects. In general, the JSPs are rather brittle. openid4java-0.9.6.662/samples/pom.xml0000644001501200150120000000200611551252230016537 0ustar miguelmiguel 4.0.0 org.openid4java openid4java-samples pom 0.9.6 OpenID4Java Samples simple-openid consumer-servlet org.apache.maven.plugins maven-idea-plugin true true true false openid4java-0.9.6.662/samples/appengine-consumer/0000755001501200150120000000000011627733442021040 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/0000755001501200150120000000000011352263622021620 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/0000755001501200150120000000000011352263622022544 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/0000755001501200150120000000000011352263622023465 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/0000755001501200150120000000000011352263622024254 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/0000755001501200150120000000000011352263622026460 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/appengine/0000755001501200150120000000000011627733442030435 5ustar miguelmiguel././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/appengine/AppEngineGuiceModule.javaopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/appengine/AppEngineGu0000644001501200150120000000237211352263622032517 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.appengine; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import org.openid4java.util.HttpFetcher; public class AppEngineGuiceModule extends AbstractModule { @Override protected void configure() { bind(HttpFetcher.class).to(AppEngineHttpFetcher.class).in(Scopes.SINGLETON); } @Provides @Singleton public URLFetchService providerUrlFetchService() { return URLFetchServiceFactory.getURLFetchService(); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/appengine/AppEngineHttpFetcher.javaopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/appengine/AppEngineHt0000644001501200150120000002062511352263622032520 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.appengine; import com.google.appengine.api.urlfetch.FetchOptions; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.ResponseTooLargeException; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.common.base.Joiner; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.openid4java.util.AbstractHttpFetcher; import org.openid4java.util.HttpRequestOptions; import org.openid4java.util.HttpResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletResponse; /** * Implementation of HttpFetcher for AppEngine. */ @Singleton public class AppEngineHttpFetcher extends AbstractHttpFetcher { private final URLFetchService fetchService; @Inject public AppEngineHttpFetcher(URLFetchService fetchService) { this.fetchService = fetchService; } @Override public HttpResponse get(String url, HttpRequestOptions requestOptions) throws IOException { return fetch(url, requestOptions, HTTPMethod.GET, null); } @Override public HttpResponse head(String url, HttpRequestOptions requestOptions) throws IOException { return fetch(url, requestOptions, HTTPMethod.HEAD, null); } @Override public HttpResponse post(String url, Map parameters, HttpRequestOptions requestOptions) throws IOException { return fetch(url, requestOptions, HTTPMethod.POST, encodeParameters(parameters )); } private String encodeParameters(Map params) { Map escapedParams = Maps.newHashMap(); for (Entry entry : params.entrySet()) { try { escapedParams.put(URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { // this should not happen throw new RuntimeException("platform does not support UTF-8", e); } } return Joiner.on("&").withKeyValueSeparator("=").join(escapedParams); } private HttpResponse fetch(String url, HttpRequestOptions requestOptions, HTTPMethod method, String content) throws IOException { final FetchOptions options = getFetchOptions(requestOptions); String currentUrl = url; for (int i = 0; i <= requestOptions.getMaxRedirects(); i++) { HTTPRequest httpRequest = new HTTPRequest(new URL(currentUrl), method, options); addHeaders(httpRequest, requestOptions); if (method == HTTPMethod.POST && content != null) { httpRequest.setPayload(content.getBytes()); } HTTPResponse httpResponse; try { httpResponse = fetchService.fetch(httpRequest); } catch (ResponseTooLargeException e) { return new TooLargeResponse(currentUrl); } if (!isRedirect(httpResponse.getResponseCode())) { boolean isResponseTooLarge = (getContentLength(httpResponse) > requestOptions.getMaxBodySize()); return new AppEngineFetchResponse(httpResponse, isResponseTooLarge, currentUrl); } else { currentUrl = getResponseHeader(httpResponse, "Location").getValue(); } } throw new IOException("exceeded maximum number of redirects"); } private static int getContentLength(HTTPResponse httpResponse) { byte[] content = httpResponse.getContent(); if (content == null) { return 0; } else { return content.length; } } private static void addHeaders(HTTPRequest httpRequest, HttpRequestOptions requestOptions) { String contentType = requestOptions.getContentType(); if (contentType != null) { httpRequest.addHeader(new HTTPHeader("Content-Type", contentType)); } Map headers = getRequestHeaders(requestOptions); if (headers != null) { for (Map.Entry header : headers.entrySet()) { httpRequest.addHeader(new HTTPHeader(header.getKey(), header.getValue())); } } } @SuppressWarnings("unchecked") private static Map getRequestHeaders( HttpRequestOptions requestOptions) { return requestOptions.getRequestHeaders(); } private static Header getResponseHeader(HTTPResponse httpResponse, String headerName) { Header[] allHeaders = getResponseHeaders(httpResponse, headerName); if (allHeaders.length == 0) { return null; } else { return allHeaders[0]; } } private static Header[] getResponseHeaders(HTTPResponse httpResponse, String headerName) { List allHeaders = httpResponse.getHeaders(); List
matchingHeaders = new ArrayList
(); for (HTTPHeader header : allHeaders) { if (header.getName().equalsIgnoreCase(headerName)) { matchingHeaders.add(new BasicHeader(header.getName(), header.getValue())); } } return matchingHeaders.toArray(new Header[matchingHeaders.size()]); } private static boolean isRedirect(int responseCode) { switch (responseCode) { case HttpServletResponse.SC_MOVED_PERMANENTLY: case HttpServletResponse.SC_MOVED_TEMPORARILY: case HttpServletResponse.SC_SEE_OTHER: case HttpServletResponse.SC_TEMPORARY_REDIRECT: return true; default: return false; } } private FetchOptions getFetchOptions(HttpRequestOptions requestOptions) { return FetchOptions.Builder.disallowTruncate() .doNotFollowRedirects() .setDeadline(requestOptions.getConnTimeout() / 1000.0); } private static class AppEngineFetchResponse implements HttpResponse { private final com.google.appengine.api.urlfetch.HTTPResponse httpResponse; private final boolean bodySizeExceeded; private String finalUri; public AppEngineFetchResponse( com.google.appengine.api.urlfetch.HTTPResponse httpResponse, boolean bodySizeExceeded, String finalUri) { this.httpResponse = httpResponse; this.bodySizeExceeded = bodySizeExceeded; this.finalUri = finalUri; } public String getBody() { byte[] content = httpResponse.getContent(); return (content == null || content.length == 0) ? null : new String(content); } public String getFinalUri() { return finalUri; } public Header getResponseHeader(String headerName) { return AppEngineHttpFetcher.getResponseHeader(httpResponse, headerName); } public Header[] getResponseHeaders(String headerName) { return AppEngineHttpFetcher.getResponseHeaders(httpResponse, headerName); } public boolean isBodySizeExceeded() { return bodySizeExceeded; } public int getStatusCode() { return httpResponse.getResponseCode(); } } private static class TooLargeResponse implements HttpResponse { private String finalUri; public TooLargeResponse(String finalUri) { this.finalUri = finalUri; } public String getBody() { throw new ResponseTooLargeException(finalUri); } public String getFinalUri() { return finalUri; } public Header getResponseHeader(String headerName) { throw new ResponseTooLargeException(finalUri); } public Header[] getResponseHeaders(String headerName) { throw new ResponseTooLargeException(finalUri); } public boolean isBodySizeExceeded() { return true; } public int getStatusCode() { throw new ResponseTooLargeException(finalUri); } } } openid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/0000755001501200150120000000000011352263622030124 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/servlet/0000755001501200150120000000000011627733442031617 5ustar miguelmiguel././@LongLink0000000000000000000000000000020300000000000011560 Lustar rootrootopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/servlet/PrepareRequestAttributesFilter.javaopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/servlet/Prepa0000644001501200150120000000170611352263622032606 0ustar miguelmiguelpackage org.openid4java.samples.servlet; import com.google.inject.Inject; import com.google.inject.Singleton; import org.openid4java.consumer.ConsumerManager; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; @Singleton public class PrepareRequestAttributesFilter implements Filter { private final ConsumerManager consumerManager; @Inject public PrepareRequestAttributesFilter(ConsumerManager consumerManager) { this.consumerManager = consumerManager; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { req.setAttribute("consumermanager", consumerManager); chain.doFilter(req, resp); } public void init(FilterConfig config) { } public void destroy() { } } ././@LongLink0000000000000000000000000000017300000000000011566 Lustar rootrootopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/servlet/ServletContextListener.javaopenid4java-0.9.6.662/samples/appengine-consumer/src/main/java/org/openid4java/samples/servlet/Servl0000644001501200150120000000265711352263622032640 0ustar miguelmiguel/** * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openid4java.samples.servlet; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import org.openid4java.appengine.AppEngineGuiceModule; import javax.servlet.ServletContextEvent; public class ServletContextListener extends GuiceServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { super.contextInitialized(servletContextEvent); } @Override protected Injector getInjector() { return Guice.createInjector( new ServletModule() { @Override protected void configureServlets() { filter("/*").through(PrepareRequestAttributesFilter.class); } }, new AppEngineGuiceModule()); } } openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/0000755001501200150120000000000011627733442024031 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/WEB-INF/0000755001501200150120000000000011627733442025060 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/WEB-INF/logging.properties0000644001501200150120000000173311352263625030624 0ustar miguelmiguel# A default java.util.logging configuration. # (All App Engine logging is through java.util.logging by default). # # To use this configuration, copy it into your application's WEB-INF # folder and add the following to your appengine-web.xml: # # # # # # Set the default logging level for all loggers to WARNING .level = WARNING # Set the default logging level for ORM, specifically, to WARNING DataNucleus.JDO.level=WARNING DataNucleus.Persistence.level=WARNING DataNucleus.Cache.level=WARNING DataNucleus.MetaData.level=WARNING DataNucleus.General.level=WARNING DataNucleus.Utility.level=WARNING DataNucleus.Transaction.level=WARNING DataNucleus.Datastore.level=WARNING DataNucleus.ClassLoading.level=WARNING DataNucleus.Plugin.level=WARNING DataNucleus.ValueGeneration.level=WARNING DataNucleus.Enhancer.level=WARNING DataNucleus.SchemaTool.level=WARNING openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/WEB-INF/lib/0000755001501200150120000000000011627733442025626 5ustar miguelmiguelopenid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/WEB-INF/appengine-web.xml0000644001501200150120000000131711352263625030321 0ustar miguelmiguel openid4java 1 true openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/WEB-INF/web.xml0000644001501200150120000000111711352263625026353 0ustar miguelmiguel Archetype Created Web Application guiceFilter com.google.inject.servlet.GuiceFilter guiceFilter /* org.openid4java.samples.servlet.ServletContextListener openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/consumer_returnurl.jsp0000644001501200150120000000515211352263625030523 0ustar miguelmiguel<%@ page session="true" %> <%@ page import="org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.consumer.ConsumerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.VerificationResult" %> <% ConsumerManager manager=(ConsumerManager) request.getAttribute("consumermanager"); try { // --- processing the authentication response // extract the parameters from the authentication response // (which comes in as a HTTP request from the OpenID provider) ParameterList responselist = new ParameterList(request.getParameterMap()); // retrieve the previously stored discovery information DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disco"); // 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; ConsumerManager needs to be the same // (static) instance used to place the authentication request VerificationResult verification = manager.verify( receivingURL.toString(), responselist, discovered); // examine the verification result and extract the verified identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse(); session.setAttribute("openid", authSuccess.getIdentity()); session.setAttribute("openid-claimed", authSuccess.getClaimed()); response.sendRedirect("."); // success } else { %> Failed to login! <% } } catch (OpenIDException e) { %> Login error! <% // present error to the user } %> openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/index.jsp0000644001501200150120000000105511352263625025653 0ustar miguelmiguel<%@ page session="true" %> <% if (request.getParameter("logout")!=null) { session.removeAttribute("openid"); session.removeAttribute("openid-claimed"); %> Logged out!

<% } if (session.getAttribute("openid")==null) { %>

OpenID:
<% } else { %> Logged in as <%= session.getAttribute("openid") %>

Log out <% } %> openid4java-0.9.6.662/samples/appengine-consumer/src/main/webapp/consumer_redirect.jsp0000644001501200150120000001077311352263625030267 0ustar miguelmiguel<%@ page session="true" %> <%@ page import="java.util.Map,java.util.Iterator,org.openid4java.discovery.Identifier, org.openid4java.discovery.DiscoveryInformation, org.openid4java.message.ax.FetchRequest, org.openid4java.message.ax.FetchResponse, org.openid4java.message.ax.AxMessage, org.openid4java.message.*, org.openid4java.OpenIDException, java.util.List, java.io.IOException, javax.servlet.http.HttpSession, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.openid4java.consumer.ConsumerManager, org.openid4java.consumer.InMemoryConsumerAssociationStore, org.openid4java.consumer.InMemoryNonceVerifier, org.openid4java.discovery.DiscoveryException" %> <% // README: // Set the returnToUrl string to the appropriate value for this JSP // Since you may be deployed behind apache, etc, the jsp has no real idea what the // absolute URI is to get back here. ConsumerManager manager=(ConsumerManager) request.getAttribute("consumermanager"); String openid=request.getParameter("openid"); try { // determine a return_to URL where your application will receive // the authentication responses from the OpenID provider // YOU SHOULD CHANGE THIS TO GO TO THE String port = (request.getServerPort() == 80) ? "" : (":" + request.getServerPort()); String returnToUrl = request.getScheme() + "://" + request.getServerName() + port + "/consumer_returnurl.jsp"; // perform discovery on the user-supplied identifier List discoveries = null; try { discoveries = manager.discover(openid); } catch (DiscoveryException e) { throw new ServletException(e); } // attempt to associate with an OpenID provider // and retrieve one service endpoint for authentication DiscoveryInformation discovered = manager.associate(discoveries); // store the discovery information in the user's session session.setAttribute("openid-disco", 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 response.sendRedirect(authReq.getDestinationUrl(true)); } else { // Option 2: HTML FORM Redirection // Allows payloads > 2048 bytes //

// see samples/formredirection.jsp for a JSP example //authReq.getOPEndpoint(); // build a HTML FORM with the message parameters //authReq.getParameterMap(); %> OpenID HTML FORM Redirection <% Map pm=authReq.getParameterMap(); Iterator keyit=pm.keySet().iterator(); Object key; Object value; while (keyit.hasNext()) { key=keyit.next(); value=pm.get(key); %> <% } %>
<% } } catch (OpenIDException e) { // present error to the user response.sendError(500); } %> openid4java-0.9.6.662/samples/appengine-consumer/pom.xml0000644001501200150120000000400211551252161022337 0ustar miguelmiguel org.openid4java openid4java-samples 0.9.6 ../pom.xml 4.0.0 appengine-consumer war Example for Google AppEngine-based Consumer http://maven.apache.org javax.servlet jstl 1.1.2 junit junit 3.8.1 test com.google.appengine appengine.api 1.2.5 system ${basedir}/src/main/webapp/WEB-INF/lib/appengine-api-1.0-sdk-1.2.5.jar com.google.code.guice guice-servlet 2.0 com.google.collections google-collections 1.0-rc4 appengine-consumer org.apache.maven.plugins maven-compiler-plugin 1.5 1.5 guice http://guice-maven.googlecode.com/svn/trunk openid4java-0.9.6.662/samples/appengine-consumer/README0000644001501200150120000000133011352263625021711 0ustar miguelmiguel This directory contains a simple example for how to run an openid4java-based OpenID Relying Party on Google AppEngine. First, create the WAR directory: $ mvn package Now, test the server locally: $ $PATH_TO_APPENGINE/dev_appserver.sh -a -p 8080 \ target/appengine-consumer Point your browser to http://:8080 to test. Finally, to deploy on AppEngine, you have to first claim an application name for yourself, and then edit the configuration file src/main/webapp/WEB-INF/appengine-web.xml. Change the name of the application from "openid4java" to the name you own. Then, rebuild and upload the application: $ mvn package $ $PATH_TO_APPENGINE/appcfg.sh update target/appengine-consumer openid4java-0.9.6.662/samples/consumer-servlet/0000755001501200150120000000000011627733442020556 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/0000755001501200150120000000000011034531766021342 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/0000755001501200150120000000000011034531766022266 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/0000755001501200150120000000000011034531766023207 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/0000755001501200150120000000000011034531766023776 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/0000755001501200150120000000000011034531766026202 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/samples/0000755001501200150120000000000011034531766027646 5ustar miguelmiguel././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/samples/consumerservlet/openid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/samples/consumerservlet0000755001501200150120000000000011627733442033032 5ustar miguelmiguel././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/samples/consumerservlet/ConsumerServlet.javaopenid4java-0.9.6.662/samples/consumer-servlet/src/main/java/org/openid4java/samples/consumerservlet0000644001501200150120000003022711504002570033021 0ustar miguelmiguel/** * Created on 2007-4-14 00:54:50 */ package org.openid4java.samples.consumerservlet; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; 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.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import org.openid4java.association.AssociationSessionType; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.InMemoryConsumerAssociationStore; import org.openid4java.consumer.InMemoryNonceVerifier; 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.MessageException; import org.openid4java.message.MessageExtension; import org.openid4java.message.ParameterList; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchRequest; import org.openid4java.message.ax.FetchResponse; import org.openid4java.message.sreg.SRegMessage; import org.openid4java.message.sreg.SRegRequest; import org.openid4java.message.sreg.SRegResponse; import org.openid4java.util.HttpClientFactory; import org.openid4java.util.ProxyProperties; /** * @author Sutra Zhou */ public class ConsumerServlet extends javax.servlet.http.HttpServlet { /** * */ private static final long serialVersionUID = -5998885243419513055L; private static final String OPTIONAL_VALUE = "0"; private static final String REQUIRED_VALUE = "1"; private static final Log LOG = LogFactory.getLog(ConsumerServlet.class); private ServletContext context; private ConsumerManager manager; /** * {@inheritDoc} */ public void init(ServletConfig config) throws ServletException { super.init(config); context = config.getServletContext(); LOG.debug("context: " + context); // --- Forward proxy setup (only if needed) --- ProxyProperties proxyProps = getProxyProperties(config); if (proxyProps != null) { LOG.debug("ProxyProperties: " + proxyProps); HttpClientFactory.setProxyProperties(proxyProps); } this.manager = new ConsumerManager(); manager.setAssociations(new InMemoryConsumerAssociationStore()); manager.setNonceVerifier(new InMemoryNonceVerifier(5000)); manager.setMinAssocSessEnc(AssociationSessionType.DH_SHA256); } /** * {@inheritDoc} */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } /** * {@inheritDoc} */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if ("true".equals(req.getParameter("is_return"))) { processReturn(req, resp); } else { String identifier = req.getParameter("openid_identifier"); if (identifier != null) { this.authRequest(identifier, req, resp); } else { this.getServletContext().getRequestDispatcher("/index.jsp") .forward(req, resp); } } } private void processReturn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Identifier identifier = this.verifyResponse(req); LOG.debug("identifier: " + identifier); if (identifier == null) { this.getServletContext().getRequestDispatcher("/index.jsp") .forward(req, resp); } else { req.setAttribute("identifier", identifier.getIdentifier()); this.getServletContext().getRequestDispatcher("/return.jsp") .forward(req, resp); } } // --- placing the authentication request --- public String authRequest(String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException, ServletException { try { // configure the return_to URL where your application will receive // the authentication responses from the OpenID provider // String returnToUrl = "http://example.com/openid"; String returnToUrl = httpReq.getRequestURL().toString() + "?is_return=true"; // 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); // Simple registration example addSimpleRegistrationToAuthRequest(httpReq, authReq); // Attribute exchange example addAttributeExchangeToAuthRequest(httpReq, authReq); 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("prameterMap", httpReq.getParameterMap()); httpReq.setAttribute("message", authReq); // httpReq.setAttribute("destinationUrl", httpResp // .getDestinationUrl(false)); dispatcher.forward(httpReq, httpResp); } } catch (OpenIDException e) { // present error to the user throw new ServletException(e); } return null; } /** * Simple Registration Extension example. * * @param httpReq * @param authReq * @throws MessageException * @see Simple Registration HowTo * @see OpenID Simple Registration Extension 1.0 */ private void addSimpleRegistrationToAuthRequest(HttpServletRequest httpReq, AuthRequest authReq) throws MessageException { // Attribute Exchange example: fetching the 'email' attribute // FetchRequest fetch = FetchRequest.createFetchRequest(); SRegRequest sregReq = SRegRequest.createFetchRequest(); String[] attributes = { "nickname", "email", "fullname", "dob", "gender", "postcode", "country", "language", "timezone" }; for (int i = 0, l = attributes.length; i < l; i++) { String attribute = attributes[i]; String value = httpReq.getParameter(attribute); if (OPTIONAL_VALUE.equals(value)) { sregReq.addAttribute(attribute, false); } else if (REQUIRED_VALUE.equals(value)) { sregReq.addAttribute(attribute, true); } } // attach the extension to the authentication request if (!sregReq.getAttributes().isEmpty()) { authReq.addExtension(sregReq); } } /** * Attribute exchange example. * * @param httpReq * @param authReq * @throws MessageException * @see Attribute Exchange HowTo * @see OpenID Attribute Exchange 1.0 - Final */ private void addAttributeExchangeToAuthRequest(HttpServletRequest httpReq, AuthRequest authReq) throws MessageException { String[] aliases = httpReq.getParameterValues("alias"); String[] typeUris = httpReq.getParameterValues("typeUri"); String[] counts = httpReq.getParameterValues("count"); FetchRequest fetch = FetchRequest.createFetchRequest(); for (int i = 0, l = typeUris == null ? 0 : typeUris.length; i < l; i++) { String typeUri = typeUris[i]; if (StringUtils.isNotBlank(typeUri)) { String alias = aliases[i]; boolean required = httpReq.getParameter("required" + i) != null; int count = NumberUtils.toInt(counts[i], 1); fetch.addAttribute(alias, typeUri, required, count); } } authReq.addExtension(fetch); } // --- processing the authentication response --- public Identifier verifyResponse(HttpServletRequest httpReq) throws ServletException { 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(); receiveSimpleRegistration(httpReq, authSuccess); receiveAttributeExchange(httpReq, authSuccess); return verified; // success } } catch (OpenIDException e) { // present error to the user throw new ServletException(e); } return null; } /** * @param httpReq * @param authSuccess * @throws MessageException */ private void receiveSimpleRegistration(HttpServletRequest httpReq, AuthSuccess authSuccess) throws MessageException { if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) { MessageExtension ext = authSuccess .getExtension(SRegMessage.OPENID_NS_SREG); if (ext instanceof SRegResponse) { SRegResponse sregResp = (SRegResponse) ext; for (Iterator iter = sregResp.getAttributeNames() .iterator(); iter.hasNext();) { String name = (String) iter.next(); String value = sregResp.getParameterValue(name); httpReq.setAttribute(name, value); } } } } /** * @param httpReq * @param authSuccess * @throws MessageException */ private void receiveAttributeExchange(HttpServletRequest httpReq, AuthSuccess authSuccess) throws MessageException { 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); List aliases = fetchResp.getAttributeAliases(); Map attributes = new LinkedHashMap(); for (Iterator iter = aliases.iterator(); iter.hasNext();) { String alias = (String) iter.next(); List values = fetchResp.getAttributeValues(alias); if (values.size() > 0) { String[] arr = new String[values.size()]; values.toArray(arr); attributes.put(alias, StringUtils.join(arr)); } } httpReq.setAttribute("attributes", attributes); } } /** * Get proxy properties from the context init params. * * @return proxy properties */ private static ProxyProperties getProxyProperties(ServletConfig config) { ProxyProperties proxyProps; String host = config.getInitParameter("proxy.host"); LOG.debug("proxy.host: " + host); if (host == null) { proxyProps = null; } else { proxyProps = new ProxyProperties(); String port = config.getInitParameter("proxy.port"); String username = config.getInitParameter("proxy.username"); String password = config.getInitParameter("proxy.password"); String domain = config.getInitParameter("proxy.domain"); proxyProps.setProxyHostName(host); proxyProps.setProxyPort(Integer.parseInt(port)); proxyProps.setUserName(username); proxyProps.setPassword(password); proxyProps.setDomain(domain); } return proxyProps; } } openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/0000755001501200150120000000000011627733442023547 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/WEB-INF/0000755001501200150120000000000011627733442024576 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/WEB-INF/web.xml0000644001501200150120000000234411231247703026067 0ustar miguelmiguel Consumer Servlet Web Application Consumer Servlet org.openid4java.samples.consumerservlet.ConsumerServlet Consumer Servlet /consumer openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/return.jsp0000644001501200150120000000370311504002570025570 0ustar miguelmiguel <%@page contentType="text/html; charset=UTF-8" import="java.util.Map" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> Hello World!
Login Success! - Logout
Your OpenID
Simple Registration
Nickname: ${nickname}
Email: ${email}
Fullname: ${fullname}
Date of birth: ${dob}
Gender: ${gender}
Postcode: ${postcode}
Country: ${country}
Language: ${language}
Timezone: ${timezone}
Attribute Exchange
${attribute.key}: ${attribute.value}
queryString
openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/consumer-servlet.css0000644001501200150120000000074011504002570027560 0ustar miguelmiguelinput[name="openid_identifier"] { width: 80%; background: url(http://openid.net.cn/login-bg.gif) no-repeat; background-position: 0 50%; padding-left: 18px; } textarea[name="queryString"] { width: 100%; height: 200px; } div#ax table tfoot td,div#ax table tbody td input[name="count"],div#sreg th,div#sreg-result th,div#ax-result th { text-align: right; } div#ax th { text-align: center; } input[name="typeUri"] { width: 300px; } input[name="count"] { width: 50px; }openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/index.jsp0000644001501200150120000001122611504002570025357 0ustar miguelmiguel <%@ page contentType="text/html; charset=UTF-8" import="java.util.Map,java.util.LinkedHashMap" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> Hello World!
Sample 1:
Sample 2: using the Simple Registration extension(doc: SRegHowTo)
<% Map sRegAttrs = new LinkedHashMap(); sRegAttrs.put("nickname", "Nickname"); sRegAttrs.put("email", "Email"); sRegAttrs.put("fullname", "Fullname"); sRegAttrs.put("dob", "Date of birth"); sRegAttrs.put("gender", "Gender"); sRegAttrs.put("postcode", "Postcode"); sRegAttrs.put("country", "Country"); sRegAttrs.put("language", "Language"); sRegAttrs.put("timezone", "Timezone"); %>
All:
${attribute.value}:
Sample 3: using the Attribute Exchange extension(doc: AttributeExchangeHowTo)
<% Map attributes = new LinkedHashMap(); attributes.put("country", "http://axschema.org/contact/country/home"); attributes.put("email", "http://axschema.org/contact/email"); attributes.put("firstname", "http://axschema.org/namePerson/first"); attributes.put("lastname", "http://axschema.org/namePerson/last"); attributes.put("language", "http://axschema.org/pref/language"); %>
Alias TypeUri Required Count
openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/logout.jsp0000644001501200150120000000007711034531766025577 0ustar miguelmiguel<% session.invalidate(); response.sendRedirect("index.jsp"); %>openid4java-0.9.6.662/samples/consumer-servlet/src/main/webapp/formredirection.jsp0000644001501200150120000000142111034531766027453 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> OpenID HTML FORM Redirection
openid4java-0.9.6.662/samples/consumer-servlet/src/main/resources/0000755001501200150120000000000011627733442024303 5ustar miguelmiguelopenid4java-0.9.6.662/samples/consumer-servlet/src/main/resources/log4j.properties0000644001501200150120000000117511034531766027441 0ustar miguelmiguellog4j.rootLogger=WARN, stdout, logfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.File=${java.io.tmpdir}/consumer-servlet.log log4j.appender.logfile.Encoding=UTF-8 log4j.appender.logfile.MaxFileSize=4096KB log4j.appender.logfile.MaxBackupIndex=3 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n log4j.logger.org.openid4java.samples=DEBUGopenid4java-0.9.6.662/samples/consumer-servlet/pom.xml0000644001501200150120000000411711551252176022072 0ustar miguelmiguel org.openid4java openid4java-samples 0.9.6 ../pom.xml 4.0.0 consumer-servlet war OpenID consumer demo using servlet http://openid4java.org consumer-servlet org.mortbay.jetty maven-jetty-plugin org.apache.maven.plugins maven-eclipse-plugin true true 1.5 junit junit 3.8.1 test javax.servlet servlet-api 2.3 provided javax.servlet jstl 1.1.2 taglibs standard 1.1.2 commons-lang commons-lang 2.5 org.openid4java openid4java-consumer ${version} openid4java-0.9.6.662/samples/consumer-servlet/README.txt0000644001501200150120000000037711034531766022260 0ustar miguelmiguelHow to run the demo. Step 1. Install openid4java library. % cd openid4java % mvn package install Step 2. Run the demo. % cd samples/consumer-servlet % mvn jetty:run Step 3. OK. Open http://localhost:8080/consumer-servlet/ by browser. openid4java-0.9.6.662/samples/README0000644001501200150120000000142711205322263016110 0ustar miguelmiguelOpenID4Java Samples * formredirection JSP helper file for generating indirect messages (Authentication Requests and Responses) through HTML FORM Redirection. * simple-openid An openid demo consumer and provider using only JSPs. * consumer-servlet An openid demo consumer using servlet. * demorp Demonstrative Relying Party implementation, featuring Attribute Exchange and OpenID Infocards support. See demorp/INSTALL for installation and configuration instructions. * infocardop Stripped down OpenID Provider implementation, adapted for the protocol flow described by the OpenID Information Cards specification : handles only direct verification (openid.mode=check_authentication) requests. See infocardop/INSTALL for installation and configuration instructions. openid4java-0.9.6.662/samples/infocardop/0000755001501200150120000000000011627733442017365 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/conf/0000755001501200150120000000000011627733442020312 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/conf/config.properties-demo0000644001501200150120000000011611034531533024602 0ustar miguelmigueldatabase.jndi=java:comp/env/jdbc/infocardop private.assoc.table=private_assoc openid4java-0.9.6.662/samples/infocardop/conf/config.properties-ivb0000644001501200150120000000012411034531533024435 0ustar miguelmigueldatabase.jndi=java:comp/env/jdbc/infocardop_local private.assoc.table=private_assoc openid4java-0.9.6.662/samples/infocardop/project/0000755001501200150120000000000011627733442021033 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/0000755001501200150120000000000011034531630021605 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/net/0000755001501200150120000000000011034531630022373 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/0000755001501200150120000000000011034531630023356 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/openidcards/0000755001501200150120000000000011034531630025651 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/openidcards/infocardop/0000755001501200150120000000000011034531630027775 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/openidcards/infocardop/web/0000755001501200150120000000000011627733442030567 5ustar miguelmiguel././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/openidcards/infocardop/web/InfocardOPController.javaopenid4java-0.9.6.662/samples/infocardop/project/src/net/sxip/openidcards/infocardop/web/InfocardOPC0000644001501200150120000001036711034531630032573 0ustar miguelmiguelpackage net.sxip.openidcards.infocardop.web; import org.springframework.web.servlet.mvc.AbstractController; import org.springframework.web.servlet.ModelAndView; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletOutputStream; import java.io.IOException; import org.openid4java.server.ServerManager; import org.openid4java.server.ServerException; import org.openid4java.message.*; import org.openid4java.OpenIDException; public class InfocardOPController extends AbstractController { private static Logger _log = Logger.getLogger(InfocardOPController.class); private static final boolean DEBUG = _log.isDebugEnabled(); private String _openidErrorView; private ServerManager _manager; public void setOpenidErrorView(String openidErrorView) { this._openidErrorView = openidErrorView; } public void setServerManager(ServerManager manger) { this._manager = manger; } public ServerManager getManager() { return _manager; } protected ModelAndView handleRequestInternal( HttpServletRequest httpReq, HttpServletResponse httpResp) { if ("GET".equals(httpReq.getMethod())) return new ModelAndView(_openidErrorView); // extract the parameters from the requestParams ParameterList requestParams = new ParameterList(httpReq.getParameterMap()); String mode = requestParams.getParameterValue("openid.mode"); boolean compat = ! requestParams.hasParameter("openid.ns"); try { if ("check_authentication".equals(mode)) return handleVerifyReq(httpReq, httpResp, requestParams); else return handleUnknownReq(httpReq, httpResp); } catch (OpenIDException e) { _log.error("Error handling OpenID request: ", e); return directError(httpResp, e.getMessage(), compat); } } private ModelAndView handleVerifyReq(HttpServletRequest httpReq, HttpServletResponse httpResp, ParameterList requestParams) throws ServerException { // --- processing a verification requestParams --- Message response = _manager.verify(requestParams); String responseText = response.keyValueFormEncoding(); _log.info("Processed direct verification request from: " + httpReq.getRemoteAddr()); return directResponse(httpResp, responseText); } private ModelAndView handleUnknownReq(HttpServletRequest httpReq, HttpServletResponse httpResp) throws ServerException { // --- error response --- Message response = DirectError.createDirectError("Unknown requestParams"); String responseText = response.keyValueFormEncoding(); _log.error("Sending direct error response to " + httpReq.getRemoteAddr()); return directResponse(httpResp, responseText); } private ModelAndView directResponse(HttpServletResponse httpResp, String response) throws ServerException { if (DEBUG) _log.debug("Sending direct response:\n" + response); try { ServletOutputStream os = httpResp.getOutputStream(); os.write(response.getBytes()); os.close(); } catch (IOException e) { throw new ServerException("Error generating direct verification response", e); } return null; } private ModelAndView directError(HttpServletResponse httpResp, String response, boolean compat) { if (DEBUG) _log.debug("Sending direct response:\n" + response); try { DirectError err = DirectError.createDirectError(response, compat); ServletOutputStream os = httpResp.getOutputStream(); os.write(err.keyValueFormEncoding().getBytes()); os.close(); } catch (IOException e) { _log.error("Error generating direct error response", e); } return null; } } openid4java-0.9.6.662/samples/infocardop/project/project.properties0000644001501200150120000000045611140117010024575 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # component.name=infocardop compile.debug=yes compile.debuglevel=source,lines,vars compile.optimize=off compile.deprecation=off compile.target=1.5 compile.source=${compile.target} openid4java.dir=../../.. openid4java.lib.dir=${openid4java.dir}/lib openid4java-0.9.6.662/samples/infocardop/project/lib/0000755001501200150120000000000011627733442021601 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/build.xml0000644001501200150120000003043111275161465022654 0ustar miguelmiguel Last Changed Rev (local): : ${svn.rev.local} Copyright © 2006-2008 Sxip Identity Corp. All Rights Reserved.]]> Tomcat home directory: ${tomcat.home.dir} openid4java-0.9.6.662/samples/infocardop/project/www/0000755001501200150120000000000011627733442021657 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/0000755001501200150120000000000011627733442022706 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/applicationContext.xml0000644001501200150120000000362511034531573027277 0ustar miguelmiguel classpath:config.defaults.properties classpath:config.properties file:/www/sxweb/server/openidcards/infocardop/conf/config.properties openid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/classes/0000755001501200150120000000000011627733442024343 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/classes/log4j.properties0000644001501200150120000000654611034531573027504 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # ################################################################ # # Logging controls # ################################################################ log4j.rootLogger=INFO, A1 # INFO - log level, possible values: DEBUG, INFO, WARN, ERROR # If DEBUG is used passwords will be dumped to log files! # Do not use in production. # A2 - general daily rolling file appender # A3 - errors only file appender # Add A1 to also log to console (and catalina.out) # Add A4 to also log to syslog log4j.logger.org.openid4java=DEBUG, A2, A3 log4j.logger.net.sxip=DEBUG, A2, A3 # A1 is set to be ConsoleAppender sending its output to System.out log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout # The conversion pattern consists of date in ISO8601 format, level, # thread name, logger name truncated to its rightmost two components # and left justified to 17 characters, location information consisting # of file name (padded to 13 characters) and line number, nested # diagnostic context, the and the application supplied message log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors, Warnings and Infos to an audit log # ################################################################ # Appender A2 writes all messages to a file. # Define the location where the log file will be created. # Ensure the directory already exists with appropriate # write permissions. log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender log4j.appender.A2.DatePattern='.'yyyy'-'MM'-'dd log4j.appender.A2.File=${catalina.home}/logs/openidcards.sxip.com_op_debug_log # Append to the log. log4j.appender.A2.Append=true # Appender A2 uses the PatternLayout. log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors to an error log # ################################################################ # Appender A3 writes "error" class messages to a file. # Define the location where the log file will be created. # Ensure the directory already exists with appropriate # write permissions. log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender log4j.appender.A3.DatePattern='.'yyyy'-'MM'-'dd log4j.appender.A3.File=${catalina.home}/logs/openidcards.sxip.com_op_error_log # Append to the log. log4j.appender.A3.Append=true log4j.appender.A3.threshold=ERROR # Appender A3 uses the PatternLayout. log4j.appender.A3.layout=org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors to the SysLog # ################################################################ # Appender A4 writes to the syslog. log4j.appender.A4=org.apache.log4j.net.SyslogAppender log4j.appender.A4.threshold=ERROR # Specify host name of the syslog service log4j.appender.A4.SyslogHost=localhost # Appender A4 uses the PatternLayout. log4j.appender.A4.layout=org.apache.log4j.PatternLayout log4j.appender.A4.layout.ConversionPattern=%m CLASS:%C{2} %n openid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/classes/config.defaults.properties0000644001501200150120000000020511034531573031522 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # database.jndi=java:comp/env/jdbc/infocardop private.assoc.table=private_assoc openid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/web.xml0000644001501200150120000000203611034531573024177 0ustar miguelmiguel Infocard OpenID Provider org.springframework.web.context.ContextLoaderListener InfocardOPController org.springframework.web.servlet.DispatcherServlet 2 InfocardOPController /index.jsp DB Connection jdbc/infocardop_local javax.sql.DataSource Container openid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/InfocardOPController-servlet.xml0000644001501200150120000000414011034531573031132 0ustar miguelmiguel classpath:config.defaults.properties classpath:config.properties file:/www/sxweb/server/openidcards/infocardop/conf/config.properties /*=InfocardOPController openid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/jsp/0000755001501200150120000000000011627733442023502 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/WEB-INF/jsp/openiderror.jsp0000644001501200150120000000134311034531573026542 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> OpenID Error

Whoops!

An error was encountered while processing the OpenID request:
Expected a POST HTTP request but received a HTTP GET.

openid4java-0.9.6.662/samples/infocardop/project/www/META-INF/0000755001501200150120000000000011627733442023017 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/META-INF/context.xml0000644001501200150120000000101311034531573025211 0ustar miguelmiguel openid4java-0.9.6.662/samples/infocardop/project/www/style.css0000644001501200150120000000220211034531573023516 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ body { margin: 0; padding: 0; font-family: Verdana, Arial, "MS Trebuchet", sans-serif; font-size: 14px; } #wrapper { width: 750px; margin-left: auto; margin-right: auto; } #header { border-bottom: solid 2px #c0c0c0; margin-bottom: 20px; height: 90px; padding-top: 20px; } #message { border: solid 1px #fff32a; padding: 10px; background: #fff79b; margin-bottom: 14px; } #body { margin-left: 150px; margin-right: 150px; } #footer { border-top: solid 2px #c0c0c0; margin-top: 20px; padding-top: 30px; } #footer p { text-align: center; color: #c0c0c0; } #contents { margin-bottom: 15px; } .form { margin-top: 5px; } .form input { border: solid 1px #ccc; } .left { float: left; } .right { float: right; } .footer-center { clear: both; } #footer a { text-decoration: none; color: #555; } input.openid { background: url( images/login_openid_bg.gif ) no-repeat; background-color: #fff; background-position: 0 50%; color: #000; padding-left: 18px; } openid4java-0.9.6.662/samples/infocardop/project/www/images/0000755001501200150120000000000011627733442023124 5ustar miguelmiguelopenid4java-0.9.6.662/samples/infocardop/project/www/images/login_openid_bg.gif0000644001501200150120000000035511034531573026725 0ustar miguelmiguelGIF89ai kļcfx)о!,j'dieH:ӺBG-FS&O!$ 8[`ApK Q('g%2) z)94#!;openid4java-0.9.6.662/samples/infocardop/project/www/images/trans-1.gif0000644001501200150120000000144711034531573025077 0ustar miguelmiguelGIF89af3̙f3f3ffffff3f3333f333f3f3̙f3̙̙̙̙f̙3̙ffffff3f3333f333f3̙f3̙̙f3̙f3ff̙ffff3f33̙33f333̙f3ffffff3ffff̙fff3fffffff3ffffffffffff3fff3f3f3f3ff33f3ffffff3f3333f333333̙3f3333333f3333f3f3f3ff3f33f33333333f333333333f333f3̙f3f3ffffff3f3333f333f3!,;openid4java-0.9.6.662/samples/infocardop/InfocardOP.ipr0000644001501200150120000003762011140117010022046 0ustar miguelmiguel openid4java-0.9.6.662/samples/infocardop/INSTALL0000644001501200150120000000400711034531630020402 0ustar miguelmiguel... OpenID Infocards / Infocard-OP : INSTALL ======================================================================== INSTALLATION AND CONFIGURATION INSTRUCTIONS Introduction: This document describes how to install, configure and use the Infocard OpenID Provider, a stripped-down version of an OpenID Provider. Used together with an STS that can issue RSTRs with OpenID tokens (as specified by OpenID Infocards 1.0), this OP module only handles direct OpenID verification requests (openid.mode=check_authentication). For general information about the OpenID Infocards package please see the README document in the package root folder. Configuration: 1. SQL/JDBC a) A JDBC Connector library installed into your application server: MySQL and Tomcat example: http://dev.mysql.com/downloads/connector/j/ mysql-connector-java-*.jar installed in CATALINA_HOME/common/lib/ b) Database with one table for storing OpenID private associations, with the following schema: CREATE TABLE `private_assoc` ( `handle` varchar(255) NOT NULL, `type` varchar(255) NOT NULL, `mackey` varchar(255) NOT NULL, `expdate` datetime NOT NULL, PRIMARY KEY (`handle`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 This database needs to be shared with the 'higgins-sts' webapp. c) Application server configured with a JDBC data source with the following JNDI name: java:comp/env/jdbc/infocardop Tomcat example: infocardop/project/www/META-INF/context.xml Build and Installation: In the project/ folder, run ant This will create deployable dist/infocardop.war file. openid4java-0.9.6.662/samples/infocardop/InfocardOP.iml0000644001501200150120000003171511140117010022034 0ustar miguelmiguel jar://$MODULE_DIR$/project/lib/commons-codec-1.3.jar!/ jar://$MODULE_DIR$/project/lib/commons-httpclient-3.0.1.jar!/ jar://$MODULE_DIR$/project/lib/commons-logging-1.03.jar!/ jar://$MODULE_DIR$/project/lib/htmlparser.jar!/ jar://$MODULE_DIR$/project/lib/java-openid-sxip.jar!/ jar://$MODULE_DIR$/project/lib/jstl.jar!/ jar://$MODULE_DIR$/project/lib/log4j-1.2.8.jar!/ jar://$MODULE_DIR$/project/lib/openxri-client.jar!/ jar://$MODULE_DIR$/project/lib/openxri-syntax.jar!/ jar://$MODULE_DIR$/project/lib/spring.jar!/ jar://$MODULE_DIR$/project/lib/standard.jar!/ jar://$MODULE_DIR$/project/libext/servlet-api.jar!/ jar://$MODULE_DIR$/project/libext/svnant.jar!/ jar://$MODULE_DIR$/project/libext/svnClientAdapter.jar!/ jar://$MODULE_DIR$/project/libext/svnjavahl.jar!/ openid4java-0.9.6.662/samples/demorp/0000755001501200150120000000000011627733442016527 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/0000755001501200150120000000000011205322261017277 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/0000755001501200150120000000000011205322261020065 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/sxip/0000755001501200150120000000000011205322261021050 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/sxip/openidcards/0000755001501200150120000000000011205322261023343 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/sxip/openidcards/icdemo/0000755001501200150120000000000011205322261024603 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/sxip/openidcards/icdemo/web/0000755001501200150120000000000011627733442025377 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/src/net/sxip/openidcards/icdemo/web/IndexController.java0000644001501200150120000002732011205322261031342 0ustar miguelmiguelpackage net.sxip.openidcards.icdemo.web; import org.springframework.web.servlet.mvc.AbstractController; import org.springframework.web.servlet.ModelAndView; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.LinkedHashMap; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.discovery.DiscoveryException; 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.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.infocard.InfocardException; import org.openid4java.OpenIDException; import org.openid4java.infocard.OpenIDToken; /** * @author Marius Scurtescu */ public class IndexController extends AbstractController { private static Logger _logger = Logger.getLogger(IndexController.class); private static final String LOGGEDIN ="loggedin"; // attribute typeUri -> "nice label / alias" private static HashMap _attributes = new HashMap(); static { _attributes.put("http://axschema.org/contact/email", "Email"); _attributes.put("http://axschema.org/namePerson/first", "FirstName"); _attributes.put("http://axschema.org/namePerson/last", "LastName"); _attributes.put("http://axschema.org/contact/phone/default", "Phone"); _attributes.put("http://axschema.org/contact/postalAddress/home", "Address"); _attributes.put("http://axschema.org/contact/city/home", "City"); _attributes.put("http://axschema.org/contact/postalCode/home", "ZipCode"); _attributes.put("http://axschema.org/contact/country/home", "Country"); _attributes.put("http://axschema.org/contact/web/blog", "Blog"); } private String _loginView; private String _homeView; private String _postView; private String _errorView; private String _stsUrl; private String _axUrl; private ConsumerManager _consumerManager; private String _baseUrl; public void setConsumerManager(ConsumerManager consumerManager) { this._consumerManager = consumerManager; } public void setLoginView(String loginView) { _loginView = loginView; } public void setHomeView(String homeView) { _homeView = homeView; } public void setPostView(String postView) { _postView = postView; } public void setErrorView(String _errorView) { this._errorView = _errorView; } public void setStsUrl(String stsUrl) { this._stsUrl = stsUrl; } public void setAxUrl(String axUrl) { this._axUrl = axUrl; } public void setBaseUrl(String baseUrl) { _baseUrl = baseUrl; } protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String return_to = _baseUrl + request.getContextPath() + "/"; String mode = request.getParameter("openid.mode"); String xmlToken = request.getParameter("xmlToken"); String openIdIdentifier = request.getParameter("openid_identifier"); try { if (mode != null) { // received a standard OpenID response ParameterList openidResp = extractFromOpenIDPost(request); return processOpenIDResp(request, session, openidResp); } else if (xmlToken != null) { // received an xmlToken from an identity selector ParameterList openidResp = extractFromInfocardPost(request); return processOpenIDResp(request, session, openidResp); } else if (openIdIdentifier != null) { return buildFetchReq(openIdIdentifier, session, return_to); } else { if (request.getParameter("logout") != null) { _logger.info("Logging out..."); session.removeAttribute(LOGGEDIN); session.removeAttribute("message"); } if (session.getAttribute(LOGGEDIN) == null) { _logger.info("Showing login page..."); return showLoginPage(); } else { _logger.info("(Re)Showing home / data view..."); return new ModelAndView(_homeView); } } } catch (Exception e) { _logger.error("Error encountered: ", e); return new ModelAndView(_errorView); } } private ModelAndView showLoginPage() { Map model = new HashMap(); model.put("title", "OpenID Infocards Demo"); String loginMessage1 = "This is a demonstration of using OpenID Information Cards" + "* to log into an OpenID Relying Party.

\n" + "Besides OpenID Authentication, the Relying Party " + "also requests profile data using Information Card conventions, " + "and the values are returned in the OpenID assertion, " + "using the OpenID Attribute Exchange** extension.\n"; String loginMessage2 = "* You can get an OpenID Information Card " + "here." + "The OpenID Information Cards spec can be found " + "here." + "
** The OpenID Attribute Exchange spec " + "can be found here\""; model.put("contents", loginMessage1); model.put("contents2", loginMessage2); return new ModelAndView(_loginView, model); } private ModelAndView buildFetchReq(String identifier, HttpSession session, String return_to) throws OpenIDException { _logger.info("Building auth + fetch request for: " + identifier); Map model = new HashMap(); List discoveries; String errorMsg = ""; try { discoveries = _consumerManager.discover(identifier); } catch (DiscoveryException e) { _logger.error("Error while performing HTML discovery on " + identifier, e); discoveries = null; errorMsg = "

" + e.getMessage() + ""; } if (discoveries == null || discoveries.size() == 0) { _logger.error("Discovery failed on: " + identifier); model.put("message", "The " + identifier + " identifier could not be resolved." + errorMsg); return new ModelAndView(_loginView, model); } DiscoveryInformation discovered = _consumerManager.associate(discoveries); // store the discovery information in the session for later use session.setAttribute("discovered", discovered); FetchRequest fetch = FetchRequest.createFetchRequest(); for (String typeUri : _attributes.keySet()) { fetch.addAttribute(_attributes.get(typeUri), typeUri, false); } AuthRequest req = _consumerManager.authenticate(discovered, return_to); req.addExtension(fetch); model.put("message", req); _logger.info("Sending fetch request / auto-post view..."); return new ModelAndView(_postView, model); } private ParameterList extractFromInfocardPost(HttpServletRequest request) throws InfocardException { _logger.info("Extracting OpenID AuthResponse / Fetch Response from Infocard POST..." ); String xmlToken = request.getParameter("xmlToken"); request.getSession().setAttribute("openidAssertion", xmlToken); OpenIDToken token = OpenIDToken.createFromXmlToken(xmlToken); return token.getOpenIDParams(); } private ParameterList extractFromOpenIDPost(HttpServletRequest request) throws MessageException { _logger.info("Extracting OpenID AuthResponse / Fetch Response from OpenID POST..." ); ParameterList openidAssertion = new ParameterList(request.getParameterMap()); request.getSession().setAttribute("openidAssertion", openidAssertion.toString()); return openidAssertion; } private ModelAndView processOpenIDResp(HttpServletRequest request, HttpSession session, ParameterList openidResp) throws OpenIDException { _logger.info("Processing OpenID auth / fetch response..." ); Map model = new HashMap(); model.put("title", "OpenID 2.0 OpenID InfoCards Demo"); // retrieve the previously stored discovery information DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovered"); 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); verification.getVerifiedId(); Message authResponse = verification.getAuthResponse(); if (!(authResponse instanceof AuthSuccess)) { _logger.error("Negative auth response received; showing login view..."); model.put("message", "Negative authentication response received from the OpenID Provider."); return new ModelAndView(_loginView, model); } Identifier verified = verification.getVerifiedId(); String identifier; if (verified == null) { _logger.error("OpenID verification failed; showing login view..."); model.put("message", verification.getStatusMsg()); return new ModelAndView(_loginView, model); } else { identifier = verified.getIdentifier(); } AuthSuccess authSuccess = (AuthSuccess) authResponse; FetchResponse fetchResp = null; Map attributes = new LinkedHashMap(); MessageExtension ext; if ( authSuccess.hasExtension(AxMessage.OPENID_NS_AX) && (ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX)) instanceof FetchResponse) { fetchResp = (FetchResponse) ext; // extract the rest of the optional attributes List aliases = fetchResp.getAttributeAliases(); Map types = fetchResp.getAttributeTypes(); String alias; List values; for (Object a : aliases) { alias = (String) a; values = fetchResp.getAttributeValues(alias); attributes.put(_attributes.get(types.get(alias)), values.size() > 0 ? (String) values.get(0) : null); } } session.setAttribute(LOGGEDIN, ""); session.setAttribute("attributes", attributes); session.setAttribute("identifier", identifier); session.setAttribute("message", fetchResp); _logger.info("AX success; showing home / data view..."); return new ModelAndView(_homeView, model); } } openid4java-0.9.6.662/samples/demorp/project.properties0000644001501200150120000000044611205322261022300 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # component.name=demorp compile.debug=yes compile.debuglevel=source,lines,vars compile.optimize=off compile.deprecation=off compile.target=1.5 compile.source=${compile.target} openid4java.dir=../.. openid4java.lib.dir=${openid4java.dir}/lib openid4java-0.9.6.662/samples/demorp/lib/0000755001501200150120000000000011627733442017275 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/build.xml0000644001501200150120000002501511205322261020334 0ustar miguelmiguel Last Changed Rev (local): : ${svn.rev.local} Copyright © 2006-2008 Sxip Identity Corp. All Rights Reserved.]]> Tomcat home directory: ${tomcat.home.dir} openid4java-0.9.6.662/samples/demorp/DemoRP.ipr0000644001501200150120000004005011205322261020351 0ustar miguelmiguel openid4java-0.9.6.662/samples/demorp/www/0000755001501200150120000000000011627733442017353 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/WEB-INF/0000755001501200150120000000000011627733442020402 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/WEB-INF/springController-servlet.xml0000644001501200150120000000453611205322252026145 0ustar miguelmiguel classpath:config.defaults.properties classpath:config.properties file:/www/sxweb/server/openidcards/icdemo/conf/config.properties /index.jsp=indexController openid4java-0.9.6.662/samples/demorp/www/WEB-INF/applicationContext.xml0000644001501200150120000000357011205322252024762 0ustar miguelmiguel classpath:config.defaults.properties classpath:config.properties file:/www/sxweb/server/openidcards/icdemo/conf/config.properties openid4java-0.9.6.662/samples/demorp/www/WEB-INF/classes/0000755001501200150120000000000011627733442022037 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/WEB-INF/classes/log4j.properties0000644001501200150120000000720611205322252025162 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # ################################################################ # # Sxip Access logging controls # ################################################################ log4j.rootLogger=INFO, A1 # INFO - log level, possible values: DEBUG, INFO, WARN, ERROR # If DEBUG is used passwords will be dumped to log files! # Do not use in production. # A2 - general daily rolling file appender # A3 - errors only file appender # Add A1 to also log to console (and catalina.out) # Add A4 to also log to syslog log4j.logger.org.openid4java=DEBUG, A2, A3 log4j.logger.net.sxip=DEBUG, A2, A3 # A1 is set to be ConsoleAppender sending its output to System.out log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout # The conversion pattern consists of date in ISO8601 format, level, # thread name, logger name truncated to its rightmost two components # and left justified to 17 characters, location information consisting # of file name (padded to 13 characters) and line number, nested # diagnostic context, the and the application supplied message log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors, Warnings and Infos to an audit log # ################################################################ # Appender A2 writes all messages to the file "sxip-tng.log". # Define the location where the log file will be created. # Ensure the directory already exists with appropriate # write permissions. Refer to the "Troubleshooting" section # of the Sxip Access documentation for further information about # error messages. log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender log4j.appender.A2.DatePattern=yyMMdd'.log' log4j.appender.A2.File=${catalina.home}/logs/openidcards.sxip.com_demorp.log # Append to the log. log4j.appender.A2.Append=true # Appender A2 uses the PatternLayout. log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors to an error log # ################################################################ # Appender A3 writes "error" class messages to the file "sxip-tng-error.log". # Define the location where the log file will be created. # Ensure the directory already exists with appropriate # write permissions. Refer to the "Troubleshooting" section # of the Sxip Access documentation for further information about # error messages. log4j.appender.A3=org.apache.log4j.DailyRollingFileAppender log4j.appender.A3.DatePattern=yyMMdd'.log' log4j.appender.A3.File=${catalina.home}/logs/openidcards.sxip.com_demorp_error.log # Append to the log. log4j.appender.A3.Append=true log4j.appender.A3.threshold=ERROR # Appender A3 uses the PatternLayout. log4j.appender.A3.layout=org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss'Z'} %-5p %m CLASS:%C{2} %t %x %n ################################################################ # # Send Errors to the SysLog # ################################################################ # Appender A4 writes to the syslog. log4j.appender.A4=org.apache.log4j.net.SyslogAppender log4j.appender.A4.threshold=ERROR # Specify host name of the syslog service log4j.appender.A4.SyslogHost=localhost # Appender A4 uses the PatternLayout. log4j.appender.A4.layout=org.apache.log4j.PatternLayout log4j.appender.A4.layout.ConversionPattern=%m CLASS:%C{2} %n openid4java-0.9.6.662/samples/demorp/www/WEB-INF/classes/config.defaults.properties0000644001501200150120000000031411205322252027207 0ustar miguelmiguel# # Copyright 2006-2008 Sxip Identity Corporation # base.url=http://localhost:8080 sts.url=https://openidcards.sxip.com/TokenService/ ax.url=http://openid.net/specs/openid-attribute-exchange-1_0-07.html openid4java-0.9.6.662/samples/demorp/www/WEB-INF/web.xml0000644001501200150120000000151411205322252021663 0ustar miguelmiguel OpenID InfoCards Demo org.springframework.web.context.ContextLoaderListener springController org.springframework.web.servlet.DispatcherServlet 2 springController /index.jsp openid4java-0.9.6.662/samples/demorp/www/WEB-INF/jsp/0000755001501200150120000000000011627733442021176 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/WEB-INF/jsp/error.jsp0000644001501200150120000000165311205322252023033 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> OpenID Error

Whoops!

An error was encountered while processing the OpenID request.

If you would like to help us troubleshoot the error, please contact us with details about the site you were trying to log into and the time when this error occured.

openid4java-0.9.6.662/samples/demorp/www/WEB-INF/jsp/home.jsp0000644001501200150120000000520511205322252022627 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ page import="java.util.Calendar"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ${title}

Welcome! You have logged in using your ${identifier} OpenID identifier.

${parameter.key}: ${parameter.value}
${parameter.key}: N/A
[Show / hide OpenID Assertion]
${fn:escapeXml(openidAssertion)}
        

${contents}
openid4java-0.9.6.662/samples/demorp/www/WEB-INF/jsp/post.jsp0000644001501200150120000000171411205322252022665 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ${title}
openid4java-0.9.6.662/samples/demorp/www/WEB-INF/jsp/login.jsp0000644001501200150120000001317111205322252023010 0ustar miguelmiguel<%-- ~ Copyright 2006-2008 Sxip Identity Corporation --%> <%@ page import="java.util.Calendar"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ${title}

<%--
--%>

Login with an OpenID-InfoCard:

openid4java-0.9.6.662/samples/demorp/www/META-INF/0000755001501200150120000000000011627733442020513 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/META-INF/context.xml0000644001501200150120000000011211205322251022673 0ustar miguelmiguel openid4java-0.9.6.662/samples/demorp/www/style.css0000644001501200150120000003343111205322252021212 0ustar miguelmiguel/* * Copyright 2006-2008 Sxip Identity Corporation */ @import 'legacy.css'; body, html { /* background: url(newwebsite.png) #fff center top no-repeat; */ font-family: "verdana", "arial", "bitstream vera sans", sans; margin: 0; font-size: 11px; padding: 0; color: #434343; } p { color: #434343; font-weight: normal; padding-bottom: 5px; line-height: 16px; } a{ text-decoration: none;} a img { border: 0; } a { color: #00209f; text-decoration: underline; } h4 { margin: 10px 0 3px 0; } table, tr, td{ font-size: 11px; vertical-align: top; } td { padding-bottom: 15px; padding-left: 15px; } table li { padding: 2px; } table h3 { font-size: 1em; text-align: right; padding: 0; margin: 0; padding-left: 5px; } table p { padding: 0 !important; margin: 0; } pre { font-size: 11px; } #wrapper{ width: 750px; margin-left: auto; margin-right: auto; } #header { border-bottom: solid 1px #c0c0c0; background-color: #fff; margin-top: 15px; padding-bottom: 15px; } #header img{ border: 0; } #header h1{display: none;} #header h2{ margin: 0px; margin-top: -20px; padding: 0px; color: #00209f; text-align: right; font-size: 18px; font-weight: 500; font-family: sans-serif; } #navigation { float: left; width: 140px; padding-top: 5px; margin-left: 5px; } #navigation h3{ font-size: 12px; color: #363636; margin: 0; padding: 0; margin-top: 11px; margin-bottom: 4px; font-weight: 700; font-size: 11px; } #navigation ul { margin: 0; padding: 0; padding-left: 2px; text-indent: 0px; color: #00209f; font-weight: normal; } #navigation li { padding: 1px 0; list-style: none; } #navigation li a { margin-left: 0px; text-indent: 0px; padding-left: 10px; background: url(/themes/sxip.com/icons/arrow.png) no-repeat 0 3px; } #navigation ul ul li a{ background: url(/themes/sxip.com/icons/arrow2.png) no-repeat 1px 3px !important; } #navigation li.phone { padding-left: 10px; background: url(/themes/sxip.com/icons/phone.png) no-repeat -1px 4px !important; } #navigation li.email a { background: url(/themes/sxip.com/icons/mail.png) no-repeat -1px 1px !important; } #navigation a.current { background: url(/themes/sxip.com/icons/arrowfill.png) no-repeat 0 3px; font-weight: bold; } #navigation a:hover { background: url(/themes/sxip.com/icons/arrowfill.png) no-repeat 0 3px; font-weight: bold; } #navigation ul ul li a.current { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } #navigation ul ul li a:hover { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } .feedbuttons { margin: 20px 10px ; } /* blogmenu */ #blogmenu { width: 130px; margin: 0; padding: 0; float: right; border-left: solid 1px #919191; margin-left: 25px; padding-top: 0px; line-height: 1.3em; padding-left: 0px; padding-bottom: 50px; } #blogmenu a{ text-decoration: none; } #blogmenu h4 { padding-left: 20px; margin: 10px 0; color: #df008f; font-weight: bold; font-size: 14px; } #blogmenu ul { } #blogmenu li { list-style: none; } #blogmenu img{ margin-bottom: 10px; } #content { /*margin-left: 140px;*/ /*padding-left: 20px;*/ padding-top: 15px; /*padding-bottom: 30px;*/ } #content h1 { color: #363636; margin: 0; padding: 0 0 10px 0; font-size: 1.8em; } #content h2 { color: #363636; margin: 0; padding: 0; } #content h2 span { font-size: 12px; font-weight: 200; } #content p { margin: 0; line-height: 1.7; } #infocardSupport p { border: solid 1px #fff32a; padding: 10px; background: #fff79b; margin-bottom: 14px; } #content em { color: #e50f9f; font-weight: 700; font-size: 11px; } #content ul, #content li { padding-bottom: 3px; padding-left: 2px; margin-left: 10px; text-indent: 0; } #intro { padding-top: 20px; margin-bottom: 20px; } #intro p { margin-bottom: 4px; font-size: 120%; /*color: #7e8083;*/ } #intro h2 { font-size: 24px; } #summary { margin-bottom: 35px; } #summary h2 { margin-bottom: -15px; font-size: 20px; } #summary h3 { margin: 0px; margin-top: 25px; font-size: 14px; font-weight: bold; color: #00209f; line-height: 20px; } #summary h3 span { color: #4e4e4e; } #summary p { font-size: 11px; } .blog { } .blog h2{ margin-bottom: -5px; } .blog H3 { font-weight: Bold; font-size: 1.2em; color: #00209f; margin: 0; padding: 0; margin-top: 20px; } .blog H4{ font-size: 10px; font-weight: bold; color: #999; margin: 0; padding: 0; } .blog p{ font-size: 12px; line-height: 16px; padding: 5px 0px 0px 0px; } .blog li { } div.arrowbar { display: block; height: 20px; } #comment_bar{ border-top: solid 1px #ccc; margin-top: 10px; padding: 10px 0 0 0; width: 420px; } #comment_bar img { padding: 1px; vertical-align: middle; margin-right: 5px; } #comment_bar a { } #comment_bar ul{ margin: 0; padding: 0; } #comment_bar li { margin: 0; padding: 0; list-style: none; display: inline; padding-right: 10px; } #body { font-size: 14px; color: #818284; padding-top: 15px; padding-bottom: 15px; } #body p { /*color: #818284;*/ } #body a { color: #3fc1f3; } #body ul { } #body li { /*color: #818284; */ } #footnote { margin-top: 50px; clear: both; color: #818284; font-size: 12px; padding: 0; text-indent: 0; } #footnote p { color: #818284; } /*--------------- footer ---------------*/ #footer{ margin-top: 50px; clear: both; border-top: solid 1px #c0c0c0; color: #666; font-size: 12px; } #footer ul { float: right; margin: 0; padding: 0; text-indent: 0; } #footer ul li{ display: inline; margin: 0; padding: 0; text-indent: 0; margin-left: 10px; } #footer a{ color: #666; text-decoration: none; } #footer a:hover { text-decoration: underline; } footer p { margin: 0; padding: 0; text-indent: 0; } #footer_legal{ float: left; } .right{ float: right; } .contacts { margin-top: 20px; } .contacts h3 { } .contacts ul { padding-bottom: 5px !important; } .linkbox { margin-top: 0; margin-left: 15px; float: right; } .linkbox img { border: none; } .linkbox h3 { } .linkbox p { } .linkbox ul { font-size: 11px; font-weight: normal; } .linkbox ul { margin: 0; padding: 0; padding-left: 2px; text-indent: 0px; color: #00209f; font-weight: normal; } .linkbox li { padding: 1px 0; list-style: none; } .linkbox li a { margin-left: 0px; text-indent: 0px; padding-left: 10px; background: url(/themes/sxip.com/icons/arrow.png) no-repeat 0 3px; } .linkbox ul ul li a{ background: url(/themes/sxip.com/icons/arrow2.png) no-repeat 1px 3px !important; } .linkbox li.phone { padding-left: 12px !important; background: url(/themes/sxip.com/icons/phone.png) no-repeat 0px 4px !important; } .linkbox li.email a { background: url(/themes/sxip.com/icons/mail.png) no-repeat -1px 1px !important; } .linkbox ul ul li a.current { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } .linkbox ul ul li a:hover { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } .linkbox img { font-size: 30px; letter-spacing: -5px; font-weight: bold; color: #fff; text-indent: -10px; } .gw form{ padding:15px; padding-top: 20px; background-color: #eee; width: 480px; margin-right: auto; margin-left: auto; margin-bottom: 20px; } .gw form h3{ margin: 0; padding: 0; } .gw h3 { margin-top: 25px; } .gw h1 { color: #f90; font-size: 14px; } .gw h2{ margin-top: 25px; margin-bottom: 10px; font-size: 16px; font-weight: 100; } .gw h4{ margin: 5px 0px 5px 0px;} .gw ul{ margin: 15px; } .gw li{ color: #ff9900; } .gw dl{ padding: 15px; width: 400px; margin-left: auto; margin-right: auto; } .gw dt{ font-weight: bolder; margin: 5px; } .gw dd{ margin-bottom: 10px; } .gw .notice { padding: 20px; width: 500px; margin-left: auto; margin-right: auto; font-weight: bolder; background-color: #edd; } .gw p{ margin-top: 5px; margin-left: 5px; } .gw strong{ color: #ff9900; } .xml { border: 1px solid; border-color:#FC9 #630 #330 #F96; padding:0 3px; font:600 10px lucida,verdana,sans-serif; color:#FFF !important; background:#F60; text-decoration: none !important; margin:0; } .orange { color: #e50f9f; } /* team page */ #team img { border: solid 1px #5a5a5a; margin: 0 15px 5px 0; float: left; } #team em { font-style: normal; font-size: 1.1em; } #team p{ margin-bottom: 5px; } /* careers page */ .jobs { margin-left: 10px; } .jobs h3 { font-size: 1.8em; color: #df008f; font-weight: normal; border-top: solid 1px #919191; padding-top: 10px; } /* careers page */ #relocate { float: right; width: 200px; border: Solid 1px #919191; background: url(/themes/sxip.com/images/relocate_bgnd.png) #fafafa no-repeat; padding: 5px; margin-left: 10px; } #relocate h3 { margin-top: 50px; text-align: center; } #relocate p { line-height: 12px; } #relocate li { list-style: none; padding: 2px; margin: 0; text-indent: 0; } #relocate li ul li { margin-left: 4em; } /* endorsements page */ .endorsement { padding-bottom: 5px; border-bottom: solid 1px #eee; margin-bottom: 15px; } .sig { padding-top: 3px; padding-left: 10px; } .sig p{ color: #919191; } .sig p a{ color: #919191; } .copyright { color: #919191; font-size: 0.9em; } /* glossary page */ #glossary h3 { font-size: 1.8em; color: #df008f; font-weight: normal; border-top: solid 1px #919191; padding-top: 15px; padding-left: 5px; } /* general */ /* these are for the breadcrumbs */ .section-title{ color: #333; } .more a { color: #df008f; padding: 0; margin: 0; } .more p { color: #df008f; padding: 0 !important; margin: 0 !important; } div.map { width: 20em; } pre { font-family: "Verdana", sans, sans-serif; } #image-gallery h3{ width: 600px; display: block; border-bottom: solid 2px #cccccc; padding-bottom: 5px } #image-gallery .section { margin-bottom: 15px; } #image-gallery a dl { float: left; text-align: center; width: 100px; height: 100px; padding: 4px; margin: 0px 2px; background-color: #fff; border: solid 1px #ccc; } #image-gallery a dl:hover{ border: solid 1px red; } #image-gallery dt { background-color: #fff; height: 65px; } #image-gallery .section dd { background-color: #eee; border: 0; padding: 2px; margin: 0; vertical-align: bottom; text-indent: 0; } #image-gallery .section h3 { padding-top: 15px; padding-left: 10px; } #image-gallery .sectiontwo dl { float: left; width: 325px; height: 100px; padding: 4px; margin: 5px 5px; background-color: #fff; border: solid 1px #ccc; text-align: left; } #image-gallery .sectiontwo dt { float: left; padding-top: 15px; padding-left: 10px; height: 70px; } #image-gallery .sectiontwo a dd { padding: 2px; margin: 2px 0; margin-left: 200px; background-color: #eee; text-indent: 0; } #image-gallery .sectiontwo a:hover dd { background-color: #ddd; } #image-gallery .sectiontwo .section h3 { padding-top: 15px; padding-left: 10px; } #image-gallery .section { border: 0 ; width: 550px; float: left; } #image-gallery .sectiontwo { border: 0 ; width: 550px; float: left; } #callout{ font-size: 14px; margin-top: 10px; background-color: #ACDEF4; padding: 5px 5px 5px 10px; } #calloutsuccess{ font-size: 14px; margin-top: 10px; color: #ffffff; background-color: #7AC142; padding: 5px 5px 5px 10px; } #calloutfailure{ font-size: 14px; margin-top: 10px; color: #ffffff; background-color: #E73E97; padding: 5px 5px 5px 10px; } #nymenable a { color: #7AC142; } #nymdisable a { color: #E73E97; } dl.dark { background-color: #2a2a2a !important; } dl.dark dt { background-color: #2a2a2a !important; } dl.dark a dd { background-color: #e83f98 !important; color: #fff; } dl.dark dd { background-color: #e83f98 !important; color: #fff; } .demo h4{ padding: 0; margin: 0; } .demo ul { margin: 0; padding: 0; padding-left: 2px; text-indent: 0px; color: #00209f; font-weight: normal; } .demo li { padding: 1px 0; list-style: none; } .demo li a { margin-left: 0px; text-indent: 0px; padding-left: 10px; background: url(/themes/sxip.com/icons/arrow.png) no-repeat 0 3px; } .demo ul ul li a{ background: url(/themes/sxip.com/icons/arrow2.png) no-repeat 1px 3px !important; } .demo li.phone { padding-left: 12px !important; background: url(/themes/sxip.com/icons/phone.png) no-repeat 0px 4px !important; } .demo li.email a { background: url(/themes/sxip.com/icons/mail.png) no-repeat -1px 1px !important; } .demo ul ul li a.current { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } .demo ul ul li a:hover { background: url(/themes/sxip.com/icons/arrow2fill.png) no-repeat 1px 3px !important; } openid4java-0.9.6.662/samples/demorp/www/images/0000755001501200150120000000000011627733442020620 5ustar miguelmiguelopenid4java-0.9.6.662/samples/demorp/www/images/login_openid_bg.gif0000644001501200150120000000035511205322251024410 0ustar miguelmiguelGIF89ai kļcfx)о!,j'dieH:ӺBG-FS&O!$ 8[`ApK Q('g%2) z)94#!;openid4java-0.9.6.662/samples/demorp/www/images/openid_information_cards_demo.png0000644001501200150120000001015511205322251027353 0ustar miguelmiguelPNG  IHDR%E pHYs  tEXtSoftwareAdobe ImageReadyqe<IDATx]uHnqh6s,G`mEp(CEp(EGV I'HX=!U'B-?"-||Uo2 ,KW8&Ȉ~}T)WuV8zL&P!+LC;t)~.skȑ=DKɕ2g}'iBC&w3=rp #IaatMsޣ0ygtlkqaX>˅Y[2JHNe'-M:6gk-X&~|m{m`Y$q!\ {HLc y*$? |^k/Ѿpg3Xf" Rb, LKlL[/I'(q]'И}?!Z @/BLNA^',mI:NLߥ1Z!]Db wA:eWJ-1:&&4]uq)z.[(@O"bI|nif-C3:9ڑ!5Ip*ߺk\ HX- *6=dk s RHKﺓt}HOJrL Ϲ# sJȰ}N drAKr4|OSlI6a _ `@m) sU 7憱=]wvBI}HR-m}<}e;?K&iz!C73ڳLkH'jNnMC>r&]mv qE@ir<<EK"v]MC`_L^7-Rh7 X̩Iy-as]!;&?Ҹ*+꛾2ED@aUBeBDzG>ٱc ;?f݁"i8&S}-PW"XECϩT-?ph?hU I)s g7d -کY „2H&'DIf+X74CHKBX \g3.Qk"g :66,HxfVyd88nս\%x-O0ĉ1lv/iQ͑j} {Z׎TpGpބX3cj=5;K[ 75~q$s(QbՇ9:2eK_fzV[!Ah#|˵t7'DwΖW>W12HxFUd'u~zI2g^R 7'd;`x{7嗩>7eCtBT(R<5RNbŁ&D/br}cMplD,Pi!@2.`%*iyR#j%kǵ=LZ?$~ۖ? X"{Ʋ'5&"Jl: ɳݘ W! K&,5?5s'm҉w/>2\ڌ1]5}v⍘fc17g~Z3(qaیq9Hzhƴ Pr~?NKѓr!wߨS~niXF/B&R?dDQ{WOY Md2 q亿c{|1衿]vbm#QDN`0X:}b(HUt|@,38ęh}[$3rCM9d ϖ>3˩GֿAև||v,p9u-؍E a44= ->OSah_M .+C!ySObqKDMc!;$ e1jm g'sF;@G= ~i{~h}A!םȱگ>|5Q#T(TѧB636,CT4g9Q].m\ 3"%M>=m ϵ^(k N o|"G2_n*6d;[Oؚg(8^fm3_ox,]F3iF+{1U_dXE %j K".@>s~*ئ^&NJ>>ZU`Z-`; (hAE"N#wK1F#d1>^ꠜj!y3l+|'95btG'<=U1މN ' x}RAyh[b! ^cgH1>fitbx:[v6DjYm wD4ptoE[F=e,/ hz㕊׻5}*2IK};ܓ:vLR~Q0{GvTo{`[' Gˉ#=˦l ҕpBGHt-)E op(C=mI#rpJCM tjXz4ynbI3y&Lg3M58 o{[aNhmWiok)s#^z]X ai,Km!MY_Uqt7<[g%@AO&# '>}h|'%"]ȳP;jcK68<2܊H{dg5/P:WA(}trkGJ\\DSՆ; 9P#De5/~&!poCe|&^4`S4!N8vxGXx B B _>W8IENDB`openid4java-0.9.6.662/samples/demorp/www/images/openid_infocard.png0000644001501200150120000000637211205322251024441 0ustar miguelmiguelPNG  IHDRxPқ pHYs  tEXtSoftwareAdobe ImageReadyqe< IDATx[lWk{kԎRu*JHE*VxJ< ^>! HH " /E%<@#/MJd!I:i|I%exvwvgfg֙ݙ#濟E-j~lty:H?n&p$L,i8}V(z*E=I _0k;%mxx8 vw[9v#vQҥK$ھGPr5ow _Ԛby&&& Je5S :urA>lkA#]vGV67(RakN$t'Y Lj:znV_0v**]fwpMh;+vvO#[p'㰩f7깩w:]KppdwA~ݍ&Nձ*v ճ% | "BwE޲0)*"tݰ0)*"gwlrQ2{XRpdwa6h8E%Lޝ*IQaQ ä;Lr܆w/7@kW.}.TyZ\R.U@q¤I9KNm+X!²L6P.v*r&) $nӁ[zzzOÓN/"p:P<%byb 1jVUdQ52Q"ܾ}BmO# #'IPrՠvk0gx| l`Wc_.VJΝ;~i__9GCT[n{Jo O, 3' u'-_x DJsHF- +5H<}KҐ 'Ӵ{Ik઀ECM+{œ߾};UvJ ul'(ǀ7GS߃oM.T !c]8{ʧ Ĥ+M`t=v +Joa6dwU@4`Zd^G{7TږVNattRգ$ş~ ._~ ?I`ᅗ.Q<}_|Ot;uxiP uv KZ_pklڲyҍD2ᩗh\}!ifl5L&@Bx(Y̯ST}SIﳏ/go"ǩ͎l0fp>fت,n-ҮT\JKY$'aQw#iR*\Wh3QsTծI'PTxݐĊf{i y4 ?kKUjgªY5Wh-]Yi {.݆^4c+xN!E0(lQ2Q$hԬL9]y-\EtM5@ɝ-QX}^CE IwM$S`yy!͛70+QU׼/K `ްa"&}Ur+r7C':bX7^%w=JS쨚aȈjCq]/^B^ B)Tѫ?,](Ju!x.IcyߴLR;?{x>uYDVBO/bx'pd8^~xVq9!)6EV_0)zQ ض4`;]x谼ÑGaM]$vq,W*_ɊnpKpؼ堂,S1lԳm݇aR6Xv30;UAVm(wm V`jp'PXRok =542N_/_z/L@\\vHzou_~qP>bDtmҟ(ӿa_%dSċ• 57w#vQPHmuX3a{"V}tHH *u DZ±zQH6t8A9m1"#a%։.] '%ÈbE1 3UlLi*BEX! yz6kIS=@`zMa`606d'u6X<). &,pypPcFy0<D].nc90d*~:6(`./3p'刺$Ő2rrl|u LiV:0r. L\\$<N"VF ԦQg ͝ V.r-i䟧?V]"8s!$,D+lk)awD L_HRfe*FN cb r1ʱpy%17<zRɔs,@t}"xVC5iPbpWYܔfRQ삲׵PF 2SrM\cjB,xe$D^i.l{f`s^0>h-rHZLHYI @T@dĸnHY<^2+I㙇Hޣ^a"i `}UX[h$؋ecFs`ʬE+sy*0Kk t:>*lIX<k[k Jt'y9é[۹@ey Hhr NM ^yJx#P^ O(ˎpո訊.r˞[`[0wyMt vJ.$>Zwѥ0q7ĥ׶3<3q $.>娑G/fؚ֊(8IJ 5[V )^W)Ơzhdx&h²8~ Et`qeV5ӹkpt%,N_1`^I_Dh~F!hU [_U2Ia" K oE.^zS˳589Jo8mg?fy FVtִۈ y{apre`%b:4k0j* Wvs_Kv^d@*<Ckyd O[V_'?*=KMVx0(8:`tTgy9xS-ڀ[0 0: eCpyꢳ 7NgX15{iF"ef]t(k31}n\4YW 8A8Cg<(V#?3~QsxL ^_mIhژEMJ/a0r8(^'4u NƗ 8#5s/r+epɸL1;2D'#HinfXNU`hsn@S&~hm&Ⱦ`&JV Z+,5w$kvL&4}|͋HGRLN 6ۤ]c53HuN6]'MJQY~H3A5Ta{ ?<F-3ܾ JNQb$hXuKۤ#$w,~KҊ8aw5F`EugZciS4x}8Mr t0'}!eE{+EM3= #RؑLlXܯ63kM$Dy9"aToh ~RgEQ{I>swCYrРܤ<`iIlADa6݀d1%WDvlfZ`]"; 0C$M̾_] %@yȔSJXe?hF7BM9m ._ކm ;ٻN Jg(iVm4M:bQ '3ܐ(%h```r6l`d0tʷXc@B (0_'Y1[% hj#M23}iٰaFgWN&LS{`nw,هqx)9Q:}ʆF}\3\O fTx #ƞba״#S4ESӎtz*Va)ZEdRZ RYd6D#)xW)Fե*RO≋;{CO MKۖM.6pI%{17aOD٦%Subbˉ$bf>QWg|&t8&%\ۘE!K:N?<~h_f6+} ~pIb+$zj2{7|~[ `)e!Ul t!Rir羝,/MK4?)jZPcډ7fQx2H c擯 0.`w:5\IENDB`openid4java-0.9.6.662/samples/demorp/www/images/logo.gif0000644001501200150120000000607511205322251022237 0ustar miguelmiguelGIF89aG&ю𖘚ɦ~!,G& $dihlp,tmx|pH,Ȥrl:ШtJ [J"^ : @ _"[c}'ce1\Ya V0cv;llM +HE|2  d#1/ ɓ8I %ҽE*\ =)qIࠡ].$r `4-t;`inKmH. {wsd;j4OHtp. z>I(xNdd ]  q p'Tĩ !(aHRGDAY_>`v;dfN6a:*lBt%Dk0HK܉-r]._|.ԙH4.B>n0N+l \07)l4Ob+z(L2'J|xƕ҅~:÷ufCRf{u Ûb+lQEtWCvAl &1y9De1O7 .z&0 *du,<*x=FE]PɊ|04HgΨ0 OwaG\]2\鎋{ 4N=+M" F7`m" %~0Y 7#%:chXtE g63`OvJ\p@#|:" 4ȷAx jG#yJ0!pOFRq0. !A".֛zEY(5|@qJQsDŽ*@Id aC4njL_ .s(iA7*<=23Bmnxw@L1G$&KX] X\bQQlB5r͍cI3{ ¬YX``GdCIgJRh\;>"';4%m0Ps'| ڂ*t,XSZ?-_A6 $K3_vHVEilo `+["wukN&nl%/U+O嵏ĉf C@r>^m }\N\PᒒJV1Pdyc|ČP+bO m'BgXQiu\m7U.wUQ>m{{3TpSkM:% G$FV:÷(+ne(_! W,s 5ҳn"]bx;D3;̆wd"*AW$wq0dVHFx̆UJ)@{L A YR ;R7]IH} U`PCvK|fBZjq1l#ю-sA9aǜAzS ,ǡbhCxBڳU–D Za:2أ(JȎ8MK@K09 1ͬ6KKDЦ4<.}LPee2uamkǑTxo8KK]6;~mT'A( d-~7!KMTѦpWVǹ6DH$Mѕ/6'ff #w !&.;)jcefm%}26S1@~pk:(dozR.8uQ?68 Ua0%i;E q` )kt &9Ř&,;|WFo=easВ>}~ӫ`r~}35_ߢ d8s ~pK)SB.a;p*0&>qR% o2$po Qoq!oQ,yX+D& o3^8* 0,-RM"gR3u,s84r.{gM/e+j(z:;D!xs?:0k^r$L4DbP%'O"}ؘVMX6Ix؎(!3T7|؏PfX8yXrِx zai qxg(09$Y&y1;openid4java-0.9.6.662/samples/demorp/DemoRP.iml0000644001501200150120000004456011205322261020352 0ustar miguelmiguel jar://$MODULE_DIR$/lib/commons-codec-1.3.jar!/ jar://$MODULE_DIR$/lib/commons-httpclient-3.0.1.jar!/ jar://$MODULE_DIR$/lib/commons-logging-1.03.jar!/ jar://$MODULE_DIR$/lib/htmlparser.jar!/ jar://$MODULE_DIR$/lib/icu4j_3_4_1.jar!/ jar://$MODULE_DIR$/lib/java-openid-sxip.jar!/ jar://$MODULE_DIR$/lib/jstl.jar!/ jar://$MODULE_DIR$/lib/jug-1.1.jar!/ jar://$MODULE_DIR$/lib/log4j-1.2.8.jar!/ jar://$MODULE_DIR$/lib/openxri-client.jar!/ jar://$MODULE_DIR$/lib/openxri-syntax.jar!/ jar://$MODULE_DIR$/lib/spring.jar!/ jar://$MODULE_DIR$/lib/standard.jar!/ jar://$MODULE_DIR$/lib/xmlsec-1.1.jar!/ openid4java-0.9.6.662/samples/demorp/INSTALL0000644001501200150120000000254711205322261017551 0ustar miguelmiguel... OpenID Demo RP - featuring Attribute Exchange and OpenID Infocards ======================================================================== INSTALLATION AND CONFIGURATION INSTRUCTIONS => Introduction: This document describes how to install, configure and use the sample OpenID Demo Relying Party. The Relying Party requires an OpenID Identifier for login; the identifier is requested and can be provided through either of the following two mechanisms: - the regular form-based text entry - using OpenID Information Cards => OpenID Infocard login The OpenID protocol transactions are enhanced with the use of a client-side (Information Card) Identity Selector, as described in: https://openidcards.sxip.com/spec/openid-infocards.html The Relying Party's login page contains an additional "application/x-informationCard" element (see www/WEB-INF/jsp/login.jsp). The Relying Party extracts the OpenID Authentication Response from the xmlToken parameter POST'ed by Identity Selector, after which point the regular OpenID (direct) verification is performed. => Configuration: www/WEB-INF/classes/config.properties : - base.url : The base URL (without the context path) where the RP will be deployed => Build and Installation: In the project's folder, run ant This will create a deployable dist/demo.war file. openid4java-0.9.6.662/openid4java.png0000644001501200150120000001103211140402641016464 0ustar miguelmiguelPNG  IHDR!igAMAOX2tEXtSoftwareAdobe ImageReadyqe<IDATxkl{X?p 6@UBiȗH($MihJFHU(*)I/"5 BKH%2`0x񣿝c_ٙV39;wg |AA$_|||A$$_||AA^{zzx6;BB}R"ׯ_'l嚔Adի)ꢢ.M-tjk0 ]tŋǴ# *++},iood\ PI&ỳDpkkkxJЊ*t5hmmMgW~xhEZA;wB'c)}ISg+=J-;yNkڴi0D $}%cXTuuh).&=]fp,!>}z2 3g8T q`H ֋sϐꈱ9 8Cx&hΌd{$)9BD4xOZqJHGe4qk2SJ@r*Ke'Ar K|qr$.F:::Z[[mv1cF: Q:uʞmS\6;s $>d_yr, x0s$ϭ`GB@iLd[ZZ Mr !'8uvv=۾9~nƚI5UEA.} 2pٸĆVTTy3:\;tJq ]9h.vu[>wX8o]tQ.Qf5BS|3>}L]??,THnu؍1N{熕Kf555e)'N~/.{kϿ?9y6϶*->E,H8ЦhQϬg/0n r{O<S! 74:c~h L7{DK-7lƥ1zT! [vP"aO. s\#NfoO6 dе)۲Bh97tʙ -}H7 ON6vzg8mA, 1lN`1@RCOLqqfա@Yx~~i5xaMKCԔzES~f 1'5']>b ;Ǥ}4,UO(QKQMTm=1elT#NڬL;\ݻT1Ӈۡ>ݩ$Qt8V6bb6ePE,єbnC66O0lE`oV`o\Eģ1㐼'E oğEiڅ7`L "~c`4sD}N5W!'iQF>WS=_we1S*y1'XSy*0lwx!$2 Xܘ XŽhs1pV #iORlހJMU̱х5ɤ)Që2<{k<{-1V/j~1hś%PIEs@T5 Ad[#庚sKoN+/6+R{ˢjsSSγ"UuӄsAqY҆a#L: Y$Ph.4Sݩ2$1uDJ0"Y5#!z<{!*T+ڎ@Rz@L:,N3sɆN)R5-I1- l5o>N@HŨg/ 1C@@:˙䊢fO8Iaa2^:9;\;Ɂ4 '(™҈R4уM%f4 .)SME Ts Y7f#e4,5m@}H6'|H]@ˉg:LSgN׳dJ1oUVy㧎)=)nʽ@([].{FH67ru܉-{iyR@cm(o$*y 9܋U&}E/1PEpS$[ސI$?~^yS[~<_+^N9=z-7?q?@hlp2TzR@p?.ZrķA-WGќLzC ,U" EgH248\eee,a'?kI{Ex(|m@HNRxh5 ~⠑EK^-0$jAɕg̕C.:6H}=0HyrTu7^3.K$Gri  ̆ 6 U4H6O8wߟ0޸[ ZYbb.-Si^B"|pBePWs){4Õ8cJ r9I0[^} GGڭ z$8W, 4Br!xQ92+;@B, )0Fabw!H}=ƽ"p[$iHHso#XMͳazT(g#z6QfMUdʍ='HUeo~\6G-e(ڜ@%Z]~Sl8Hac݃UqV;RBj.. ?B#;|Րd*ݷHv(2VХԂp0%@r"A7l7rI]i~$ۓ>H1NӧOOOܓ!,ۯ+b8'M E0Q Czh\[[ʔ)94pI&M81IY6>HО7mڴ]J@nz@mN,dARUfVM y@=! Z &zҰAkⰜɭ7Z@iiipq`.el@RxR@ť&AAˠ TTThЮkӸ\*3ͻ_7D?2Hʥ_B#k^*3 )n( ~ْ2 3#^+If(I@2<9=.g{$E+41-<[ "vk;yd#(H! %I`E df;KgrBAz5AJzRj%Vs %|)M'.H%GꤎlJ4@ />H />H>H ⃔޶zIENDB`openid4java-0.9.6.662/INSTALL0000644001501200150120000003262411202057712014621 0ustar miguelmiguel.... OpenID4Java Library - INSTALL ======================================================================== INSTALLATION AND USAGE INSTRUCTIONS Introduction: This document describes how to install and use the OpenID4Java library. For general information about the package please see the README document. Requirements: - Java 1.5 JVM (or higher) - Ant (optional: needed for building the package and running the tests) - Maven2 (optional: alternative to Ant; see maven2/README.txt) - JUnit (optional: needed for running the tests) Installation: 1. Installing the package => To make the OpenID4Java library available to a (web) application the following JAR files need to be copied to the application's classpath: - openid4java-*.jar - library dependencies (see below) => Library dependencies: lib/*jar : Required. Core OpenID4Java library dependencies. lib/optional/ : Optional. Libraries supporting alternative deployments. - spring-*.jar : JdbcServerAssociationStore - ehcache-1.2.4.jar : EhcacheNonceVerifier - log4j-1.2.8.jar lib/extra/ : Extra/development libraries, not needed for deployments. (JUnit tests, Jetty servlet container, SVN/Ant utilities) lib/xri/ : Optional. Local OpenXRI resolver dependencies. Included only in the "openid4java-xri" and "openid4java-full" packages. (A dependency-less proxy XRI resolver is included in the standard package) lib/infocard/ : Optional. OpenID-Infocards/Higgins STS dependencies. Included only in the "openid4java-infocard" and "openid4java-full" packages. => Relying Party Discovery: Relying Parties must publish their endpoints in order for the OpenID Providers to be able to verify authentication requests and prevent proxy attacks. The Yadis protocol and realm verification mechanisms are used for this purpose. See the section "Discovering OpenID Relying Parties" of the OpenID Authentication specification for details. Example: http://specs.openid.net/auth/2.0/return_to http://consumer.example.com/return The RP should publish the above element at their realm URL. All OpenID Authentication request sent by this RP should contain openid.return_to values matching the http://consumer.example.com/return realm. OpenID Providers: Validation of openid.return_to values against Relying Party Discovery endpoints is enabled by default. This feature can be disabled with ServerManager.setEnforceRpId(false). => Java 1.4 compatibility The official OpenID4Java distribution is compiled with a Java 1.5 compiler. The source, however, can be compiled with Java 1.4. See the "Building the package" section below. 2. OPTIONAL: Configuring logging OpenID4Java uses Apache's commons-logging API. This allows the application developers to choose (or change) their preferred logging implementations, without the need to modify or recompile the library. http://commons.apache.org/logging/guide.html#Configuration => Log4J configuration Log4J v1.2 is used as the logging implementation for the sample projects included with the OpenID4Java library. Commons-logging uses Log4J as the primary default and automatically detects if Log4J is available when discoverying available logging implementations. A typical way to configure Log4J is using a log4j.properties file in the classpath which should contain the following (adjust log levels as desired): log4j.rootLogger=INFO, A1 log4j.logger.org.openid4java=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout http://logging.apache.org/log4j/1.2/ 3. OPTIONAL: Enabling 256bit cryptographic support => Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Download and install (under JAVA_HOME/jre/lib/security) the JCE unlimited strength policy files, usually distributed along with JVMs (but not included in standard packages). SUN's Java JCE policy files can be found as separate downloads at the following URLs: http://java.sun.com/javase/downloads/index_jdk5.jsp => Third party libraries Third party libraries that provide unlimited strength JCE implementations can also be used. One such library is provided by Bouncy Castle: http://www.bouncycastle.org/java.html 4. OPTIONAL: Building the package To build the package from source Ant is also needed. The following build targets are provided: - Packages compiled class files into a JAR archive ant jar - Builds official distributable archive ant dist 5. OPTIONAL: Testing the package JUnit test classes and data files are found under the test/ folder. JUnit and Ant are needed for running the tests: A servlet is provided for generating custom OpenID URIs and the HTTP responses needed during discovery. The servlet is run inside the lightweight Jetty servlet container. - To run the tests execute the following Ant target: ant test Alternatively, if Ant is not used, the following need to be configured: - The port on which the servlet will listen SERVLET_PORT system property - The path where the test data is available to the servlet TEST_DATA system property The test data files need to be updated with the actual servlet port, which is part of the YadisURLs API Usage and Examples: Following is the general usage pattern of the library. => NOTE: For extended usage see the JavaDoc API documentation under apidoc/ The main interaction points between a web application acting as a Relying Party (Consumer) and the library are the Discovery and ConsumerManager classes. See also the SampleConsumer.java implementation in the consumer package. // instantiate a ConsumerManager object public static manager = new ConsumerManager(); // --- placing the authentication request --- // determine a return_to URL where your application will receive // the authentication responses from the OpenID provider String returnToUrl = "http://example.com/openid"; // perform discovery on the user-supplied identifier List discoveries = manager.discover(userSuppliedString); // attempt to associate with an OpenID provider // and retrieve one service endpoint for authentication DiscoveryInformation discovered = manager.associate(discoveries); // store the discovery information in the user's session session.setAttribute("openid-disco", discovered); // Attribute Exchange example: fetching the 'email' attribute FetchRequest fetch = new FetchRequest(); fetch.addAttribute("email", // attribute alias "http://schema.openid.net/contact/email", // type URI true); // required // obtain a AuthRequest message to be sent to the OpenID provider AuthRequest authReq = manager.authenticate(discovered, returnToUrl); // attach the extension to the authentication request authReq.addExtensionParams(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 to 255 bytes return authReq.getRedirectUrl(); } else { // Option 2: HTML FORM Redirection // Allows payloads > 255 bytes //
// see samples/formredirection.jsp for a JSP example authReq.getOPEndpoint(); // build a HTML FORM with the message parameters authReq.getParameterMap(); } // --- processing the authentication response // 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) session.getAttribute("openid-disco"); // verify the response; ConsumerManager needs to be the same // (static) instance used to place the authentication request VerificationResult verification = manager.verify( httpReq.getRequestURL().toString(), response, discovered); // examine the verification result and extract the verified identifier Identifier verified = verification.getVerifiedId(); if (verified != null) { // Attribute Exchange: retrieving the fetched "email" attribute AuthSuccess authSuccess = AuthSuccess.createAuthSuccess(response); MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX); if (ext != null) { FetchResponse fetchResp = new FetchResponse(ext.getParameters()); String email = fetchResp.getParameter("email"); } return verified; // success } The main interaction point between a web application acting as a OpenID Provider (Server) and the library is the ServerManager class. See also the SampleServer.java implementation in the server package. // instantiate a ServerManager object public static ServerManager manager = new ServerManager(); // configure the OpenID Provider's endpoint URL static { manager.setOPEndpointUrl("Http://my.openidprovider.com/server"); } // extract the parameters from the request ParameterList request = new ParameterList(httpReq.getParameterMap()); String mode = request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null; Message response; String responseText; if ("associate".equals(mode)) { // --- process an association request --- response = manager.associationResponse(request); responseText = response.keyValueFormEncoding(); } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) { // interact with the user and obtain data needed to continue List userData = userInteraction(request); String userSelectedId = (String) userData.get(0); String userSelectedClaimedId = (String) userData.get(1); Boolean authenticatedAndApproved = (Boolean) userData.get(2); // --- process an authentication request --- response = manager.authResponse(request, userSelectedId, userSelectedClaimedId, authenticatedAndApproved.booleanValue()); // caller will need to decide which of the following to use: // - GET HTTP-redirect to the return_to URL // - HTML FORM Redirection responseText = response.wwwFormEncoding(); } else if ("check_authentication".equals(mode)) { // --- processing a verification request --- response = manager.verify(request); responseText = response.keyValueFormEncoding(); } else { // --- error response --- response = DirectError.createDirectError("Unknown request"); responseText = response.keyValueFormEncoding(); } // return the result to the user return responseText; Contacts: If you want freely available support, to participate in active development, and to be informed about new code releases, bug fixes, security fixes, general news and information about the OpenID4Java Library, subscribe to the Google Group at: http://groups.google.com/group/openid4java If you want commercial support for running the OpenID4Java Library, please contact: bizdev@sxip.com If you find a bug in the OpenID4Java Library please submit a defect in the tracking database after verifying that it hasn't already been submitted. http://code.google.com/p/openid4java/issues/list Thanks for running OpenID! The Sxip Team -- http://sxip.com ======================================================================== Copyright 2006-2008 Sxip Identity Corporation Project home page and package distribution: => http://code.google.com/p/openid4java => http://code.google.com/p/openid4java/downloads/ For support, please visit the wiki and join the Google Groups! => http://groups.google.com/group/openid4java/ => http://code.google.com/p/openid4java/w/ OpenID => http://openid.net/ Released under the Apache License 2.0 => see LICENSE openid4java-0.9.6.662/openid4java_checks.xml0000644001501200150120000001636711504002570020041 0ustar miguelmiguel openid4java-0.9.6.662/TODO0000644001501200150120000000252611202131611014245 0ustar miguelmiguel.... OpenID4Java Library - TODO ======================================================================== => Documentation and Packaging - Complete JavaDocs => Tests => Samples - Sample code - Documentation => Implementation - Extensions to implement: - OpenID Signed Assertions 1.0 - MessageExtension.providesIdentifier() - review interface to allow exchange of messages with no identifiers at all - review affected message validation logic - Compatibility mode - check/enforce limits defined in v1 --> Nice to have, but not essential: - Auth* class hierarchy reorganization - Factory method for incoming messages - Review consumer verification flow - Interface for saving discovered information - into session, db, url/return_to, etc. - saveDiscoveryInfo(... , session, return_to) - loadDiscoveryInfo(httpRequest) - Extension Builder interface ======================================================================== Copyright 2006-2008 Sxip Identity Corporation Package distribution: => http://code.sxip.com Source code and defect management: => http://code.google.com/p/openid4java For support, please join the Google Groups! => http://groups.google.com/group/openid4java OpenID => http://openid.net Released under the Apache License 2.0 => see LICENSE openid4java-0.9.6.662/README0000644001501200150120000000541611205322264014447 0ustar miguelmiguel.... OpenID4Java Library - README ======================================================================== What is this package? OpenID4Java is a Java Library originally developed by Sxip Identity, licensed under Apache 2.0. The library currently supports the following OpenID specifications: - OpenID Authentication 2.0 - OpenID Attribute Exchange 1.0 - OpenID Simple Registration 1.0 and 1.1 - OpenID Provider Authentication Policy Extension 1.0 - OpenID Information Cards 1.0, draft 1 OpenID starts with the concept that anyone can identify themselves on the Internet the same way websites do - with a URI. Since URIs are at the very core of Web architecture, they provide a solid foundation for user-centric identity. The first piece of the OpenID framework is authentication -- how you prove ownership of a URI. Today, websites require usernames and passwords to login, which means that many people use the same password everywhere. With OpenID Authentication, your username is your URI, and your password (or other credentials) stays safely stored on your OpenID Provider (which you can run yourself, or use a third-party identity provider). For more information about the OpenID protocol please refer to the specification at: http://openid.net/developers/specs/ The Latest Version: Details of the latest version can be found on the OpenID4Java library distribution project page at: http://code.google.com/p/openid4java/downloads/ Package contents: CHANGELOG : Version highlight changes. INSTALL : Installation and usage instructions. LICENSE : OpenID4Java Library license (Apache 2.0). MAINTAINERS : List of code and documentation maintainers. README : This file! TODO : Tasks remaining and/or ongoing. VERSION : The released version of this package. apidoc/ : JavaDoc API documentation. samples/ : Sample implementation projects. See samples/README for details. src/ : Source code. test/ : Test cases source code and test data. lib/ : Library dependencies. See INSTALL / Installing the package for details. build.xml : Ant build file; see INSTALL / Building the package. project.properties maven2/ : Maven2 build scripts; see maven2/README.txt. ======================================================================== Copyright 2006-2008 Sxip Identity Corporation Project home page and package distribution: => http://code.google.com/p/openid4java => http://code.google.com/p/openid4java/downloads/ For support, please visit the wiki and join the Google Groups! => http://groups.google.com/group/openid4java/ => http://code.google.com/p/openid4java/w/ OpenID => http://openid.net/ Released under the Apache License 2.0 => see LICENSE