Example usage for javax.servlet.http HttpSession invalidate

List of usage examples for javax.servlet.http HttpSession invalidate

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession invalidate.

Prototype

public void invalidate();

Source Link

Document

Invalidates this session then unbinds any objects bound to it.

Usage

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
 * {@inheritDoc}//from   ww w. j  av a  2  s. c  o m
  */
public HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException {

    // get the current session
    HttpSession oldSession = request.getSession();

    // make a copy of the session content
    Map<String, Object> temp = new ConcurrentHashMap<String, Object>();
    Enumeration e = oldSession.getAttributeNames();
    while (e != null && e.hasMoreElements()) {
        String name = (String) e.nextElement();
        Object value = oldSession.getAttribute(name);
        temp.put(name, value);
    }

    // kill the old session and create a new one
    oldSession.invalidate();
    HttpSession newSession = request.getSession();
    User user = ESAPI.authenticator().getCurrentUser();
    user.addSession(newSession);
    user.removeSession(oldSession);

    // copy back the session content
    for (Map.Entry<String, Object> stringObjectEntry : temp.entrySet()) {
        newSession.setAttribute(stringObjectEntry.getKey(), stringObjectEntry.getValue());
    }
    return newSession;
}

From source file:com.ikon.servlet.ValidateLicenseServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Validating License");
    LicenseManager licenseManager = null;
    HttpSession httpSession = request.getSession();

    /*if(LICENSE_PATH.isFile()){
       if(remainingDays()>0){/*from  w w  w  .  ja va2  s .  c om*/
    request.setAttribute("DAYS_LEFT", "Trial Days Left : " + remainingDays());
    request.getRequestDispatcher("./login.jsp").forward(request, response);   
       } else {
    LICENSE_PATH.delete();
       }
    }*/

    try {

        if (licenseManager == null) {
            licenseManager = LicenseManager.getInstance();
        }

        if (licenseManager.isValid()) { //checks for unauthorized license modifications   
            if (licenseManager.getFeature("MAC Address").equals(getMacAddress())
                    || licenseManager.getFeature("MAC Address").equals(SKIP_MACID_CHECK)) {
                if (licenseManager.daysLeft() > 0) {
                    HttpSessionManager.getInstance().add(request);
                    List<HttpSessionInfo> httpSessionInfos = HttpSessionManager.getInstance().getSessions();
                    logger.info("Number of users online : " + httpSessionInfos.size());
                    if (httpSessionInfos.size() > Integer
                            .parseInt(licenseManager.getFeature("Number of Users"))) {
                        logger.info("Max users Logged in");
                        httpSession.invalidate();
                        throw new LicenseException("Max users have logged in. Please wait.");
                    } else {
                        httpSession.setAttribute("DAYS_LEFT",
                                "Days Left : " + String.valueOf(licenseManager.daysLeft()));
                        request.getRequestDispatcher("./index.jsp").forward(request, response);
                    }
                } else {
                    logger.info("License is expired");
                    throw new LicenseException("License is expired.");
                }

            } else {
                logger.info("Mac Id mismatch");
                throw new LicenseException("MacId of the server seems to be changed.");
            }

        } else {
            logger.info("License had been modified");
            throw new LicenseException("License could not be read/expired.");
        }
    } catch (LicenseException exception) {
        request.setAttribute("ERROR", exception.getMessage());
        request.setAttribute("SUPPORT", "Please contact support@writercorporation.com");
        request.getRequestDispatcher("./info.jsp").forward(request, response);
    } catch (RuntimeException exception) {
        request.setAttribute("ERROR", "License could not be found");
        request.setAttribute("SUPPORT", "Please contact support@writercorporation.com");
        request.getRequestDispatcher("./info.jsp").forward(request, response);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

}

From source file:org.tolven.web.RegisterAction.java

/**
 * <p>Register a new user. /*from   www  .j a  v a2s. c o  m*/
 * After the registration form has collected initial information such as username and password,
 * begin the registration process. We'll generate and send an eMail to validate the user's email address.
 * The message will contain a link to an invitation, that we create, that allows us to finish the
 * process.</p> 
 * <p> In this method, we take the UID and add it as an email address to LDAP. Thus, user id is email address of user. </p>
 */
