Search in sources :

Example 6 with MessageException

use of org.openid4java.message.MessageException in project spring-security by spring-projects.

the class OpenID4JavaConsumer method beginConsumption.

// ~ Methods
// ========================================================================================================
public String beginConsumption(HttpServletRequest req, String identityUrl, String returnToUrl, String realm) throws OpenIDConsumerException {
    List<DiscoveryInformation> discoveries;
    try {
        discoveries = consumerManager.discover(identityUrl);
    } catch (DiscoveryException e) {
        throw new OpenIDConsumerException("Error during discovery", e);
    }
    DiscoveryInformation information = consumerManager.associate(discoveries);
    req.getSession().setAttribute(DISCOVERY_INFO_KEY, information);
    AuthRequest authReq;
    try {
        authReq = consumerManager.authenticate(information, returnToUrl, realm);
        logger.debug("Looking up attribute fetch list for identifier: " + identityUrl);
        List<OpenIDAttribute> attributesToFetch = attributesToFetchFactory.createAttributeList(identityUrl);
        if (!attributesToFetch.isEmpty()) {
            req.getSession().setAttribute(ATTRIBUTE_LIST_KEY, attributesToFetch);
            FetchRequest fetchRequest = FetchRequest.createFetchRequest();
            for (OpenIDAttribute attr : attributesToFetch) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Adding attribute " + attr.getType() + " to fetch request");
                }
                fetchRequest.addAttribute(attr.getName(), attr.getType(), attr.isRequired(), attr.getCount());
            }
            authReq.addExtension(fetchRequest);
        }
    } catch (MessageException e) {
        throw new OpenIDConsumerException("Error processing ConsumerManager authentication", e);
    } catch (ConsumerException e) {
        throw new OpenIDConsumerException("Error processing ConsumerManager authentication", e);
    }
    return authReq.getDestinationUrl(true);
}
Also used : AuthRequest(org.openid4java.message.AuthRequest) MessageException(org.openid4java.message.MessageException) DiscoveryInformation(org.openid4java.discovery.DiscoveryInformation) FetchRequest(org.openid4java.message.ax.FetchRequest) ConsumerException(org.openid4java.consumer.ConsumerException) DiscoveryException(org.openid4java.discovery.DiscoveryException)

Example 7 with MessageException

use of org.openid4java.message.MessageException in project spring-security by spring-projects.

the class OpenID4JavaConsumer method fetchAxAttributes.

List<OpenIDAttribute> fetchAxAttributes(Message authSuccess, List<OpenIDAttribute> attributesToFetch) throws OpenIDConsumerException {
    if (attributesToFetch == null || !authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        return Collections.emptyList();
    }
    logger.debug("Extracting attributes retrieved by attribute exchange");
    List<OpenIDAttribute> attributes = Collections.emptyList();
    try {
        MessageExtension ext = authSuccess.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchResponse) {
            FetchResponse fetchResp = (FetchResponse) ext;
            attributes = new ArrayList<OpenIDAttribute>(attributesToFetch.size());
            for (OpenIDAttribute attr : attributesToFetch) {
                List<String> values = fetchResp.getAttributeValues(attr.getName());
                if (!values.isEmpty()) {
                    OpenIDAttribute fetched = new OpenIDAttribute(attr.getName(), attr.getType(), values);
                    fetched.setRequired(attr.isRequired());
                    attributes.add(fetched);
                }
            }
        }
    } catch (MessageException e) {
        throw new OpenIDConsumerException("Attribute retrieval failed", e);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved attributes" + attributes);
    }
    return attributes;
}
Also used : MessageExtension(org.openid4java.message.MessageExtension) MessageException(org.openid4java.message.MessageException) FetchResponse(org.openid4java.message.ax.FetchResponse)

Example 8 with MessageException

use of org.openid4java.message.MessageException in project spring-security by spring-projects.

the class OpenID4JavaConsumerTests method messageExceptionFetchingAttributesRaisesOpenIDException.

