Java Code Examples for org.openid4java.discovery.DiscoveryInformation#isVersion2()

The following examples show how to use org.openid4java.discovery.DiscoveryInformation#isVersion2() . 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: 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 2
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 3
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 4
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 5
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);
	}

}