public void process(OpenIdTestService s, AuthRequest authReq, Message rep)
            throws MessageException {
          if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG)) {
            MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG);
            if (ext instanceof SRegRequest) {
              SRegRequest sregReq = (SRegRequest) ext;
              SRegResponse sregRes = SRegResponse.createFetchResponse();

              List<String> attrs = (List<String>) sregReq.getAttributes();
              if (attrs.contains("fullname") && s.props.containsKey(IdProperty.fullName)) {
                sregRes.addAttribute("fullname", s.props.get(IdProperty.fullName));
              }

              if (attrs.contains("nickname") && s.props.containsKey(IdProperty.nick)) {
                sregRes.addAttribute("nickname", s.props.get(IdProperty.nick));
              }

              if (attrs.contains("email") && s.props.containsKey(IdProperty.email)) {
                sregRes.addAttribute("email", s.props.get(IdProperty.email));
              }

              rep.addExtension(sregRes);
            }
          }
        }
  /**
   * Create an OpenID Auth Request, using the DiscoveryInformation object return by the openid4java
   * library.
   *
   * <p>This method also uses the Simple Registration Extension to grant the Relying Party (RP).
   *
   * @param discoveryInformation The DiscoveryInformation that should have been previously obtained
   *     from a call to performDiscoveryOnUserSuppliedIdentifier().
   * @param returnToUrl The URL to which the OP will redirect once the authentication call is
   *     complete.
   * @return AuthRequest - A "good-to-go" AuthRequest object packed with all kinds of great OpenID
   *     goodies for the OpenID Provider (OP). The caller must take this object and forward it on to
   *     the OP. Or call processAuthRequest() - part of this Service Class.
   */
  public static AuthRequest createOpenIdAuthRequest(
      DiscoveryInformation discoveryInformation, String returnToUrl) {
    AuthRequest ret = null;
    //
    try {
      // Create the AuthRequest object
      ret = getConsumerManager().authenticate(discoveryInformation, returnToUrl);
      // Create the Simple Registration Request
      SRegRequest sRegRequest = SRegRequest.createFetchRequest();
      FetchRequest ax = FetchRequest.createFetchRequest();
      // ax.addAttribute("http://www.w3.org/2006/vcard/ns#role",true);
      ax.addAttribute("label", "http://www.w3.org/2006/vcard/ns#role", true, 0);

      sRegRequest.addAttribute("email", false);
      sRegRequest.addAttribute("fullname", false);
      sRegRequest.addAttribute("dob", false);
      sRegRequest.addAttribute("postcode", false);
      ret.addExtension(sRegRequest);
      ret.addExtension(ax);

    } catch (Exception e) {
      String message = "Exception occurred while building AuthRequest object!";
      log.error(message, e);
      throw new RuntimeException(message, e);
    }
    return ret;
  }
        public void process(OpenIdTestService s, AuthRequest authReq, Message rep)
            throws MessageException {
          if (authReq.hasExtension(TeamExtensionFactory.URI)) {
            MessageExtension ext = authReq.getExtension(TeamExtensionFactory.URI);
            if (ext instanceof TeamExtensionRequest) {
              TeamExtensionRequest teamReq = (TeamExtensionRequest) ext;

              rep.addExtension(new ServiceTeamExtensionResponse(s.teams));
            }
          }
        }
  public static AuthRequest createAuthRequest(ParameterList params, RealmVerifier realmVerifier)
      throws MessageException {
    AuthRequest req = new AuthRequest(params);

    req.setRealmVerifier(realmVerifier);

    req.validate();

    if (DEBUG) _log.debug("Created auth request:\n" + req.keyValueFormEncoding());

    return req;
  }
  private void respondToExtensions(ParameterList reqp, Message rep) throws MessageException {
    AuthRequest authReq = AuthRequest.createAuthRequest(reqp, manager.getRealmVerifier());

    for (ProcessExtension e : extensions) {
      e.process(this, authReq, rep);
    }
  }
  public static AuthRequest createAuthRequest(
      String claimedId,
      String delegate,
      boolean compatibility,
      String returnToUrl,
      String handle,
      String realm,
      RealmVerifier verifier)
      throws MessageException {
    AuthRequest req =
        new AuthRequest(claimedId, delegate, compatibility, returnToUrl, handle, realm, verifier);

    req.validate();

    if (DEBUG) _log.debug("Created auth request:\n" + req.keyValueFormEncoding());

    return req;
  }
  @SuppressWarnings("unchecked")
  private boolean prepareAndSendAuthRequest(
      HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Figure out the service url
    String authType = request.getParameter(AUTH_TYPE);
    if (authType == null || authType.length() == 0) {
      authType = (String) request.getSession().getAttribute(AUTH_TYPE);
    }
    determineServiceUrl(authType);

    String openId = openIdServiceUrl;
    HttpSession session = request.getSession(true);
    if (openId != null) {
      session.setAttribute("openid", openId);
      List<DiscoveryInformation> discoveries;
      try {
        discoveries = openIdConsumerManager.discover(openId);
      } catch (DiscoveryException e) {
        throw new RuntimeException(e);
      }

      DiscoveryInformation discovered = openIdConsumerManager.associate(discoveries);
      session.setAttribute("discovery", discovered);
      try {
        AuthRequest authReq = openIdConsumerManager.authenticate(discovered, returnURL);

        // Add in required attributes
        authReq.addExtension(fetchRequest);

        String url = authReq.getDestinationUrl(true);
        response.sendRedirect(url);

        request.getSession().setAttribute("STATE", STATES.AUTH.name());
        return false;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    return false;
  }
        public void process(OpenIdTestService s, AuthRequest authReq, Message rep)
            throws MessageException {
          if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
            MessageExtension ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
            if (ext instanceof FetchRequest) {
              FetchRequest fetchReq = (FetchRequest) ext;
              FetchResponse fr = FetchResponse.createFetchResponse();

              for (Map.Entry<String, String> e :
                  ((Map<String, String>) fetchReq.getAttributes()).entrySet()) {
                if ((e.getValue().equals("http://axschema.org/contact/email"))
                    && s.props.containsKey(IdProperty.email)) {
                  if (s.props.get(IdProperty.email) != null) {
                    fr.addAttribute(e.getKey(), e.getValue(), s.props.get(IdProperty.email));
                  }
                } else if ((e.getValue().equals("http://schema.openid.net/contact/email"))
                    && s.props.containsKey(IdProperty.email2)) {
                  if (s.props.get(IdProperty.email2) != null) {
                    fr.addAttribute(e.getKey(), e.getValue(), s.props.get(IdProperty.email2));
                  }
                } else if ((e.getValue().equals("http://openid.net/schema/contact/email"))
                    && s.props.containsKey(IdProperty.email3)) {
                  if (s.props.get(IdProperty.email3) != null) {
                    fr.addAttribute(e.getKey(), e.getValue(), s.props.get(IdProperty.email3));
                  }
                }

                if (e.getValue().equals("http://axschema.org/namePerson/first")
                    && s.props.containsKey(IdProperty.firstName))
                  fr.addAttribute(e.getKey(), e.getValue(), s.props.get(IdProperty.firstName));

                if (e.getValue().equals("http://axschema.org/namePerson/last")
                    && s.props.containsKey(IdProperty.lastName))
                  fr.addAttribute(e.getKey(), e.getValue(), s.props.get(IdProperty.lastName));
              }

              rep.addExtension(fr);
            }
          }
        }
  /*
   * This method is called by the application when the user clicks on 'Sign In
   * with Intuit' button from the Login Page to get the OpenId.
   */
  @RequestMapping(value = "/initialize.htm", method = RequestMethod.GET)
  public void initialize(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException {

    LOG.info("### OpenIdController -> initialize() - started ###");

    final List<DiscoveryInformation> discoveries = new ArrayList<DiscoveryInformation>();
    final ConsumerManager manager = new ConsumerManager();

    manager.setAssociations(new InMemoryConsumerAssociationStore());
    manager.setNonceVerifier(new InMemoryNonceVerifier(5000));
    manager.setMinAssocSessEnc(AssociationSessionType.DH_SHA256);

    DiscoveryInformation discovered = null;

    try {
      LOG.info("OpenID Provider URL = " + WebUtils.OPENID_PROVIDER_URL);
      discovered = new DiscoveryInformation(new URL(WebUtils.OPENID_PROVIDER_URL));
    } catch (DiscoveryException e) {
      LOG.error(e.getLocalizedMessage());
    } catch (MalformedURLException me) {
      LOG.error(me.getLocalizedMessage());
    }

    discoveries.add(discovered);

    final DiscoveryInformation discoveryInfo = manager.associate(discoveries);
    request.getSession().setAttribute("openid-disc", discoveryInfo);

    final FetchRequest fetch = FetchRequest.createFetchRequest();

    try {
      fetch.addAttribute("FirstName", "http://axschema.org/namePerson/first", true);
      fetch.addAttribute("LastName", "http://axschema.org/namePerson/last", true);
      fetch.addAttribute("Email", "http://axschema.org/contact/email", true);
      fetch.addAttribute("RealmId", "http://axschema.org/intuit/realmId", true);
    } catch (MessageException e) {
      LOG.error(e.getLocalizedMessage());
    }

    fetch.setCount("Email", 3);

    AuthRequest authReq = null;
    LOG.info("openIdReturnUrl = " + WebUtils.OPENID_RETURN_URL);
    try {
      authReq = manager.authenticate(discoveryInfo, WebUtils.OPENID_RETURN_URL);
      authReq.addExtension(fetch);
    } catch (MessageException e) {
      LOG.error(e.getLocalizedMessage());
    } catch (ConsumerException e) {
      LOG.error(e.getLocalizedMessage());
    }

    final HttpSession session = request.getSession();
    LOG.info("Session Id : " + session.getId());
    session.setAttribute("consumerManager", manager);
    LOG.info("authReq.getDestinationUrl: " + authReq.getDestinationUrl(true));
    LOG.info("### OpenIdController -> initialize() - completed ###");

    response.sendRedirect(authReq.getDestinationUrl(true));
  }
  @SuppressWarnings("unchecked")
  protected void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
      throws ServletException, IOException {
    ServerManager manager = getServerManager();
    IWMainApplication iwma = IWMainApplication.getIWMainApplication(req);

    // extract the parameters from the request
    ParameterList requestParameters = new ParameterList(req.getParameterMap());

    OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
    ParameterList sessionStoredParameterList = serverBean.getParameterList();
    if (sessionStoredParameterList != null) {
      if (!requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)) {
        sessionStoredParameterList.addParams(requestParameters);
        requestParameters = sessionStoredParameterList;
      }
    }

    String mode =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_OPENID_MODE)
            : null;
    String realm =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_REALM)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_REALM)
            : null;
    if (realm != null) {
      serverBean.setReturnUrl(realm);
      realm = getRealmName(realm);
      serverBean.setRealm(realm);
    }

    Message response;
    String responseText = null;

    try {
      if (OpenIDConstants.PARAMETER_ASSOCIATE.equals(mode)) {
        // --- process an association request ---
        response = manager.associationResponse(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else if (OpenIDConstants.PARAMETER_CHECKID_SETUP.equals(mode)
          || OpenIDConstants.PARAMETER_CHECKID_IMMEDIATE.equals(mode)) {
        IWContext iwc = new IWContext(req, resp, getServletContext());

        boolean goToLogin = doRedirectToLoginPage(manager, requestParameters, iwc, realm);

        if (!goToLogin) {
          serverBean.setParameterList(null);
          serverBean.setServerUrl(null);
          serverBean.setDoRedirect(null);
          serverBean.setUsername(null);

          // interact with the user and obtain data needed to continue
          User user = iwc.getCurrentUser();
          String userSelectedClaimedId = getUserSelectedClaimedId(iwc, user);

          // --- process an authentication request ---
          AuthRequest authReq =
              AuthRequest.createAuthRequest(requestParameters, manager.getRealmVerifier());

          storeRequestedAttributesToSession(iwc, authReq);

          Boolean authenticatedAndApproved = isAuthenticatedAndApproved(iwc, user, authReq);

          String opLocalId = null;
          // if the user chose a different claimed_id than the one in request
          if (userSelectedClaimedId != null
              && !userSelectedClaimedId.equals(authReq.getClaimed())) {
            opLocalId = userSelectedClaimedId;
          }

          response =
              manager.authResponse(
                  requestParameters,
                  opLocalId,
                  userSelectedClaimedId,
                  authenticatedAndApproved.booleanValue(),
                  false); // Sign after we added extensions.

          if (response instanceof DirectError) {
            directResponse(resp, response.keyValueFormEncoding());
            return;
          } else if (response instanceof AuthFailure) {
            redirectToAuthorisationPage(req, resp, requestParameters, serverBean);
            return;
          } else {
            String[] extensionsToSign = prepareResponse(serverBean, response, iwc, user, authReq);
            boolean signExtensions =
                iwma.getSettings().getBoolean(OpenIDConstants.PROPERTY_SIGN_EXTENSIONS, false);

            AuthSuccess success = (AuthSuccess) response;
            if (signExtensions) {
              success.setSignExtensions(extensionsToSign);
            }

            // Sign the auth success message.
            // This is required as AuthSuccess.buildSignedList has a `todo' tag now.
            manager.sign(success);

            // caller will need to decide which of the following to use:

            // option1: GET HTTP-redirect to the return_to URL
            //		                cleanUpBeforeReturning(iwc, loginExpireHandle);
            // Clean up before returning
            serverBean.invalidate();

            getDAO().createLogEntry(user.getUniqueId(), realm, "");

            resp.sendRedirect(response.getDestinationUrl(true));
            return;

            // option2: HTML FORM Redirection
            // RequestDispatcher dispatcher =
            // getServletContext().getRequestDispatcher("formredirection.jsp");
            // httpReq.setAttribute("parameterMap", response.getParameterMap());
            // httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false));
            // dispatcher.forward(request, response);
            // return null;
          }
        } else {
          redirectToLoginPage(req, resp, requestParameters, serverBean, manager);
          return;
        }
      } else if (OpenIDConstants.PARAMETER_CHECK_AUTHENTICATION.equals(mode)) {
        // --- processing a verification request ---
        response = manager.verify(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
        serverBean.invalidate();
      }
    } catch (MessageException me) {
      me.printStackTrace();
      responseText = me.getMessage();
      serverBean.invalidate();
    } catch (AssociationException ae) {
      ae.printStackTrace();
      responseText = ae.getMessage();
      serverBean.invalidate();
    } catch (ServerException se) {
      se.printStackTrace();
      responseText = se.getMessage();
      serverBean.invalidate();
    }

    // return the result to the user
    directResponse(resp, responseText);
  }
  @SuppressWarnings("unchecked")
  private void storeRequestedAttributesToSession(IWContext iwc, AuthRequest authReq) {
    if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
      MessageExtension ext;
      try {
        ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchRequest) {
          FetchRequest fetchReq = (FetchRequest) ext;
          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          Map<String, String> allAttributes = (Map<String, String>) fetchReq.getAttributes();
          Map<String, String> required = (Map<String, String>) fetchReq.getAttributes(true);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          String realm = serverBean.getRealm();

          for (String alias : allAttributes.keySet()) {
            ExchangeAttribute attribute =
                getDAO().getExchangeAttribute(alias, allAttributes.get(alias));
            if (attribute != null) {
              User user = iwc.getCurrentUser();
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.containsKey(alias) && attribute.getType().equals(required.get(alias))) {
                requiredAttributesList.add(aattr);
              } else {
                optionalAttributesList.add(aattr);
              }
            } else {
              LOGGER.warning(
                  "Requesting unknown exchange attribute: "
                      + alias
                      + " : "
                      + allAttributes.get(alias));
              // throw new UnsupportedOperationException("Requesting unknown exchange attribute.");
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        } else /*if (ext instanceof StoreRequest)*/ {
          // TODO implement?
          throw new UnsupportedOperationException("TODO");
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
    if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG11)) {
      try {
        MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG11);

        if (ext instanceof SRegRequest) {
          SRegRequest sregReq = (SRegRequest) ext;
          List<String> all = sregReq.getAttributes();
          List<String> required = sregReq.getAttributes(true);
          List<String> optional = sregReq.getAttributes(false);

          List<AuthorizedAttribute> allAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> requiredAttributesList = new ArrayList<AuthorizedAttribute>();
          List<AuthorizedAttribute> optionalAttributesList = new ArrayList<AuthorizedAttribute>();

          OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
          String realm = serverBean.getRealm();
          User user = iwc.getCurrentUser();

          for (String alias : all) {
            ExchangeAttribute attribute = getDAO().getExchangeAttribute(alias);
            if (attribute != null) {
              AuthorizedAttribute aattr =
                  getDAO().getAuthorizedAttributes(user.getUniqueId(), realm, attribute);
              if (aattr == null) {
                aattr = new AuthorizedAttribute();
                aattr.setExchangeAttribute(attribute);
                aattr.setRealm(realm);
                aattr.setUserUUID(user.getUniqueId());
                aattr.setIsAllowed(true);
              }
              allAttributesList.add(aattr);
              if (required.contains(alias)) {
                requiredAttributesList.add(aattr);
              }
              if (optional.contains(alias)) {
                optionalAttributesList.add(aattr);
              }
            }
          }

          serverBean.setRequestedAttributes(allAttributesList);
          serverBean.setRequiredAttributes(requiredAttributesList);
          serverBean.setOptionalAttributes(optionalAttributesList);
          return;
        }
      } catch (MessageException e) {
        e.printStackTrace();
      }
    }
  }
  protected String[] prepareResponse(
      OpenIDServerBean serverBean, Message response, IWContext iwc, User user, AuthRequest authReq)
      throws MessageException {
    List<String> extensionsToSign = new ArrayList<String>();
    if (authReq.hasExtension(AxMessage.OPENID_NS_AX)) {
      try {
        MessageExtension ext = authReq.getExtension(AxMessage.OPENID_NS_AX);
        if (ext instanceof FetchRequest) {
          FetchRequest fetchReq = (FetchRequest) ext;
          Map<String, String> requestedAttributes = fetchReq.getAttributes();
          Map userDataExt = new HashMap();

          FetchResponse fetchResp = FetchResponse.createFetchResponse(fetchReq, userDataExt);
          List<AuthorizedAttribute> s = serverBean.getRequestedAttributes();
          Set<String> keys = requestedAttributes.keySet();
          Collection<String> types = requestedAttributes.values();
          for (AuthorizedAttribute a : s) {
            ExchangeAttribute attr = a.getExchangeAttribute();
            String alias = attr.getName();
            String type = attr.getType();
            if (keys.contains(alias) || types.contains(type)) {
              String value = getAttributeValue(iwc, user, alias, type);
              if (value == null) {
                value = "";
              }
              fetchResp.addAttribute(alias, type, value);
            } else {
              // FetchRequest not asking for this attribute
              throw new UnsupportedOperationException(
                  "Processed and requested attributes do not match.");
            }
          }

          response.addExtension(fetchResp);
          extensionsToSign.add(AxMessage.OPENID_NS_AX);
        } else /*if (ext instanceof StoreRequest)*/ {
          throw new UnsupportedOperationException("TODO");
        }
      } catch (MessageException me) {
        System.err.println(me.getMessage());
      }
    }
    if (authReq.hasExtension(SRegMessage.OPENID_NS_SREG11)) {
      MessageExtension ext = authReq.getExtension(SRegMessage.OPENID_NS_SREG11);

      if (ext instanceof SRegRequest) {
        SRegRequest sregReq = (SRegRequest) ext;
        List<String> required = sregReq.getAttributes(true);
        List<String> optional = sregReq.getAttributes(false);

        Map userData = new HashMap();
        for (String alias : required) {
          String value = getAttributeValue(iwc, user, alias, null);
          if (alias.length() > 0 && value != null) {
            userData.put(alias, value);
          } else if (alias.length() > 0) {
            throw new UnsupportedOperationException("Required attribute not supported: " + alias);
          }
        }
        for (String alias : optional) {
          String value = getAttributeValue(iwc, user, alias, null);
          if (alias.length() > 0 && value != null) {
            userData.put(alias, value);
          }
        }

        SRegResponse sregResp = SRegResponse.createSRegResponse(sregReq, userData);
        response.addExtension(sregResp);
        extensionsToSign.add(SRegMessage.OPENID_NS_SREG11);
      } else if (ext instanceof SRegResponse) {
        response.addExtension(ext);
      }
    }

    return extensionsToSign.toArray(new String[extensionsToSign.size()]);
  }
Exemple #13
0
  public void doStart(
      StaplerRequest request, StaplerResponse response, @QueryParameter String openid)
      throws IOException, ServletException {
    try {
      // determine a return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      // YOU SHOULD CHANGE THIS TO GO TO THE
      String url = request.getRequestURL().toString();
      String returnToUrl = url.substring(0, url.length() - 5 /*start*/) + "return";

      // perform discovery on the user-supplied identifier
      List discoveries = manager.discover(openid);

      // attempt to associate with an OpenID provider
      // and retrieve one service endpoint for authentication
      discovered = manager.associate(discoveries);

      // store the discovery information in the user's session

      // 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

      // see http://code.google.com/apis/accounts/docs/OpenID.html
      fetch.addAttribute("ff", "http://axschema.org/namePerson/first", true);
      fetch.addAttribute("ll", "http://axschema.org/namePerson/last", true);

      // attach the extension to the authentication request
      authReq.addExtension(fetch);

      SRegRequest sregReq = SRegRequest.createFetchRequest();
      sregReq.addAttribute("fullname", true);
      sregReq.addAttribute("nickname", true);
      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
        response.sendRedirect(authReq.getDestinationUrl(true));
      } else {
        // Option 2: HTML FORM Redirection
        // Allows payloads > 2048 bytes

        // <FORM action="OpenID Provider's service endpoint">
        // see samples/formredirection.jsp for a JSP example
        // authReq.getOPEndpoint();

        // build a HTML FORM with the message parameters
        // authReq.getParameterMap();

        RequestDispatcher d = request.getView(this, "formRedirect.jelly");
        request.setAttribute("endpoint", authReq.getOPEndpoint());
        request.setAttribute("parameters", authReq.getParameterMap());
        d.forward(request, response);
      }
    } catch (OpenIDException e) {
      // present error to the user
      throw new Error(e);
    }
  }
  /**
   * Authenticate an user with the provider
   *
   * @param adapter protocol adapter
   * @param providerInfo Information about a provider derived from discovery process
   * @return
   * @throws OpenIDDiscoveryException
   * @throws OpenIDConsumerException
   * @throws OpenIDMessageException
   * @throws OpenIDProtocolException
   */
  @SuppressWarnings("unchecked")
  public boolean authenticate(OpenIDProtocolAdapter adapter, OpenIDProviderInformation providerInfo)
      throws OpenIDDiscoveryException, OpenIDConsumerException, OpenIDMessageException,
          OpenIDProtocolException {
    DiscoveryInformation discovered = providerInfo.get();

    // obtain a AuthRequest message to be sent to the OpenID provider
    try {
      AuthRequest authReq = consumerManager.authenticate(discovered, adapter.getReturnURL());

      // Attribute Exchange example: fetching the 'email' attribute
      FetchRequest fetch = FetchRequest.createFetchRequest();
      SRegRequest sregReq = SRegRequest.createFetchRequest();

      OpenIDAttributeMap amap = adapter.getAttributeMap();

      if ("1".equals(amap.get("nickname"))) {
        // fetch.addAttribute("nickname",
        // "http://schema.openid.net/contact/nickname", false);
        sregReq.addAttribute("nickname", false);
      }

      if ("1".equals(amap.get("email"))) {
        fetch.addAttribute("email", OpenIDConstants.EMAIL.url(), false);
        sregReq.addAttribute("email", false);
      }

      if ("1".equals(amap.get("fullname"))) {
        fetch.addAttribute("fullname", OpenIDConstants.FULLNAME.url(), false);
        sregReq.addAttribute("fullname", false);
      }
      if ("1".equals(amap.get("dob"))) {
        fetch.addAttribute("dob", OpenIDConstants.DOB.url(), true);
        sregReq.addAttribute("dob", false);
      }

      if ("1".equals(amap.get("gender"))) {
        fetch.addAttribute("gender", OpenIDConstants.GENDER.url(), false);
        sregReq.addAttribute("gender", false);
      }

      if ("1".equals(amap.get("postcode"))) {
        fetch.addAttribute("postcode", OpenIDConstants.POSTCODE.url(), false);
        sregReq.addAttribute("postcode", false);
      }

      if ("1".equals(amap.get("country"))) {
        fetch.addAttribute("country", OpenIDConstants.COUNTRY.url(), false);
        sregReq.addAttribute("country", false);
      }

      if ("1".equals(amap.get("language"))) {
        fetch.addAttribute("language", OpenIDConstants.LANGUAGE.url(), false);
        sregReq.addAttribute("language", false);
      }

      if ("1".equals(amap.get("timezone"))) {
        fetch.addAttribute("timezone", OpenIDConstants.TIMEZONE.url(), false);
        sregReq.addAttribute("timezone", false);
      }

      // attach the extension to the authentication request
      if (!sregReq.getAttributes().isEmpty()) {
        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
        adapter.sendToProvider(1, authReq.getDestinationUrl(true), null);
        return true;
      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
        adapter.sendToProvider(2, authReq.getDestinationUrl(false), authReq.getParameterMap());
      }
    } catch (MessageException e) {
      throw new OpenIDMessageException(e);
    } catch (ConsumerException e) {
      throw new OpenIDConsumerException(e);
    }
    return false;
  }
  protected void sendOpenIdRequest(
      ThemeDisplay themeDisplay, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    HttpSession session = request.getSession();

    LiferayPortletResponse liferayPortletResponse =
        PortalUtil.getLiferayPortletResponse(actionResponse);

    String openId = ParamUtil.getString(actionRequest, "openId");

    PortletURL portletURL = liferayPortletResponse.createActionURL();

    portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
    portletURL.setParameter(Constants.CMD, Constants.READ);
    portletURL.setParameter("struts_action", "/login/open_id");

    List<DiscoveryInformation> discoveryInformationList = _consumerManager.discover(openId);

    DiscoveryInformation discoveryInformation =
        _consumerManager.associate(discoveryInformationList);

    session.setAttribute(OpenIdWebKeys.OPEN_ID_DISCO, discoveryInformation);

    AuthRequest authRequest =
        _consumerManager.authenticate(
            discoveryInformation, portletURL.toString(), themeDisplay.getPortalURL());

    if (_userLocalService.fetchUserByOpenId(themeDisplay.getCompanyId(), openId) != null) {

      response.sendRedirect(authRequest.getDestinationUrl(true));

      return;
    }

    String screenName = getScreenName(openId);

    User user = _userLocalService.fetchUserByScreenName(themeDisplay.getCompanyId(), screenName);

    if (user != null) {
      _userLocalService.updateOpenId(user.getUserId(), openId);

      response.sendRedirect(authRequest.getDestinationUrl(true));

      return;
    }

    FetchRequest fetchRequest = FetchRequest.createFetchRequest();

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

    Map<String, String> openIdAXTypes = openIdProvider.getAxTypes();

    for (String openIdAXType : openIdAXTypes.keySet()) {
      fetchRequest.addAttribute(openIdAXType, openIdAXTypes.get(openIdAXType), true);
    }

    authRequest.addExtension(fetchRequest);

    SRegRequest sRegRequest = SRegRequest.createFetchRequest();

    sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_EMAIL, true);
    sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_FULLNAME, true);

    authRequest.addExtension(sRegRequest);

    response.sendRedirect(authRequest.getDestinationUrl(true));
  }
  @Override
  public void sendRequest(
      ThemeDisplay themeDisplay, ActionRequest actionRequest, ActionResponse actionResponse)
      throws PortalException {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    request = PortalUtil.getOriginalServletRequest(request);

    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    HttpSession session = request.getSession();

    LiferayPortletResponse liferayPortletResponse =
        PortalUtil.getLiferayPortletResponse(actionResponse);

    String openId = ParamUtil.getString(actionRequest, "openId");

    PortletURL portletURL = liferayPortletResponse.createActionURL();

    portletURL.setParameter(ActionRequest.ACTION_NAME, "/login/openid");
    portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
    portletURL.setParameter("mvcRenderCommandName", "/login/openid");
    portletURL.setParameter(Constants.CMD, Constants.READ);

    try {
      List<DiscoveryInformation> discoveryInformationList = _consumerManager.discover(openId);

      DiscoveryInformation discoveryInformation =
          _consumerManager.associate(discoveryInformationList);

      session.setAttribute(OpenIdWebKeys.OPEN_ID_DISCO, discoveryInformation);

      AuthRequest authRequest =
          _consumerManager.authenticate(
              discoveryInformation, portletURL.toString(), themeDisplay.getPortalURL());

      if (_userLocalService.fetchUserByOpenId(themeDisplay.getCompanyId(), openId) != null) {

        response.sendRedirect(authRequest.getDestinationUrl(true));

        return;
      }

      String screenName = getScreenName(openId);

      User user = _userLocalService.fetchUserByScreenName(themeDisplay.getCompanyId(), screenName);

      if (user != null) {
        _userLocalService.updateOpenId(user.getUserId(), openId);

        response.sendRedirect(authRequest.getDestinationUrl(true));

        return;
      }

      FetchRequest fetchRequest = FetchRequest.createFetchRequest();

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

      Map<String, String> openIdAXTypes = openIdProvider.getAxTypes();

      for (String openIdAXType : openIdAXTypes.keySet()) {
        fetchRequest.addAttribute(openIdAXType, openIdAXTypes.get(openIdAXType), true);
      }

      authRequest.addExtension(fetchRequest);

      SRegRequest sRegRequest = SRegRequest.createFetchRequest();

      sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_EMAIL, true);
      sRegRequest.addAttribute(_OPEN_ID_SREG_ATTR_FULLNAME, true);

      authRequest.addExtension(sRegRequest);

      response.sendRedirect(authRequest.getDestinationUrl(true));
    } catch (ConsumerException ce) {
      throw new OpenIdServiceException.ConsumerException(ce.getMessage(), ce);
    } catch (DiscoveryException de) {
      throw new OpenIdServiceException.DiscoveryException(de.getMessage(), de);
    } catch (MessageException me) {
      throw new OpenIdServiceException.MessageException(me.getMessage(), me);
    } catch (IOException ioe) {
      throw new SystemException("Unable to communicate with OpenId provider", ioe);
    }
  }
  // authentication request
  public String authRequest(
      String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
      throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print("OpenID realm wasn't initialized.");
      out.print("</h2>");

      // out.print(HTTPUtils.printStackTraceHTML(t));

      out.print("</div></body></html>");
      return null;
    }
    try {
      String returnAfterAuthentication = httpReq.getParameter("return_to");

      // configure the return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      String returnToUrl =
          httpReq.getRequestURL().toString()
              + "?is_return=true&exist_return="
              + returnAfterAuthentication;

      // 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);

      if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
        SRegRequest sregReq = SRegRequest.createFetchRequest();

        sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

        authReq.addExtension(sregReq);
      } else {

        FetchRequest fetch = FetchRequest.createFetchRequest();

        fetch.addAttribute(
            AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
        fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

        // wants up to three email addresses
        fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

        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));
        return null;

      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

        Object OPEndpoint = authReq.getDestinationUrl(false);

        ServletOutputStream out = httpResp.getOutputStream();

        httpResp.setContentType("text/html; charset=UTF-8");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("    <title>OpenID HTML FORM Redirection</title>");
        out.println("</head>");
        out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
        out.println(
            "    <form name=\"openid-form-redirection\" action=\""
                + OPEndpoint
                + "\" method=\"post\" accept-charset=\"utf-8\">");

        Map<String, String> parameterMap = authReq.getParameterMap();
        for (Entry<String, String> entry : parameterMap.entrySet()) {
          out.println(
              "	<input type=\"hidden\" name=\""
                  + entry.getKey()
                  + "\" value=\""
                  + entry.getValue()
                  + "\"/>");
        }

        out.println("        <button type=\"submit\">Continue...</button>");
        out.println("    </form>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
      }
    } catch (OpenIDException e) {
      // present error to the user
      LOG.debug("OpenIDException", e);

      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print(e.getMessage());
      out.print("</h2>");

      Throwable t = e.getCause();
      if (t != null) {
        // t can be null
        out.print(HTTPUtils.printStackTraceHTML(t));
      }

      out.print("</div></body></html>");
    }

    return null;
  }