/*
public String register() throws Exception {
   if (!Boolean.parseBoolean(getTolvenPropertiesBean().getProperty("tolven.login.create.activatedUser"))) {
  throw new SecurityException( "tolven property tolven.login.create.activatedUser must be true");
   }
boolean error = false;
// Make the UID the email address
String separateUID = getTolvenPropertiesBean().getProperty("tolven.register.separateUID");
if (separateUID==null || !Boolean.parseBoolean(separateUID)) {
     getTp().addMail( getTp().getUid() );
}
if (!getRepeatUid().equals(getTp().getPrimaryMail())) {
    FacesContext.getCurrentInstance().addMessage( "register:email", new FacesMessage("Both email addresses must match"));
    error = true;
}
if (!getTp().getPrimaryMail().matches("[\\w\\.\\_\\-\\@]+") ) {
    FacesContext.getCurrentInstance().addMessage( "register:email", new FacesMessage("Does not appear to be a valid email address"));
    error = true;
}
if (getTp().getOrganizationUnitName() == null || getTp().getOrganizationUnitName().trim().length() == 0) {
    FacesContext.getCurrentInstance().addMessage( "register:organizationUnitName", new FacesMessage("An Organization Unit Name is required"));
    error = true;
}
if (getTp().getOrganizationName() == null || getTp().getOrganizationName().trim().length() == 0) {
    FacesContext.getCurrentInstance().addMessage( "register:organizationName", new FacesMessage("An Organization Name is required"));
    error = true;
}
if (getTp().getStateOrProvince() == null || getTp().getStateOrProvince().trim().length() == 0) {
    FacesContext.getCurrentInstance().addMessage( "register:stateOrProvince", new FacesMessage("A State Or Province is required"));
    error = true;
}
if (getTp().getCountryName() == null || getTp().getCountryName().trim().length() == 0) {
    FacesContext.getCurrentInstance().addMessage( "register:countryName", new FacesMessage("A Country Name is required"));
    error = true;
}
if (!getRepeatUserPassword().equals(getTp().getUserPassword())) {
    FacesContext.getCurrentInstance().addMessage( "register:userPassword2", new FacesMessage("Both passwords must match"));
    error = true;
}
if (error) return "error";
getTp().setCn( getTp().getGivenName() + " " + getTp().getSn());
// Verify email address is unique in LDAP
if (getLDAPLocal().entryExists( tp.getUid() )) {
   FacesContext.getCurrentInstance().addMessage( "register:uid", new FacesMessage("This id is already in use, please select another"));
   return "error";
}
String returnStatus = null;
// Option to register with activation (or without - for demo)
if (this.isNoActivation()) {
  try {
      getLoginBean().registerAndActivate( tp, getNow() );
 } catch (Throwable e) {
    while (e.getCause()!=null) {
       if (e.getCause() instanceof NoResultException ) {
          FacesContext.getCurrentInstance().addMessage( "register:referenceCode", new FacesMessage("Invalid Reference Code"));
          return "error";
       }
       e = e.getCause();
    }
    throw new TolvenSecurityException( "Error Registering user: " + getTp().getUid(), e);
 }
 returnStatus = Status.ACTIVATED.value();
 // Make the user available to top (session)
 getTop().setTp(tp);
} else {
  try {
       HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
       // Create the user and the invitation. The user will be invited to join a new, empty account.
       // Other invitations may reference an existing account or a referral account.
      getLoginBean().register( getTp(), getNow(), request.getLocalAddr());
 } catch (Throwable e) {
    while (e.getCause()!=null) {
       if (e.getCause() instanceof NoResultException ) {
          FacesContext.getCurrentInstance().addMessage( "register:referenceCode", new FacesMessage("Invalid Reference Code"));
          return "error";
       }
       e = e.getCause();
    }
    if (e instanceof Exception) throw (Exception)e;
 }
 returnStatus = Status.REGISTERED.value();
        
}
// Invite the user to join a new Tolven account (this could be optional if the user is expecting an invitation from someone else
// inviting the user to join their account). but right now, we do it automatically.
// Before we're done, we must invalidate session.
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.invalidate();
         
return returnStatus;
}
*/
/*
 * TODO Note that this method is only here for backward compatibility. The only users who should be entering this information, should be
 * those we had the old-style DB UserPrivateKey, and are converting those into the new userPKCS12 key in LDAP
 */
