public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    logger.debug("servlet path info = {}", request.getPathInfo());

    if ("/verify".equals(request.getPathInfo())) {
      logger.info("Verify OpenId auth response.");

      try {
        Identifier id = this.consumer.verifyResponse(request);
        if (id == null) {
          logger.info("Access denied");
          this.onAccessDenied(request, response);
          return;
        }

        logger.info("openid identifier = {}", id.getIdentifier());
        this.onAccessGranted(request, response);
        return;
      } catch (OpenIDException e) {
        throw new ServletException(e);
      }
    }

    try {
      logger.info("Send OpenId auth request.");
      AuthRequest authReq = this.consumer.authRequest(this.publicIdentifier, request, response);
      request.setAttribute("message", authReq);
      request.getRequestDispatcher(this.returnToUrl).forward(request, response);
    } catch (OpenIDException e) {
      throw new ServletException(e);
    }
  }
예제 #2
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;
  }
  /*
   * This method is a call method used by the initialize method to verify the
   * OpenId received by the Intuit OpenID Provider.
   */
  @RequestMapping(value = "/verifyopenid.htm", method = RequestMethod.GET)
  public String verifyOpenIDFromIntuit(final HttpServletRequest request) {

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

    String redirectTo;

    final HttpSession session = request.getSession();
    final OpenIDHelper openIDHelper = new OpenIDHelper();

    final Identifier identifier = openIDHelper.verifyResponse(request);
    LOG.info("OpenID identifier:" + ((identifier == null) ? "null" : identifier.getIdentifier()));

    final String identity = request.getParameter("openid.identity");
    LOG.info("openid.identity: " + identity);

    final String firstName = request.getParameter("openid.alias3.value.alias1");
    LOG.info("openid.alias3.value.alias1: " + firstName);

    final String lastName = request.getParameter("openid.alias3.value.alias2");
    LOG.info("openid.alias3.value.alias2: " + lastName);

    final String email = request.getParameter("openid.alias3.value.alias3");
    LOG.info("openid.alias3.value.alias3: " + email);

    final String realmId = request.getParameter("openid.alias3.value.alias4");
    LOG.info("openid.alias3.value.alias4: " + realmId);

    session.setAttribute("openIDidentity", identity);
    session.setAttribute("firstName", firstName);
    session.setAttribute("lastName", lastName);
    session.setAttribute("email", email);
    session.setAttribute("openidstatus", "verified");
    session.setAttribute("connectionStatus", "not_authorized");

    LOG.info("### OpenIdController -> verifyOpenIDFromIntuit() - completed ###");

    if (request.getSession().getAttribute("isLinkingRequired") != null
        && request.getSession().getAttribute("isLinkingRequired").equals("true")) {
      redirectTo = "directconnect";
    } else {
      redirectTo = "redirect:/home.htm";
    }

    return redirectTo;
  }
예제 #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;
  }
  // 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;
  }
예제 #6
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");
  }