@Test(expected = OpenIDConsumerException.class)
public void messageExceptionFetchingAttributesRaisesOpenIDException() throws Exception {
    OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory());
    Message msg = mock(Message.class);
    FetchResponse fr = mock(FetchResponse.class);
    when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true);
    when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenThrow(new MessageException(""));
    when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x", "y"));
    consumer.fetchAxAttributes(msg, attributes);
}
Also used : AxMessage(org.openid4java.message.ax.AxMessage) Message(org.openid4java.message.Message) MessageException(org.openid4java.message.MessageException) FetchResponse(org.openid4java.message.ax.FetchResponse)

Example 9 with MessageException

use of org.openid4java.message.MessageException in project gerrit by GerritCodeReview.

the class OpenIdServiceImpl method doAuth.

/** Called by {@link OpenIdLoginServlet} doGet, doPost */
void doAuth(final HttpServletRequest req, final HttpServletResponse rsp) throws Exception {
    if (OMODE_CANCEL.equals(req.getParameter(OPENID_MODE))) {
        cancel(req, rsp);
        return;
    }
    // Process the authentication response.
    //
    final SignInMode mode = signInMode(req);
    final String openidIdentifier = req.getParameter("openid.identity");
    final String claimedIdentifier = req.getParameter(P_CLAIMED);
    final String returnToken = req.getParameter(P_TOKEN);
    final boolean remember = "1".equals(req.getParameter(P_REMEMBER));
    final String rediscoverIdentifier = claimedIdentifier != null ? claimedIdentifier : openidIdentifier;
    final State state;
    if (!isAllowedOpenID(rediscoverIdentifier) || !isAllowedOpenID(openidIdentifier) || (claimedIdentifier != null && !isAllowedOpenID(claimedIdentifier))) {
        cancelWithError(req, rsp, "Provider not allowed");
        return;
    }
    state = init(req, rediscoverIdentifier, mode, remember, returnToken);
    if (state == null) {
        // Re-discovery must have failed, we can't run a login.
        //
        cancel(req, rsp);
        return;
    }
    final String returnTo = req.getParameter("openid.return_to");
    if (returnTo != null && returnTo.contains("openid.rpnonce=")) {
        // Some providers (claimid.com) seem to embed these request
        // parameters into our return_to URL, and then give us them
        // in the return_to request parameter. But not all.
        //
        state.retTo.put("openid.rpnonce", req.getParameter("openid.rpnonce"));
        state.retTo.put("openid.rpsig", req.getParameter("openid.rpsig"));
    }
    final VerificationResult result = manager.verify(state.retTo.toString(), new ParameterList(req.getParameterMap()), state.discovered);
    if (result.getVerifiedId() == null) /* authentication failure */
    {
        if ("Nonce verification failed.".equals(result.getStatusMsg())) {
            // We might be suffering from clock skew on this system.
            //
            log.error("OpenID failure: " + result.getStatusMsg() + "  Likely caused by clock skew on this server," + " install/configure NTP.");
            cancelWithError(req, rsp, result.getStatusMsg());
        } else if (result.getStatusMsg() != null) {
            // Authentication failed.
            //
            log.error("OpenID failure: " + result.getStatusMsg());
            cancelWithError(req, rsp, result.getStatusMsg());
        } else {
            // Assume authentication was canceled.
            //
            cancel(req, rsp);
        }
        return;
    }
    final Message authRsp = result.getAuthResponse();
    SRegResponse sregRsp = null;
    FetchResponse fetchRsp = null;
    if (0 <= papeMaxAuthAge) {
        PapeResponse ext;
        boolean unsupported = false;
        try {
            ext = (PapeResponse) authRsp.getExtension(PapeMessage.OPENID_NS_PAPE);
        } catch (MessageException err) {
            // Far too many providers are unable to provide PAPE extensions
            // right now. Instead of blocking all of them log the error and
            // let the authentication complete anyway.
            //
            log.error("Invalid PAPE response " + openidIdentifier + ": " + err);
            unsupported = true;
            ext = null;
        }
        if (!unsupported && ext == null) {
            log.error("No PAPE extension response from " + openidIdentifier);
            cancelWithError(req, rsp, "OpenID provider does not support PAPE.");
            return;
        }
    }
    if (authRsp.hasExtension(SRegMessage.OPENID_NS_SREG)) {
        final MessageExtension ext = authRsp.getExtension(SRegMessage.OPENID_NS_SREG);
        if (ext instanceof SRegResponse) {
            sregRsp = (SRegResponse) ext;
        }
    }
    if (authRsp.hasExtension(AxMessage.OPENID_NS_AX)) {
        final MessageExtension ext = authRsp.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchResponse) {
            fetchRsp = (FetchResponse) ext;
        }
    }
    final com.google.gerrit.server.account.AuthRequest areq = new com.google.gerrit.server.account.AuthRequest(ExternalId.Key.parse(openidIdentifier));
    if (sregRsp != null) {
        areq.setDisplayName(sregRsp.getAttributeValue("fullname"));
        areq.setEmailAddress(sregRsp.getAttributeValue("email"));
    } else if (fetchRsp != null) {
        final String firstName = fetchRsp.getAttributeValue("FirstName");
        final String lastName = fetchRsp.getAttributeValue("LastName");
        final StringBuilder n = new StringBuilder();
        if (firstName != null && firstName.length() > 0) {
            n.append(firstName);
        }
        if (lastName != null && lastName.length() > 0) {
            if (n.length() > 0) {
                n.append(' ');
            }
            n.append(lastName);
        }
        areq.setDisplayName(n.length() > 0 ? n.toString() : null);
        areq.setEmailAddress(fetchRsp.getAttributeValue("Email"));
    }
    if (openIdDomains != null && openIdDomains.size() > 0) {
        // Administrator limited email domains, which can be used for OpenID.
        // Login process will only work if the passed email matches one
        // of these domains.
        //
        final String email = areq.getEmailAddress();
        int emailAtIndex = email.lastIndexOf("@");
        if (emailAtIndex >= 0 && emailAtIndex < email.length() - 1) {
            final String emailDomain = email.substring(emailAtIndex);
            boolean match = false;
            for (String domain : openIdDomains) {
                if (emailDomain.equalsIgnoreCase(domain)) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                log.error("Domain disallowed: " + emailDomain);
                cancelWithError(req, rsp, "Domain disallowed");
                return;
            }
        }
    }
    if (claimedIdentifier != null) {
        // The user used a claimed identity which has delegated to the verified
        // identity we have in our AuthRequest above. We still should have a
        // link between the two, so set one up if not present.
        //
        Optional<Account.Id> claimedId = accountManager.lookup(claimedIdentifier);
        Optional<Account.Id> actualId = accountManager.lookup(areq.getExternalIdKey().get());
        if (claimedId.isPresent() && actualId.isPresent()) {
            if (claimedId.get().equals(actualId.get())) {
            // Both link to the same account, that's what we expected.
            } else {
                // This is (for now) a fatal error. There are two records
                // for what might be the same user.
                //
                log.error("OpenID accounts disagree over user identity:\n" + "  Claimed ID: " + claimedId.get() + " is " + claimedIdentifier + "\n" + "  Delgate ID: " + actualId.get() + " is " + areq.getExternalIdKey());
                cancelWithError(req, rsp, "Contact site administrator");
                return;
            }
        } else if (!claimedId.isPresent() && actualId.isPresent()) {
            // Older account, the actual was already created but the claimed
            // was missing due to a bug in Gerrit. Link the claimed.
            //
            final com.google.gerrit.server.account.AuthRequest linkReq = new com.google.gerrit.server.account.AuthRequest(ExternalId.Key.parse(claimedIdentifier));
            linkReq.setDisplayName(areq.getDisplayName());
            linkReq.setEmailAddress(areq.getEmailAddress());
            accountManager.link(actualId.get(), linkReq);
        } else if (claimedId.isPresent() && !actualId.isPresent()) {
            // Claimed account already exists, but it smells like the user has
            // changed their delegate to point to a different provider. Link
            // the new provider.
            //
            accountManager.link(claimedId.get(), areq);
        } else {
        // Both are null, we are going to create a new account below.
        }
    }
    try {
        final com.google.gerrit.server.account.AuthResult arsp;
        switch(mode) {
            case REGISTER:
            case SIGN_IN:
                arsp = accountManager.authenticate(areq);
                final Cookie lastId = new Cookie(OpenIdUrls.LASTID_COOKIE, "");
                lastId.setPath(req.getContextPath() + "/login/");
                if (remember) {
                    lastId.setValue(rediscoverIdentifier);
                    lastId.setMaxAge(LASTID_AGE);
                } else {
                    lastId.setMaxAge(0);
                }
                rsp.addCookie(lastId);
                webSession.get().login(arsp, remember);
                if (arsp.isNew() && claimedIdentifier != null) {
                    final com.google.gerrit.server.account.AuthRequest linkReq = new com.google.gerrit.server.account.AuthRequest(ExternalId.Key.parse(claimedIdentifier));
                    linkReq.setDisplayName(areq.getDisplayName());
                    linkReq.setEmailAddress(areq.getEmailAddress());
                    accountManager.link(arsp.getAccountId(), linkReq);
                }
                callback(arsp.isNew(), req, rsp);
                break;
            case LINK_IDENTIY:
                {
                    arsp = accountManager.link(identifiedUser.get().getAccountId(), areq);
                    webSession.get().login(arsp, remember);
                    callback(false, req, rsp);
                    break;
                }
        }
    } catch (AccountException e) {
        log.error("OpenID authentication failure", e);
        cancelWithError(req, rsp, "Contact site administrator");
    }
}
Also used : AuthRequest(org.openid4java.message.AuthRequest) SRegMessage(org.openid4java.message.sreg.SRegMessage) PapeMessage(org.openid4java.message.pape.PapeMessage) AxMessage(org.openid4java.message.ax.AxMessage) Message(org.openid4java.message.Message) SRegResponse(org.openid4java.message.sreg.SRegResponse) MessageException(org.openid4java.message.MessageException) Cookie(javax.servlet.http.Cookie) FetchResponse(org.openid4java.message.ax.FetchResponse) MessageExtension(org.openid4java.message.MessageExtension) VerificationResult(org.openid4java.consumer.VerificationResult) AccountException(com.google.gerrit.server.account.AccountException) ParameterList(org.openid4java.message.ParameterList) PapeResponse(org.openid4java.message.pape.PapeResponse) ExternalId(com.google.gerrit.server.account.externalids.ExternalId)