public String updateCertInfo() throws Exception {
    boolean error = false;
    if (getTp().getOrganizationUnitName() == null || getTp().getOrganizationUnitName().trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:organizationUnitName",
                new FacesMessage("An Organization Unit Name is required"));
        error = true;
    }
    if (getTp().getOrganizationName() == null || getTp().getOrganizationName().trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:organizationName",
                new FacesMessage("An Organization Name is required"));
        error = true;
    }
    if (getTp().getStateOrProvince() == null || getTp().getStateOrProvince().trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:stateOrProvince",
                new FacesMessage("A State Or Province is required"));
        error = true;
    }
    if (getTp().getCountryName() == null || getTp().getCountryName().trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:countryName",
                new FacesMessage("A Country Name is required"));
        error = true;
    }
    if (getOldUserPassword() == null || getOldUserPassword().trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:oldUserPassword",
                new FacesMessage("A password is required"));
        error = true;
    }
    if (!getLDAPLocal().verifyPassword(getTp().getUid(), getOldUserPassword().toCharArray())) {
        FacesContext.getCurrentInstance().addMessage("createCertificate:oldUserPassword",
                new FacesMessage("Incorrect password"));
        error = true;
    }
    if (error)
        return "error";
    /*
     * The user needs to logout in order for the credentials to be added to the Subject
     */
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
            .getSession(false);
    session.invalidate();
    return "success";
}

From source file:org.infoscoop.web.SessionManagerFilter.java

private String getUidFromSession(HttpServletRequest req) {
    HttpSession session = req.getSession(true);
    String uid = (String) session.getAttribute("Uid");
    String sessionId = req.getHeader("MSDPortal-SessionId");
    boolean uidIgnoreCase = SessionCreateConfig.getInstance().isUidIgnoreCase();

    if ("true".equalsIgnoreCase(req.getParameter(CheckDuplicateUidFilter.IS_PREVIEW))) {
        String uidParam = req.getParameter("Uid");
        if (uid.equalsIgnoreCase(uidParam)) {
            uid = uidParam;/*ww w  . j av  a  2  s . c o m*/
            session.setAttribute("Uid", uid);
        }
    } else if (uidIgnoreCase && uid != null) {
        uid = uid.toLowerCase();

        session.setAttribute("Uid", uid);
    }

    if (uid == null) {
        if (sessionId != null) {
            session.setAttribute(LOGINUSER_SESSION_ID_ATTR_NAME, sessionId);
            return SessionDAO.newInstance().getUid(sessionId);
        }
    } else if (sessionId != null) {
        String oldSessionId = (String) session.getAttribute(LOGINUSER_SESSION_ID_ATTR_NAME);
        if (oldSessionId != null && !sessionId.equals(oldSessionId)) {
            session.invalidate();
            session = req.getSession(true);
            session.setAttribute(LOGINUSER_SESSION_ID_ATTR_NAME, sessionId);
            return SessionDAO.newInstance().getUid(sessionId);
        }
    }
    return uid;
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    HttpSession session = request.getSession();

    try {//w  w w .j a  v  a 2  s. c  om

        SliApi.setBaseUrl(apiUrl);

        // Setup OAuth service
        OAuthService service = new ServiceBuilder().provider(SliApi.class)
                .apiKey(propDecryptor.getDecryptedClientId())
                .apiSecret(propDecryptor.getDecryptedClientSecret()).callback(callbackUrl).build();

        // Check cookies for token, if found insert into session
        boolean cookieFound = checkCookiesForToken(request, session);

        Object token = session.getAttribute(OAUTH_TOKEN);

        if (token == null && request.getParameter(OAUTH_CODE) == null) {
            // Initiate authentication
            initiatingAuthentication(request, response, session, service);
        } else if (token == null && request.getParameter(OAUTH_CODE) != null) {
            // Verify authentication
            verifyingAuthentication(request, response, session, service);
        } else {
            // Complete authentication
            completeAuthentication(request, response, session, token, cookieFound);
        }
    } catch (OAuthException ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
        return;
    } catch (Exception ex) {
        session.invalidate();
        LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() });
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        return;
    }
}

