private ServerManager getServerManager() {
    ServerManager manager =
        (ServerManager)
            IWMainApplication.getDefaultIWApplicationContext()
                .getApplicationAttribute(OpenIDConstants.ATTRIBUTE_SERVER_MANAGER);
    if (manager == null) {
      String endPointUrl =
          IWMainApplication.getDefaultIWApplicationContext()
              .getApplicationSettings()
              .getProperty(OpenIDConstants.PROPERTY_END_POINT_URL, "http://localhost:8080/");
      String userSetupUrl =
          IWMainApplication.getDefaultIWApplicationContext()
              .getApplicationSettings()
              .getProperty(
                  OpenIDConstants.PROPERTY_USER_SETUP_URL,
                  "http://localhost:8080/pages/profile/?doRedirect=true");

      manager = new ServerManager();
      manager.setSharedAssociations(new InMemoryServerAssociationStore());
      manager.setPrivateAssociations(new InMemoryServerAssociationStore());

      manager.setOPEndpointUrl(endPointUrl);
      manager.setUserSetupUrl(userSetupUrl);
      IWMainApplication.getDefaultIWApplicationContext()
          .setApplicationAttribute(OpenIDConstants.ATTRIBUTE_SERVER_MANAGER, manager);
    }

    return manager;
  }
  protected boolean doRedirectToLoginPage(
      ServerManager manager, ParameterList requestParameters, IWContext iwc, String realm) {
    boolean goToLogin = true;
    // Log user out if this is an authentication request for a new association
    // (i.e. another Relying Party or an expired association) or if this is a new request
    // after a completed successful one (loginExpireTime is removed on successful login)
    String loginExpireHandle =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_ASSOCIATE_HANDLE)
            ? "openid-login-"
                + requestParameters.getParameterValue(OpenIDConstants.PARAMETER_ASSOCIATE_HANDLE)
            : null;
    Date currentTime = new Date();
    if (loginExpireHandle == null) {
      String simpleRegHandle = "openid-simpleRegHandle-" + realm;
      Date loginExpirationTime = (Date) iwc.getSessionAttribute(simpleRegHandle);

      if (loginExpirationTime == null || currentTime.after(loginExpirationTime)) {
        if (iwc.isLoggedOn()) {
          // Make user log in again
          LoginBusinessBean loginBusiness = getLoginBusiness(iwc.getRequest());
          loginBusiness.logOutUser(iwc);
        }
        int expireInMilliSeconds = manager.getExpireIn() * 1000;
        iwc.setSessionAttribute(
            simpleRegHandle, new Date(currentTime.getTime() + expireInMilliSeconds));
        goToLogin = true;
      } else {
        // coming here again in the same request/association
        goToLogin = !iwc.isLoggedOn();
      }
    } else {
      Date loginExpirationTime = (Date) iwc.getSessionAttribute(loginExpireHandle);

      if (loginExpirationTime == null || currentTime.after(loginExpirationTime)) {
        if (iwc.isLoggedOn()) {
          // Make user log in again
          LoginBusinessBean loginBusiness = getLoginBusiness(iwc.getRequest());
          loginBusiness.logOutUser(iwc);
        }
        int expireInMilliSeconds = manager.getExpireIn() * 1000;
        iwc.setSessionAttribute(
            loginExpireHandle, new Date(currentTime.getTime() + expireInMilliSeconds));
        goToLogin = true;
      } else {
        // coming here again in the same request/association
        goToLogin = !iwc.isLoggedOn();
      }
    }
    return goToLogin;
  }
示例#3
0
  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);
    }
  }
示例#4
0
  OpenIdTestService(
      String url,
      Map<IdProperty, String> props,
      Set<String> teams,
      List<ProcessExtension> extensions) {
    this.url = url;
    this.endpointUrl = url + "endpoint";

    this.props = props;
    this.teams = teams;
    this.extensions = extensions;

    manager = new ServerManager();
    manager.setSharedAssociations(new InMemoryServerAssociationStore());
    manager.setPrivateAssociations(new InMemoryServerAssociationStore());
    manager.setOPEndpointUrl(endpointUrl);
  }
