org.openid4java.discovery.DiscoveryInformation Java Examples

The following examples show how to use org.openid4java.discovery.DiscoveryInformation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #2
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: YadisResult.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #4
Source File: ConsumerManagerTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public void testPerferredAssociation() throws Exception {
	manager.setPrefAssocSessEnc(AssociationSessionType.DH_SHA1);
	DiscoveryInformation disc = new DiscoveryInformation(new URL(server.createAbsoluteUrl("/op/endpoint")), null);
	DiscoveryInformation info = manager.associate(Collections.singletonList(disc));
	assertEquals(1,server.getRequestParams().size());
	Map request = (Map)server.getRequestParams().get(0);
	assertEquals(manager.getPrefAssocSessEnc().getAssociationType(),((String[])request.get("openid.assoc_type"))[0]);
	assertEquals(manager.getPrefAssocSessEnc().getSessionType(),((String[])request.get("openid.session_type"))[0]);
}
 
Example #5
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #6
Source File: LocalXriResolver.java    From openid4java with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: OpenIdConsumer.java    From jerseyoauth2 with MIT License 4 votes vote down vote up
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(OpenIdConstants.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);
				
				httpReq.getSession().setAttribute(OpenIdConstants.OPENID_SESSION_VAR, new OpenIDUser(email));
			}

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

	return null;
}
 
Example #8
Source File: OpenIdConsumer.java    From jerseyoauth2 with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void authRequest(String openidServiceId, String returnToUrl, HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException, ServletException {
	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(openidServiceId);

		// 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(OpenIdConstants.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));
		} else {
			// Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

			sendFormRedirect(httpResp, authReq.getDestinationUrl(false), (Map<String,String>)authReq.getParameterMap());
		}
	} catch (OpenIDException e) {
		e.printStackTrace(System.err);
	}

}
 
Example #9
Source File: LoggedInSessionBean.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public void setDiscoveryInformation(DiscoveryInformation discoveryInformation) {
    this.discoveryInformation = discoveryInformation;
}
 
Example #10
Source File: LoggedInSessionBean.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public DiscoveryInformation getDiscoveryInformation() {
    return discoveryInformation;
}
 
Example #11
Source File: SSOAgentSessionBean.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public void setDiscoveryInformation(DiscoveryInformation discoveryInformation) {
    this.discoveryInformation = discoveryInformation;
}
 
Example #12
Source File: SSOAgentSessionBean.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public DiscoveryInformation getDiscoveryInformation() {
    return discoveryInformation;
}
 
Example #13
Source File: ConsumerServlet.java    From openid4java with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #14
Source File: ConsumerServlet.java    From openid4java with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #15
Source File: IndexController.java    From openid4java with Apache License 2.0 4 votes vote down vote up
private ModelAndView buildFetchReq(String identifier, HttpSession session, String return_to)
    throws OpenIDException
{
    _logger.info("Building auth + fetch request for: " + identifier);

    Map<String,Object> model = new HashMap<String,Object>();
    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 = "<br /><br /><em>" + e.getMessage() + "</em>";
    }

    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);
}
 
Example #16
Source File: XrdsParserTest.java    From openid4java with Apache License 2.0 4 votes vote down vote up
public void testXrdsParse() throws Exception
{
    XrdsParser parser = new XrdsParserImpl();
    parser.parseXrds(XRD, DiscoveryInformation.OPENID_OP_TYPES);
}
 
Example #17
Source File: SampleConsumer.java    From openid4java with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #18
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example #19
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 4 votes vote down vote up
/**
 * Performs verification on the Authentication Response (assertion)
 * received from the OpenID Provider.
 * <p>
 * Three verification steps are performed:
 * <ul>
 * <li> nonce:                  the same assertion will not be accepted more
 *                              than once
 * <li> signatures:             verifies that the message was indeed sent
 *                              by the OpenID Provider that was contacted
 *                              earlier after discovery
 * <li> discovered information: the information contained in the assertion
 *                              matches the one obtained during the
 *                              discovery (the OpenID Provider is
 *                              authoritative for the claimed identifier;
 *                              the received assertion is not meaningful
 *                              otherwise
 * </ul>
 *
 * @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.");

    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));
}
 
Example #20
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 4 votes vote down vote up
/**
 * 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. <br>
 *                          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). <br>
 *                          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;
}
 
Example #21
Source File: SampleConsumer.java    From openid4java with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #22
Source File: YadisResolver.java    From openid4java with Apache License 2.0 3 votes vote down vote up
/**
 * Performs Yadis discovery on the YadisURL.
 * <p>
 * <ul>
 * <li> tries to retrieve the XRDS location via a HEAD call on the Yadis URL
 * <li> retrieves the XRDS document with a GET on the above if available,
 *      or through a GET on the YadisURL otherwise
 * </ul>
 *
 * @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);
}
 
Example #23
Source File: YadisResolver.java    From openid4java with Apache License 2.0 3 votes vote down vote up
/**
 * 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));
}
 
Example #24
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 3 votes vote down vote up
/**
 * 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. <br>
 *                          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). <br>
 *                          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);
}
 
Example #25
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 3 votes vote down vote up
/**
 * Builds a authentication request message for the user specified in the
 * discovery information provided as a parameter.
 * <p>
 * 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. <br>
 *                          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). <br>
 *                          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);
}