Exemplo n.º 1
0
  public void doReturn(StaplerRequest request, StaplerResponse rsp) throws IOException {
    try {
      // --- processing the authentication response

      // extract the parameters from the authentication response
      // (which comes in as a HTTP request from the OpenID provider)
      ParameterList responselist = new ParameterList(request.getParameterMap());

      // extract the receiving URL from the HTTP request
      StringBuffer receivingURL = request.getRequestURL();
      String queryString = request.getQueryString();
      if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(request.getQueryString());

      // verify the response
      VerificationResult verification =
          manager.verify(receivingURL.toString(), responselist, discovered);

      // examine the verification result and extract the verified identifier
      Identifier verified = verification.getVerifiedId();
      if (verified != null) {
        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

        openid = authSuccess.getIdentity();
        claimedOpenid = authSuccess.getClaimed();
        rsp.sendRedirect(".");
      } else {
        throw HttpResponses.error(500, "Failed to login");
      }
    } catch (OpenIDException e) {
      throw new Error(e);
    }
  }
Exemplo n.º 2
0
  /**
   * Verify a previously authenticated user with the provider
   *
   * @param adapter protocol adapter
   * @param parameterMap request parameters
   * @param receivedURL url where the response will be received
   * @return
   * @throws OpenIDMessageException
   * @throws OpenIDDiscoveryException
   * @throws OpenIDAssociationException
   * @throws OpenIDLifeCycleException
   */
  public boolean verify(
      OpenIDProtocolAdapter adapter, Map<String, String> parameterMap, String receivedURL)
      throws OpenIDMessageException, OpenIDDiscoveryException, OpenIDAssociationException,
          OpenIDLifeCycleException {
    OpenIDLifecycle lifeCycle = null;

    if (adapter instanceof OpenIDLifecycle) {
      lifeCycle = (OpenIDLifecycle) adapter;
    }
    ParameterList responselist = new ParameterList(parameterMap);

    if (lifeCycle == null) throw new IllegalStateException("Lifecycle not found");

    DiscoveryInformation discovered =
        (DiscoveryInformation) lifeCycle.getAttributeValue(CONST.OPENID_DISC.get());

    // verify the response; ConsumerManager needs to be the same
    // (static) instance used to place the authentication request
    try {
      VerificationResult verification =
          this.consumerManager.verify(receivedURL, responselist, discovered);

      // examine the verification result and extract the verified identifier
      Identifier verified = verification.getVerifiedId();
      if (verified != null) {
        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

        // Create an lifecycle event array
        OpenIDLifecycleEvent[] eventArr =
            new OpenIDLifecycleEvent[] {
              /** Store the id * */
              new OpenIDLifecycleEvent(
                  OpenIDLifecycleEvent.TYPE.SESSION,
                  OpenIDLifecycleEvent.OP.ADD,
                  CONST.OPENID.get(),
                  authSuccess.getIdentity()),

              /** Store the claimed * */
              new OpenIDLifecycleEvent(
                  OpenIDLifecycleEvent.TYPE.SESSION,
                  OpenIDLifecycleEvent.OP.ADD,
                  CONST.OPENID_CLAIMED.get(),
                  authSuccess.getClaimed()),

              /** Indicate success * */
              new OpenIDLifecycleEvent(OpenIDLifecycleEvent.TYPE.SUCCESS, null, null, null)
            };
        lifeCycle.handle(eventArr);
        return true;
      }
    } catch (MessageException e) {
      throw new OpenIDMessageException(e);
    } catch (DiscoveryException e) {
      throw new OpenIDDiscoveryException(e);
    } catch (AssociationException e) {
      throw new OpenIDAssociationException(e);
    }

    return false;
  }