示例#5
0
  public HttpResponse doEndpoint(StaplerRequest request) throws IOException {
    final ParameterList requestp = new ParameterList(request.getParameterMap());
    final String mode = requestp.getParameterValue("openid.mode");
    final String realm = getRealm(requestp);

    if ("associate".equals(mode)) {
      // --- process an association extend ---
      return new MessageResponse(manager.associationResponse(requestp));
    } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {

      // No need to redirect to a page with an HTML form
      // Skip the authentication step

      String identity = getUserIdentity();
      Message rsp = manager.authResponse(requestp, identity, identity, true, false);
      try {
        respondToExtensions(requestp, rsp);
      } catch (MessageException ex) {
        throw new OperationFailure(ex.getMessage());
      }

      // Need to sign after because SReg extension parameters are signed by openid4java
      if (rsp instanceof AuthSuccess) {
        try {
          manager.sign((AuthSuccess) rsp);
        } catch (ServerException e) {
          throw new OperationFailure(e.getMessage());
        } catch (AssociationException e) {
          throw new OperationFailure(e.getMessage());
        }
      }

      return new HttpRedirect(rsp.getDestinationUrl(true));
    } else if ("check_authentication".equals(mode)) {
      return new MessageResponse(manager.verify(requestp));
    } else {
      throw new OperationFailure("Unknown extend: " + mode);
    }
  }
  protected void redirectToLoginPage(
      HttpServletRequest req,
      HttpServletResponse resp,
      ParameterList requestParameters,
      OpenIDServerBean serverBean,
      ServerManager manager)
      throws IOException {
    String URL =
        req.getScheme()
            + "://"
            + req.getServerName()
            + (req.getServerPort() != 80 ? ":" + req.getServerPort() : "")
            + req.getRequestURI();

    String queryString = req.getQueryString();
    if (queryString != null) {
      URL += "?" + queryString;
    }

    serverBean.setServerUrl(URL);
    serverBean.setParameterList(requestParameters);

    serverBean.setDoRedirect(Boolean.TRUE);

    String identity = requestParameters.getParameterValue("openid.claimed_id");
    if (identity == null) {
      identity = requestParameters.getParameterValue("openid.identity");
    }

    if (identity != null) {
      String subdomain = new OpenIDUtil().getSubDomain(identity);
      serverBean.setUsername(subdomain);
    }

    resp.sendRedirect(manager.getUserSetupUrl());
  }
  @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);
  }
  private Representation handle(ParameterList request) {
    Logger log = getLogger();
    log.info("Handle on OP");
    ConcurrentMap<String, Object> attribs = getContext().getAttributes();
    ServerManager manager = (ServerManager) attribs.get("openid_manager");
    log.info("OP endpoint = " + manager.getOPEndpointUrl());

    String mode =
        request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null;

    Message response;
    String responseText;

    if ("associate".equals(mode)) {
      // --- process an association request ---
      response = manager.associationResponse(request);
      responseText = response.keyValueFormEncoding();
    } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
      // interact with the user and obtain data needed to continue
      List<?> userData = userInteraction(request, manager.getOPEndpointUrl());

      String userSelectedId = (String) userData.get(0);
      String userSelectedClaimedId = (String) userData.get(1);
      Boolean authenticatedAndApproved = (Boolean) userData.get(2);

      // --- process an authentication request ---
      response =
          manager.authResponse(
              request,
              userSelectedId,
              userSelectedClaimedId,
              authenticatedAndApproved.booleanValue());

      if (response instanceof DirectError) {
        Form f = new Form();
        @SuppressWarnings("unchecked")
        Map<String, String> m = (Map<String, String>) response.getParameterMap();
        for (String key : m.keySet()) {
          f.add(key, m.get(key));
        }
        return f.getWebRepresentation();
      } else {
        // caller will need to decide which of the following to use:

        // option1: GET HTTP-redirect to the return_to URL
        // return new
        // StringRepresentation(response.getDestinationUrl(true));
        redirectSeeOther(response.getDestinationUrl(true));
        return new EmptyRepresentation();

        // option2: HTML FORM Redirection
        // RequestDispatcher dispatcher =
        // getServletContext().getRequestDispatcher("formredirection.jsp");
        // httpReq.setAttribute("prameterMap",
        // response.getParameterMap());
        // httpReq.setAttribute("destinationUrl",
        // response.getDestinationUrl(false));
        // dispatcher.forward(request, response);
        // return null;
      }
    } else if ("check_authentication".equals(mode)) {
      // --- processing a verification request ---
      response = manager.verify(request);
      log.info("OpenID : " + response.keyValueFormEncoding());
      responseText = response.keyValueFormEncoding();
    } else if (Method.GET.equals(getMethod())) {
      // Could be a discovery request
      sendXRDSLocation();
      return new StringRepresentation("XRDS Discovery Information");
    } else {
      // --- error response ---
      response = DirectError.createDirectError("Unknown request");
      responseText = response.keyValueFormEncoding();
    }

    // return the result to the user
    return new StringRepresentation(responseText);
  }