Example 10 with MessageException

use of org.openid4java.message.MessageException in project oxTrust by GluuFederation.

the class OxChooserWebService method responseHandler.

@Path("/Response")
@GET
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response responseHandler(@Context HttpServletRequest httpReq, @Context HttpServletResponse httpRes, ForwardedRequest frequest) throws ConsumerException {
    try {
        log.debug("instantiating a ParameterList ");
        ParameterList response = new ParameterList(frequest.getParameterMap());
        log.debug("getting DiscoveryInformation ");
        DiscoveryInformation discovered = (DiscoveryInformation) httpReq.getSession().getAttribute("openid-disc");
        log.debug("getting StringBuffer ");
        StringBuffer receivingURL = frequest.getRequestURL();
        log.debug("getting QueryString ");
        String queryString = frequest.getQueryString();
        if (queryString != null && queryString.length() > 0)
            log.debug("getting receivingURL ");
        receivingURL.append("?").append(frequest.getQueryString());
        log.debug("getting VerificationResult ");
        VerificationResult verification = manager.verify(receivingURL.toString(), response, discovered);
        log.debug("getting VerificationResult ");
        Identifier verified = verification.getVerifiedId();
        log.debug(" VerificationResult retrieved ");
        if (verified != null) {
            log.debug("verified != null");
            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                log.debug("getting FetchResponse");
                FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
                log.debug("getting emails");
                List emails = fetchResp.getAttributeValues("email");
                log.debug("getting FirstName");
                String firstName = fetchResp.getAttributeValue("firstname");
                log.debug("getting LastName");
                String lastName = fetchResp.getAttributeValue("lastname");
                log.debug("getting one Email");
                String email = (String) emails.get(0);
                log.debug("email : ", email);
                String nickName = fetchResp.getAttributeValue("nickname");
                String Image = fetchResp.getAttributeValue("image");
                String Language = fetchResp.getAttributeValue("language");
                String Country = fetchResp.getAttributeValue("country");
                String Timezone = fetchResp.getAttributeValue("timezone");
                String Gender = fetchResp.getAttributeValue("gender");
                String Fullname = fetchResp.getAttributeValue("fullname");
                IdentityResponse idResponse = new IdentityResponse();
                idResponse.setFirstname(firstName);
                idResponse.setLastname(lastName);
                idResponse.setEmail(email);
                idResponse.setNickname(nickName);
                idResponse.setImage(Image);
                idResponse.setLanguage(Language);
                idResponse.setCountry(Country);
                idResponse.setTimezone(Timezone);
                idResponse.setGender(Gender);
                idResponse.setFullname(Fullname);
                return Response.ok(idResponse).build();
            }
            return errorResponse("Could not get fetched attributes");
        }
    } catch (AssociationException e) {
        return errorResponse("An AssociationException occured , please check your request.");
    } catch (MessageException e) {
        return errorResponse("An MessageException occured , please check your request.");
    } catch (DiscoveryException e) {
        return errorResponse("An DiscoveryException occured , please check your request.");
    } finally {
        identity.logout();
    }
    return errorResponse("An Error occured , please check your request.");
}
Also used : IdentityResponse(org.gluu.oxtrust.model.oxchooser.IdentityResponse) FetchResponse(org.openid4java.message.ax.FetchResponse) Identifier(org.openid4java.discovery.Identifier) VerificationResult(org.openid4java.consumer.VerificationResult) MessageException(org.openid4java.message.MessageException) DiscoveryInformation(org.openid4java.discovery.DiscoveryInformation) AuthSuccess(org.openid4java.message.AuthSuccess) ParameterList(org.openid4java.message.ParameterList) AssociationException(org.openid4java.association.AssociationException) List(java.util.List) ParameterList(org.openid4java.message.ParameterList) DiscoveryException(org.openid4java.discovery.DiscoveryException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

MessageException (org.openid4java.message.MessageException)10 DiscoveryInformation (org.openid4java.discovery.DiscoveryInformation)5 DiscoveryException (org.openid4java.discovery.DiscoveryException)4 AuthRequest (org.openid4java.message.AuthRequest)4 ParameterList (org.openid4java.message.ParameterList)4 FetchResponse (org.openid4java.message.ax.FetchResponse)4 AssociationException (org.openid4java.association.AssociationException)3 ConsumerException (org.openid4java.consumer.ConsumerException)3 VerificationResult (org.openid4java.consumer.VerificationResult)3 List (java.util.List)2 ConsumerManager (org.openid4java.consumer.ConsumerManager)2 Identifier (org.openid4java.discovery.Identifier)2 Message (org.openid4java.message.Message)2 MessageExtension (org.openid4java.message.MessageExtension)2 AxMessage (org.openid4java.message.ax.AxMessage)2 FetchRequest (org.openid4java.message.ax.FetchRequest)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 AccountException (com.google.gerrit.server.account.AccountException)1 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)1 ArrayList (java.util.ArrayList)1