Exemplo n.º 3
0
  @SuppressWarnings("unchecked")
  public Principal processIncomingAuthResult(
      HttpServletRequest request, HttpServletResponse response) throws IOException {
    Principal principal = null;
    HttpSession session = request.getSession(false);
    if (session == null) throw new RuntimeException("wrong lifecycle: session was null");

    // extract the parameters from the authentication response
    // (which comes in as a HTTP request from the OpenID provider)
    ParameterList responseParamList = new ParameterList(request.getParameterMap());
    // retrieve the previously stored discovery information
    DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovery");
    if (discovered == null) throw new RuntimeException("discovered information was null");
    // extract the receiving URL from the HTTP request
    StringBuffer receivingURL = request.getRequestURL();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0)
      receivingURL.append("?").append(request.getQueryString());

    // verify the response; ConsumerManager needs to be the same
    // (static) instance used to place the authentication request
    VerificationResult verification;
    try {
      verification =
          openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // examine the verification result and extract the verified identifier
    Identifier identifier = verification.getVerifiedId();

    if (identifier != null) {
      AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

      Map<String, List<String>> attributes = null;
      if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        FetchResponse fetchResp;
        try {
          fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
        } catch (MessageException e) {
          throw new RuntimeException(e);
        }

        attributes = fetchResp.getAttributes();
      }

      principal =
          createOpenIDPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(), attributes);
      request.getSession().setAttribute("PRINCIPAL", principal);

      if (trace) log.trace("Logged in as:" + principal);
    } else {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    return principal;
  }