From source file:byps.http.HHttpServlet.java

/**
 * Get first BYPS session from application server's session. Old client
 * applications do not send the session ID in the BMessageHeader. For this
 * clients, the BYPS session is found in the application server's session.
 * /*from www  .j  a v a2s  .  c o m*/
 * @param hsess
 *          Application server's session.
 * @return BYPS session, or null
 */
protected synchronized HSession getFirstBypsSessionFromHttpSession(HttpSession hsess) {
    HSession ret = null;
    try {
        HHttpSessionObject sessObj = (HHttpSessionObject) hsess
                .getAttribute(HConstants.HTTP_SESSION_BYPS_SESSIONS);
        if (sessObj != null) {
            ret = sessObj.getFirstSessionOrNull();
        }
        if (ret == null) {
            hsess.invalidate();
        }
    } catch (IllegalStateException ignored) {
        // HttpSession could be already invalidated.
    }
    return ret;
}

From source file:org.opencms.workplace.CmsLogin.java

/**
 * Returns the HTML for the login dialog in it's current state.<p>
 * //  w  ww. j av  a  2  s  .c om
 * @return the HTML for the login dialog
 * 
 * @throws IOException in case a redirect fails
 */
public String displayDialog() throws IOException {

    if ((OpenCms.getSiteManager().getSites().size() > 1)
            && !OpenCms.getSiteManager().isWorkplaceRequest(getRequest())) {

        // this is a multi site-configuration, but not a request to the configured Workplace site
        StringBuffer loginLink = new StringBuffer(256);
        loginLink.append(OpenCms.getSiteManager().getWorkplaceSiteMatcher().toString());
        loginLink.append(getFormLink());
        // send a redirect to the workplace site
        getResponse().sendRedirect(loginLink.toString());
        return null;
    }

    CmsObject cms = getCmsObject();

    m_message = null;
    if (cms.getRequestContext().getCurrentUser().isGuestUser()) {
        // user is not currently logged in
        m_action = ACTION_DISPLAY;
        m_username = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_USERNAME);
        if (m_username != null) {
            // remove white spaces, can only lead to confusion on user name
            m_username = m_username.trim();
        }
        m_password = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PASSWORD);
        m_actionLogin = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGIN);
        m_oufqn = getRequest().getParameter(PARAM_OUFQN);
        if (m_oufqn == null) {
            m_oufqn = getPreDefOuFqn();
        }
        if (OpenCms.getLoginManager().isEnableSecurity()) {
            // security option is enabled, try to get PC type from request parameter
            m_pcType = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_PCTYPE);
        } else {
            // if security option is disabled, just set PC type to "private" to get common login dialog
            m_pcType = PCTYPE_PRIVATE;
        }
        // try to get some info from a cookie
        getCookieData();

        // set PC type to "public" as default if not already set by cookie, request or if security option is disabled
        if (m_pcType == null) {
            m_pcType = PCTYPE_PUBLIC;
        }
    } else {
        // user is already logged in
        m_oufqn = cms.getRequestContext().getOuFqn();
        m_action = ACTION_LOGIN;
        m_actionLogout = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_LOGOUT);
    }

    if (m_oufqn == null) {
        m_oufqn = CmsOrganizationalUnit.SEPARATOR;
    }

    String actionGetOus = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_ACTION_GETOULIST);
    if (Boolean.TRUE.toString().equals(actionGetOus)) {
        return getJsonOrgUnitList();
    }

    // initialize the right ou
    m_ou = null;
    try {
        m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
    } catch (CmsException e) {
        m_oufqn = CmsOrganizationalUnit.SEPARATOR;
        try {
            m_ou = OpenCms.getOrgUnitManager().readOrganizationalUnit(getCmsObject(), m_oufqn);
        } catch (CmsException exc) {
            LOG.error(exc.getLocalizedMessage(), exc);
        }
    }

    // initialize the requested resource
    m_requestedResource = CmsRequestUtil.getNotEmptyParameter(getRequest(),
            CmsWorkplaceManager.PARAM_LOGIN_REQUESTED_RESOURCE);
    if (m_requestedResource == null) {
        // no resource was requested, use default workplace URI
        m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
    }

    if (Boolean.valueOf(m_actionLogin).booleanValue()) {
        // login was requested
        if ((m_username == null) && (m_password == null)) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_DATA_0);
        } else if (m_username == null) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_NAME_0);
        } else if (m_password == null) {
            m_message = Messages.get().container(Messages.GUI_LOGIN_NO_PASSWORD_0);
        } else if ((m_username != null) && (m_password != null)) {

            // try to login with the given user information
            login((m_oufqn == null ? CmsOrganizationalUnit.SEPARATOR : m_oufqn) + m_username, m_password);

            if (getLoginException() == null) {
                // the login was successful
                m_action = ACTION_LOGIN;

                // set the default project of the user
                CmsUserSettings settings = new CmsUserSettings(cms);

                // get the direct edit path
                m_directEditPath = getDirectEditPath(settings);

                try {
                    CmsProject project = cms.readProject(settings.getStartProject());
                    if (OpenCms.getOrgUnitManager().getAllAccessibleProjects(cms, project.getOuFqn(), false)
                            .contains(project)) {
                        // user has access to the project, set this as current project
                        cms.getRequestContext().setCurrentProject(project);
                    }
                } catch (CmsException e) {
                    // unable to set the startup project, bad but not critical
                    LOG.warn(Messages.get().getBundle().key(Messages.LOG_LOGIN_NO_STARTUP_PROJECT_2, m_username,
                            settings.getStartProject()), e);
                }
            } else {
                // there was an error during login

                if (org.opencms.security.Messages.ERR_LOGIN_FAILED_DISABLED_2 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // the user account is disabled
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_DISABLED_0);
                } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_TEMP_DISABLED_4 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // the user account is temporarily disabled because of too many login failures
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_TEMP_DISABLED_0);
                } else if (org.opencms.security.Messages.ERR_LOGIN_FAILED_WITH_MESSAGE_1 == getLoginException()
                        .getMessageContainer().getKey()) {
                    // all logins have been disabled be the Administration
                    CmsLoginMessage loginMessage = OpenCms.getLoginManager().getLoginMessage();
                    if (loginMessage != null) {
                        m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_WITH_MESSAGE_1,
                                loginMessage.getMessage());
                    }
                }
                if (m_message == null) {
                    // any other error - display default message
                    m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_0);
                }
            }
        }
    } else if (Boolean.valueOf(m_actionLogout).booleanValue()) {
        m_action = ACTION_LOGOUT;
        // store the workplace window data
        Cookie wpDataCookie = getCookie(COOKIE_WP_DATA);
        String wpData = CmsRequestUtil.getNotEmptyParameter(getRequest(), PARAM_WPDATA);
        if (wpData != null) {
            wpData = CmsEncoder.escapeXml(wpData);
            wpDataCookie.setValue(wpData);
            setCookie(wpDataCookie, false);
        }
        // after logout this will automatically redirect to the login form again
        logout();
        return null;
    }

    if (m_action == ACTION_LOGIN) {
        // clear message
        m_message = null;
        // login is successful, check if the requested resource can be read
        CmsUriSplitter splitter = new CmsUriSplitter(m_requestedResource, true);
        String resource = splitter.getPrefix();
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(resource)) {
            // bad resource name, use workplace as default
            resource = CmsFrameset.JSP_WORKPLACE_URI;
        }
        if (!getCmsObject().existsResource(resource, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
            // requested resource does either not exist or is not readable by user
            if (CmsFrameset.JSP_WORKPLACE_URI.equals(resource)) {
                // we know the Workplace exists, so the user does not have access to the Workplace
                // probably this is a "Guest" user in a default setup where "Guest" has no access to the Workplace
                m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_NO_WORKPLACE_PERMISSIONS_0);
                m_action = ACTION_DISPLAY;
            } else if (getCmsObject().existsResource(CmsFrameset.JSP_WORKPLACE_URI)) {
                // resource does either not exist or is not readable, but general workplace permissions are granted
                m_message = Messages.get().container(Messages.GUI_LOGIN_UNKNOWN_RESOURCE_1,
                        m_requestedResource);
                m_requestedResource = CmsFrameset.JSP_WORKPLACE_URI;
            } else {
                // resource does not exist and no general workplace permissions granted
                m_message = Messages.get().container(Messages.GUI_LOGIN_FAILED_NO_TARGET_PERMISSIONS_1,
                        m_requestedResource);
                m_action = ACTION_DISPLAY;
            }
        }
        if (m_action == ACTION_DISPLAY) {
            // the login was invalid
            m_requestedResource = null;
            // destroy the generated session
            HttpSession session = getRequest().getSession(false);
            if (session != null) {
                session.invalidate();
            }
        } else {
            // successfully logged in, so set the cookie
            setCookieData();
        }
    }

    return displayLoginForm();
}