Exemple #18
0
  @SuppressWarnings("rawtypes")
  protected void processOpenID(
      HttpServletRequest request,
      HttpServletResponse response,
      String provider,
      String returnURL,
      boolean isRegister) {
    HttpSession session = request.getSession();
    session.setAttribute(SA_REGISTRATION, isRegister);
    session.setAttribute(SA_OPENID_PROVIDER, provider);
    if (returnURL == null || returnURL.isEmpty()) {
      returnURL = "/ui/admin";
    }
    session.setAttribute(SA_RETURN_URL, returnURL);

    if (provider == null || provider.isEmpty()) {
      provider = DEFAULT_PROVIDER;
    }
    log.info("Authentication request for " + provider + (isRegister ? " (registration)" : ""));

    String responseURL = uriInfo.getBaseUri().toString() + "system/security/response";
    try {
      // perform discovery on the user-supplied identifier
      List discoveries = manager.discover(provider);

      // 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
      request.getSession().setAttribute(SA_OPENID_DISC, discovered);

      // obtain a AuthRequest message to be sent to the OpenID provider
      AuthRequest authReq = manager.authenticate(discovered, responseURL);

      if (isRegister) {
        // Attribute Exchange example: fetching the 'email' attribute
        FetchRequest fetch = FetchRequest.createFetchRequest();
        if (provider.contains("google.com")) {
          //                    fetch.addAttribute(AP_EMAIL, "http://axschema.org/contact/email",
          // false);
          fetch.addAttribute(AP_FIRST_NAME, "http://axschema.org/namePerson/first", true);
          fetch.addAttribute(AP_LAST_NAME, "http://axschema.org/namePerson/last", true);
        } else if (provider.contains("yahoo.com")) {
          //                    fetch.addAttribute(AP_EMAIL, "http://axschema.org/contact/email",
          // false);
          fetch.addAttribute(AP_FULL_NAME, "http://axschema.org/namePerson", true);
        } else { // works for myOpenID
          //                    fetch.addAttribute(AP_EMAIL,
          // "http://schema.openid.net/contact/email", false);
          fetch.addAttribute(AP_FULL_NAME, "http://schema.openid.net/namePerson", true);
        }

        // attach the extension to the authentication request
        authReq.addExtension(fetch);
      }

      // For version2 endpoints can do a form-redirect but this is easier,
      // Relies on payload being less ~ 2k, currently ~ 800 bytes
      response.sendRedirect(authReq.getDestinationUrl(true));
    } catch (Exception e) {
      throw new WebApplicationException(e);
    }
  }