Exemplo n.º 4
0
  /**
   * Processes the returned information from an authentication request from the OP.
   *
   * @param discoveryInformation DiscoveryInformation that was created earlier in the conversation
   *     (by openid4java). This will need to be verified with openid4java to make sure everything
   *     went smoothly and there are no possible problems. This object was probably stored in
   *     session and retrieved for use in calling this method.
   * @param pageParameters PageParameters passed to the page handling the return verificaion.
   * @param returnToUrl The "return to" URL that was passed to the OP. It must match exactly, or
   *     openid4java will issue a verification failed message in the logs.
   * @return RegistrationModel - null if there was a problem, or a RegistrationModel object, with
   *     parameters filled in as compeletely as possible from the information available from the OP.
   *     If you are using MyOpenID, most of the time what is returned is from your "Default"
   *     profile, so if you need more information returned, make sure your Default profile is
   *     completely filled out.
   * @throws AssociationException
   * @throws DiscoveryException
   * @throws MessageException
   */
  public static RegistrationModel processReturn(HttpServletRequest req)
      throws MessageException, DiscoveryException, AssociationException {
    RegistrationModel ret = null;
    ParameterList response = new ParameterList(req.getParameterMap());
    log.debug("RETURN STATE " + response.getParameterValue("openid.mode"));
    DiscoveryInformation discovered =
        (DiscoveryInformation) req.getSession().getAttribute("openid-disc");
    // log.debug("Register: Authtype"+req.getAuthType().toString());
    log.debug("Register Attribute names" + req.getAttributeNames());

    // extract the receiving URL from the HTTP request
    // StringBuffer receivingURL = req.getRequestURL();
    // String queryString = req.getQueryString();
    // if (queryString != null && queryString.length() > 0)
    //   receivingURL.append("?").append(req.getQueryString());
    // HAck:
    String receivingURL = response.getParameterValue("openid.return_to");
    System.out.println("ReturnTO" + receivingURL);

    // verify the response; ConsumerManager needs to be the same
    // (static) instance used to place the authentication request
    log.debug("Consumer start verify");
    VerificationResult verification =
        getConsumerManager().verify(receivingURL.toString(), response, discovered);

    log.debug("Register: Messages :" + verification.getAuthResponse().toString());
    log.debug(
        "Reigster Class of verification" + verification.getAuthResponse().getClass().toString());
    log.debug("Register: ConsumerManager" + consumerManager.getDiscovery().toString());

    if (verification.getAuthResponse() instanceof org.openid4java.message.AuthFailure) {
      log.debug("Evtl. Fehlerhafter Return");
    } else if (verification.getAuthResponse() instanceof org.openid4java.message.AuthSuccess) {
      log.debug("Evtl. erfolgreicher Auth");
    } else {
      log.debug("Kein Positiver und kein negativer Auth. Fehler!");
    }

    // examine the verification result and extract the verified identifier
    Identifier verified = verification.getVerifiedId();
    log.debug("VerifiedID:" + verified);
    if (verified != null) {

      ret = new RegistrationModel();
      AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

      if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

        List<String> roles = fetchResp.getAttributeValues("label");

        log.debug("roles size: " + roles.size());
        if (roles.size() > 0) {
          String role = (String) roles.get(0);
          ret.setRole(role);
        }
      }
      if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
        MessageExtension extension = authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);
        if (extension instanceof SRegResponse) {
          ret.setOpenId(verified.getIdentifier());
          ret.setIs_verified(true);
          SRegResponse sRegResponse = (SRegResponse) extension;
          String value = sRegResponse.getAttributeValue("dob");
          if (value != null) {
            ret.setDateOfBirth(value);
          }
          value = sRegResponse.getAttributeValue("email");
          if (value != null) {
            ret.setEmailAddress(value);
          }
          value = sRegResponse.getAttributeValue("fullname");
          if (value != null) {
            ret.setFullName(value);
          }
        }
      }
    }
    return ret;
  }
  @Override
  public String readResponse(ThemeDisplay themeDisplay, ActionRequest actionRequest)
      throws PortalException {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    request = PortalUtil.getOriginalServletRequest(request);

    String receivingURL = ParamUtil.getString(request, "openid.return_to");
    ParameterList parameterList = new ParameterList(request.getParameterMap());

    HttpSession session = request.getSession();

    DiscoveryInformation discoveryInformation =
        (DiscoveryInformation) session.getAttribute(OpenIdWebKeys.OPEN_ID_DISCO);

    if (discoveryInformation == null) {
      return null;
    }

    AuthSuccess authSuccess = null;
    String firstName = null;
    String lastName = null;
    String emailAddress = null;

    try {
      VerificationResult verificationResult =
          _consumerManager.verify(receivingURL, parameterList, discoveryInformation);

      Identifier identifier = verificationResult.getVerifiedId();

      if (identifier == null) {
        return null;
      }

      authSuccess = (AuthSuccess) verificationResult.getAuthResponse();

      firstName = null;
      lastName = null;
      emailAddress = null;

      if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
        MessageExtension messageExtension = authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);

        if (messageExtension instanceof SRegResponse) {
          SRegResponse sregResp = (SRegResponse) messageExtension;

          String fullName =
              GetterUtil.getString(sregResp.getAttributeValue(_OPEN_ID_SREG_ATTR_FULLNAME));

          String[] names = splitFullName(fullName);

          if (names != null) {
            firstName = names[0];
            lastName = names[1];
          }

          emailAddress = sregResp.getAttributeValue(_OPEN_ID_SREG_ATTR_EMAIL);
        }
      }

      if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        MessageExtension messageExtension = authSuccess.getExtension(AxMessage.OPENID_NS_AX);

        if (messageExtension instanceof FetchResponse) {
          FetchResponse fetchResponse = (FetchResponse) messageExtension;

          OpenIdProvider openIdProvider =
              _openIdProviderRegistry.getOpenIdProvider(discoveryInformation.getOPEndpoint());

          String[] openIdAXTypes = openIdProvider.getAxSchema();

          for (String openIdAXType : openIdAXTypes) {
            if (openIdAXType.equals(_OPEN_ID_AX_ATTR_EMAIL)) {
              if (Validator.isNull(emailAddress)) {
                emailAddress =
                    getFirstValue(fetchResponse.getAttributeValues(_OPEN_ID_AX_ATTR_EMAIL));
              }
            } else if (openIdAXType.equals(_OPEN_ID_AX_ATTR_FIRST_NAME)) {

              if (Validator.isNull(firstName)) {
                firstName =
                    getFirstValue(fetchResponse.getAttributeValues(_OPEN_ID_AX_ATTR_FIRST_NAME));
              }
            } else if (openIdAXType.equals(_OPEN_ID_AX_ATTR_FULL_NAME)) {

              String fullName = fetchResponse.getAttributeValue(_OPEN_ID_AX_ATTR_FULL_NAME);

              String[] names = splitFullName(fullName);

              if (names != null) {
                if (Validator.isNull(firstName)) {
                  firstName = names[0];
                }

                if (Validator.isNull(lastName)) {
                  lastName = names[1];
                }
              }
            } else if (openIdAXType.equals(_OPEN_ID_AX_ATTR_LAST_NAME)) {

              if (Validator.isNull(lastName)) {
                lastName =
                    getFirstValue(fetchResponse.getAttributeValues(_OPEN_ID_AX_ATTR_LAST_NAME));
              }
            }
          }
        }
      }
    } catch (AssociationException ae) {
      throw new OpenIdServiceException.AssociationException(ae.getMessage(), ae);
    } catch (DiscoveryException de) {
      throw new OpenIdServiceException.DiscoveryException(de.getMessage(), de);
    } catch (MessageException me) {
      throw new OpenIdServiceException.MessageException(me.getMessage(), me);
    }

    String openId = normalize(authSuccess.getIdentity());

    User user = _userLocalService.fetchUserByOpenId(themeDisplay.getCompanyId(), openId);

    if (user != null) {
      session.setAttribute(WebKeys.OPEN_ID_LOGIN, user.getUserId());

      return null;
    }

    try {
      if (Validator.isNull(firstName)
          || Validator.isNull(lastName)
          || Validator.isNull(emailAddress)) {

        SessionMessages.add(request, "openIdUserInformationMissing");

        if (_log.isInfoEnabled()) {
          _log.info(
              "The OpenID provider did not send the required " + "attributes to create an account");
        }

        String createAccountURL = PortalUtil.getCreateAccountURL(request, themeDisplay);

        String portletId = HttpUtil.getParameter(createAccountURL, "p_p_id", false);

        String portletNamespace = PortalUtil.getPortletNamespace(portletId);

        createAccountURL =
            HttpUtil.setParameter(createAccountURL, portletNamespace + "openId", openId);

        session.setAttribute(WebKeys.OPEN_ID_LOGIN_PENDING, Boolean.TRUE);

        return createAccountURL;
      }
    } catch (Exception e) {
      throw new PortalException(e);
    }

    long creatorUserId = 0;
    long companyId = themeDisplay.getCompanyId();
    boolean autoPassword = false;
    String password1 = PwdGenerator.getPassword();
    String password2 = password1;
    boolean autoScreenName = true;
    String screenName = StringPool.BLANK;
    long facebookId = 0;
    Locale locale = themeDisplay.getLocale();
    String middleName = StringPool.BLANK;
    long prefixId = 0;
    long suffixId = 0;
    boolean male = true;
    int birthdayMonth = Calendar.JANUARY;
    int birthdayDay = 1;
    int birthdayYear = 1970;
    String jobTitle = StringPool.BLANK;
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = false;

    ServiceContext serviceContext = new ServiceContext();

    user =
        _userLocalService.addUser(
            creatorUserId,
            companyId,
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            facebookId,
            openId,
            locale,
            firstName,
            middleName,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            groupIds,
            organizationIds,
            roleIds,
            userGroupIds,
            sendEmail,
            serviceContext);

    session.setAttribute(WebKeys.OPEN_ID_LOGIN, user.getUserId());

    return null;
  }
  // authentication response
  public Account 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) {
        // success

        String accountName = AccountImpl.escape(verified.getIdentifier());
        AbstractAccount account = (AbstractAccount) OpenIDRealm.instance.getAccount(accountName);
        if (account == null) {
          Database db = OpenIDRealm.instance.getDatabase();
          org.exist.security.Subject currentSubject = db.getSubject();
          try {
            db.setSubject(db.getSecurityManager().getSystemSubject());

            // XXX: set OpenID group by default
            account =
                (AbstractAccount)
                    OpenIDRealm.instance.addAccount(
                        new UserAider(OpenIDRealm.instance.getId(), accountName));
          } finally {
            db.setSubject(currentSubject);
          }
        }

        org.exist.security.Subject principal = new SubjectAccreditedImpl(account, verified);

        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
        authSuccess.getExtensions();

        if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
          MessageExtension ext = authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);
          if (ext instanceof SRegResponse) {
            SRegResponse sregResp = (SRegResponse) ext;
            for (Iterator iter = sregResp.getAttributeNames().iterator(); iter.hasNext(); ) {
              String name = (String) iter.next();
              if (LOG.isDebugEnabled()) LOG.debug(name + " : " + sregResp.getParameterValue(name));
              principal.setMetadataValue(
                  AXSchemaType.valueOfNamespace(name), sregResp.getParameterValue(name));
            }
          }
        }
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
          FetchResponse fetchResp =
              (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

          List aliases = fetchResp.getAttributeAliases();
          for (Iterator iter = aliases.iterator(); iter.hasNext(); ) {
            String alias = (String) iter.next();
            List values = fetchResp.getAttributeValues(alias);
            if (values.size() > 0) {
              if (LOG.isDebugEnabled()) LOG.debug(alias + " : " + values.get(0));
              principal.setMetadataValue(AXSchemaType.valueOfAlias(alias), (String) values.get(0));
            }
          }
        }
        // update metadata
        Database db = OpenIDRealm.instance.getDatabase();
        org.exist.security.Subject currentSubject = db.getSubject();
        try {
          db.setSubject(db.getSecurityManager().getSystemSubject());

          OpenIDRealm.instance.updateAccount(principal);
        } finally {
          db.setSubject(currentSubject);
        }

        OpenIDUtility.registerUser(principal);
        return principal;
      }
    } catch (OpenIDException e) {
      LOG.error(e);
    } catch (ConfigurationException e) {
      LOG.error(e);
    } catch (PermissionDeniedException e) {
      LOG.error(e);
    } catch (EXistException e) {
      LOG.error(e);
    }

    return null;
  }