From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    logger.info("doPost");
    QuestionHelper.initQuestionsOptions(req);

    try {//from ww  w.  j  a v a  2  s .c o  m
        String servletPath = req.getServletPath();
        logger.debug("getServletPath  |" + servletPath + "|");
        if (servletPath.equals(Constants.SERVLET_URI + "/login")) {
            doLogin(req, resp);
        } else if (servletPath.equals(Constants.SERVLET_URI + "/promptUserID")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                req.getSession().setAttribute(Constants.ACTION_TOKEN, Constants.VALIDATE_TOKEN); //CADSRPASSW-90 //CADSRPASSW-91
                doValidateUserQuestionsForPasswordChange(req, resp); //CADSRPASSW-76
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/changePassword")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                req.getSession().setAttribute(Constants.ACTION_TOKEN, Constants.CHANGE_TOKEN);
                doChangePassword(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/saveQuestions")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                req.getSession().setAttribute(Constants.ACTION_TOKEN, Constants.SAVE_TOKEN);
                doSaveQuestions(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/promptUserQuestions")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                doRequestUserQuestions(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion1")) {
            doQuestion1(req, resp);
        } else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion2")) {
            doQuestion2(req, resp);
        } else if (servletPath.equals(Constants.SERVLET_URI + "/promptQuestion3")) {
            doQuestion3(req, resp);
        } else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion1")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                doValidateQuestion1(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion2")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                doValidateQuestion2(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/validateQuestion3")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                doValidateQuestion3(req, resp);
            }
        } else if (servletPath.equals(Constants.SERVLET_URI + "/resetPassword")) {
            if (req.getParameter("cancel") != null) {
                resp.sendRedirect(Constants.LANDING_URL);
            } else {
                doChangePassword2(req, resp);
            }
        } else {
            // this also catches the intentional logout with path /logout 
            logger.info("logging out because of invalid servlet path");
            HttpSession session = req.getSession(false);
            if (session != null) {
                logger.debug("non-null session");
                session.invalidate();
            }
            resp.sendRedirect("./jsp/loggedOut.jsp");
        }
    } catch (Throwable theException) {
        logger.error(CommonUtil.toString(theException));
    }
}

