org.openid4java.OpenIDException Java Examples

The following examples show how to use org.openid4java.OpenIDException. 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: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }

}
 
Example #2
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #3
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #4
Source File: CyberNekoDOMHtmlParser.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #6
Source File: PapeRequest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the validity of the extension.
 * <p>
 * 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);
        }
    }
}
 
Example #7
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #8
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #9
Source File: DirectError.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #11
Source File: CyberNekoDOMYadisHtmlParser.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #12
Source File: VerifyRequest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: YadisResolver.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: IndirectError.java    From openid4java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: YadisResolver.java    From openid4java with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
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 #17
Source File: HtmlResolver.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: YadisUrl.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);

}
 
Example #19
Source File: YadisUrl.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #20
Source File: YadisResolver.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #21
Source File: CyberNekoDOMHtmlParser.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #22
Source File: ConsumerManager.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #23
Source File: AuthFailure.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #24
Source File: YadisResolverTest.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #25
Source File: AuthImmediateFailure.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: AssociationError.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #27
Source File: DirectError.java    From openid4java with Apache License 2.0 5 votes vote down vote up
protected DirectError(OpenIDException e, String msg, boolean compatibility)
{
    set("error", msg);
    _exception = e;

    if ( ! compatibility )
        set("ns", OPENID2_NS);
}
 
Example #28
Source File: InfocardOPController.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source File: VerifyResponse.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #30
Source File: IndirectError.java    From openid4java with Apache License 2.0 5 votes vote down vote up
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);
}