Exemplo n.º 7
0
  @SuppressWarnings({"unchecked"})
  public Response verifyResponse(HttpServletRequest request, HttpServletResponse httpresponse) {
    try {
      HttpSession session = request.getSession();

      // extract the parameters from the authentication response
      // (which comes in as a HTTP request from the OpenID provider)
      ParameterList response = new ParameterList(request.getParameterMap());

      // retrieve the previously stored discovery information
      DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disc");

      // extract the receiving URL from the HTTP request
      StringBuffer receivingURL = request.getRequestURL();
      String queryString = request.getQueryString();
      if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(request.getQueryString());

      // verify the response; ConsumerManager needs to be the same
      // (static) instance used to place the authentication request
      VerificationResult verification =
          manager.verify(receivingURL.toString(), response, discovered);

      // examine the verification result and extract the verified identifier
      Identifier verified = verification.getVerifiedId();
      if (verified != null) {
        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
        String name = null;
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
          FetchResponse fetchResp =
              (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
          Map<String, List<String>> attributes = fetchResp.getAttributes();
          if (attributes.containsKey(AP_FULL_NAME)) {
            name = attributes.get(AP_FULL_NAME).get(0);
          } else {
            name = attributes.get(AP_FIRST_NAME).get(0) + " " + attributes.get(AP_LAST_NAME).get(0);
          }
        }
        log.info(String.format("Verified identity %s = %s", verified.getIdentifier(), name));
        UserStore userstore = Registry.get().getUserStore();
        boolean isRegistration = ((Boolean) session.getAttribute(SA_REGISTRATION)).booleanValue();
        String registrationStatus = RS_LOGIN;
        if (isRegistration) {
          UserInfo userinfo = new UserInfo(verified.getIdentifier(), name);
          if (userstore.register(userinfo)) {
            registrationStatus = RS_NEW;
          } else {
            registrationStatus = RS_ALREADY_REGISTERED;
          }
        }

        RegToken token = new RegToken(verified.getIdentifier(), true);
        Subject subject = SecurityUtils.getSubject();
        try {
          subject.login(token);
          session.setAttribute(VN_REGISTRATION_STATUS, registrationStatus);
          String provider = (String) session.getAttribute(SA_OPENID_PROVIDER);
          if (provider != null && !provider.isEmpty()) {
            Cookie cookie = new Cookie(PROVIDER_COOKIE, provider);
            cookie.setComment(
                "Records the openid provider you last used to log in to a UKGovLD registry");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            httpresponse.addCookie(cookie);
          }
          return redirectTo(session.getAttribute(SA_RETURN_URL).toString());
          //                    return RequestProcessor.render("admin.vm", uriInfo, servletContext,
          // request, VN_SUBJECT, subject, VN_REGISTRATION_STATUS, registrationStatus);
        } catch (Exception e) {
          log.error("Authentication failure: " + e);
          return RequestProcessor.render(
              "error.vm",
              uriInfo,
              servletContext,
              request,
              "message",
              "Could not find a registration for you.");
        }
      }
    } catch (Exception e) {
      throw new WebApplicationException(e);
    }
    return RequestProcessor.render(
        "error.vm", uriInfo, servletContext, request, "message", "OpenID login failed");
  }