From source file:org.CloudOps.laas.ws.login.java

private Boolean checkAuthorization(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException, IOException {
    HttpSession session = request.getSession();
    if (session == null || session.getAttribute("apikey") == null) {
        // no session or not authenticate
        // Check for HTTP header: Authorization
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            StringTokenizer st = new StringTokenizer(authHeader);
            if (st.hasMoreTokens()) {
                String basic = st.nextToken();

                if (basic.equalsIgnoreCase("Basic")) {
                    String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                    log.debug("Credentials: " + credentials);
                    int p = credentials.indexOf(":");
                    if (p != -1) {
                        String login = credentials.substring(0, p).trim();
                        String password = credentials.substring(p + 1).trim();

                        reloadApikeys();

                        if (apikeys.containsKey(login) && apikeys.get(login).equals(password)) {
                            log.debug("APIKEY '" + login + "' authenticated");
                            if (session != null)
                                session.invalidate();
                            session = request.getSession(true);
                            session.setAttribute("apikey", login);

                            return true;
                        } else {
                            log.info("Invalid APIKEY(" + login + ":" + password + ")");
                        }/*from   w ww.j  a v a  2s  .co  m*/
                    } else {
                        log.error("Invalid authentication token " + authHeader);
                    }
                } else {
                    log.warn("Unsupported HTTP authentication method '" + basic
                            + "', Authorization HTTP header: '" + authHeader + "'");
                }
            } else {
                log.warn("Invalid HTTP authentication request '" + authHeader + "'");
            }
        }
        if (noAuthenticationFor != null) {
            // an authentication bypass configured
            String clientIP = request.getHeader("X-Real-IP");
            if (clientIP == null)
                clientIP = request.getRemoteAddr();
            Matcher m = noAuthenticationFor.matcher(clientIP);
            if (m.find()) {
                if (session != null) {
                    session.invalidate();
                }
                // create a new session, everytime for security reason
                session = request.getSession(true);
                session.setAttribute("apikey", "BYPASS");

                log.info("checkAuthorization from Authentication Bypassed for '" + clientIP + "'");
                return true;
            }
            log.info("checkAuthorization from Authentication required for '" + clientIP + "'");
        }
    }

    return false;
}

