Ejemplo n.º 1
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;
  }
  @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;
  }
  @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);
    }
  }
Ejemplo n.º 4
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);
    }
  }
Ejemplo n.º 5
0
  /**
   * 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;
  }
  // 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;
  }
Ejemplo n.º 7
0
  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));
  }