From source file:com.neu.controller.LoginController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource");

    String action = request.getParameter("action");
    ModelAndView mv = new ModelAndView();

    HttpSession session = request.getSession();

    if (action.equalsIgnoreCase("login")) {
        try {/*from  w w  w.j ava2s  .  com*/
            String userName = request.getParameter("user");
            String password = request.getParameter("password");
            QueryRunner run = new QueryRunner(ds);
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[2];
            params[0] = userName;
            params[1] = password;
            UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user,
                    params);
            if (ub != null) {
                ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>(
                        MessageBean.class);
                List<MessageBean> msg = run.query("select * from messages where userName =?", messages,
                        userName);
                session.setAttribute("userName", userName);
                session.setAttribute("messageList", msg);
                mv.setViewName("userhome");
            } else {
                mv.addObject("error", "true");
                mv.setViewName("index");

            }

        } catch (Exception ex) {
            System.out.println("Error Message" + ex.getMessage());

        }

    } else if (action.equalsIgnoreCase("logout")) {

        session.invalidate();
        mv.setViewName("index");
    } else if (action.equalsIgnoreCase("signup")) {

        System.out.println("sign up");
        //                
        //                String userName = request.getParameter("user");
        //                String password = request.getParameter("password");
        //                String emailObj = request.getParameter("emailObj");
        //                
        // System.out.println("printing details: " + userName + " " +password + " "+emailObj);
        mv.setViewName("signup");
    } else if (action.equalsIgnoreCase("signupsubmit")) {

        System.out.println("sign up submit");

        String userName = request.getParameter("user");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        System.out.println("printing details: " + userName + " " + password + " " + email);

        if (userName.equals("") || (password.equals("")) || (email.equals(""))) {
            System.out.println("empty values");
            mv.addObject("error", "true");
        }

        else {
            ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class);
            Object[] params = new Object[3];
            params[0] = userName;
            params[1] = password;
            params[2] = email;
            QueryRunner run = new QueryRunner(ds);
            int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)",
                    params);//Logic to insert into table
            System.out.println("inserts value " + inserts);

            if (inserts > 0) {
                mv.addObject("success", "true");
                Email emailObj = new SimpleEmail();
                emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj.
                emailObj.setSmtpPort(465);
                emailObj.setAuthenticator(
                        new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc"));
                emailObj.setSSLOnConnect(true);
                emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing!
                emailObj.setSubject("TestMail");
                emailObj.setMsg("This is spring MVC Contact Application sending you the email");
                emailObj.addTo(email);//Will come from the sign up details
                emailObj.send();
            }

        }

        mv.setViewName("signup");
    }

    return mv;
}