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.alfresco.web.sharepoint.auth.BasicAuthenticationHandler.java

/**
 * Returns <code>true</code> if the user is authenticated and their details are cached in the session
 * //www.j a va 2 s . c o  m
 * @param context
 *            the servlet context
 * @param request
 *            the servlet request
 * @return <code>true</code>, if the user is authenticated
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             On other errors.
 */
public boolean isUserAuthenticated(ServletContext context, HttpServletRequest request)
        throws IOException, ServletException {
    String authHdr = request.getHeader(HEADER_AUTHORIZATION);
    HttpSession session = request.getSession(false);
    SessionUser sessionUser = session == null ? null
            : (SessionUser) session.getAttribute(USER_SESSION_ATTRIBUTE);
    if (sessionUser == null) {
        if (remoteUserMapper != null && (!(remoteUserMapper instanceof ActivateableBean)
                || ((ActivateableBean) remoteUserMapper).isActive())) {
            String userId = remoteUserMapper.getRemoteUser(request);
            if (userId != null) {
                // authenticated by other
                authenticationComponent.setCurrentUser(userId);

                request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(userId,
                        authenticationService.getCurrentTicket(), personService.getPerson(userId)));
                return true;
            }
        }
        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase(BASIC_START)) {
            String basicAuth = new String(Base64.decodeBase64(authHdr.substring(5).getBytes()));
            String username = null;
            String password = null;

            int pos = basicAuth.indexOf(":");
            if (pos != -1) {
                username = basicAuth.substring(0, pos);
                password = basicAuth.substring(pos + 1);
            } else {
                username = basicAuth;
                password = "";
            }

            try {
                if (logger.isDebugEnabled())
                    logger.debug("Authenticating user '" + username + "'");

                authenticationService.authenticate(username, password.toCharArray());

                // Normalize the user ID taking into account case sensitivity settings
                username = authenticationService.getCurrentUserName();

                if (logger.isDebugEnabled())
                    logger.debug("Authenticated user '" + username + "'");

                authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password));

                request.getSession().setAttribute(USER_SESSION_ATTRIBUTE, new User(username,
                        authenticationService.getCurrentTicket(), personService.getPerson(username)));

                return true;
            } catch (AuthenticationException ex) {
                authenticationListener.authenticationFailed(new BasicAuthCredentials(username, password), ex);
            }
        }
    } else {
        try {
            authenticationService.validate(sessionUser.getTicket());
            authenticationListener.userAuthenticated(new TicketCredentials(sessionUser.getTicket()));
            return true;
        } catch (AuthenticationException ex) {
            authenticationListener.authenticationFailed(new TicketCredentials(sessionUser.getTicket()), ex);
            session.invalidate();
        }
    }

    return false;
}

From source file:com.netpace.cms.sso.filter.AlfrescoOpenSSOFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession httpSession = httpRequest.getSession();

    SSOToken token = getOpenSSOClient().createTokenFrom(httpRequest);

    boolean isLoginRequest = isLoginRequest(httpRequest);
    boolean isLogoutRequest = isLogoutRequest(httpRequest);
    boolean isNormalRequest = (token != null && !isLoginRequest && !isLogoutRequest);

    if (isLoginRequest) {
        if (logger.isDebugEnabled()) {
            logger.debug("Is login request.");
        }//from   ww w .  ja v  a2s . c  o m
        httpResponse.sendRedirect(buildURLForRedirect(request));
    }

    if (isLogoutRequest) {
        if (logger.isDebugEnabled()) {
            logger.debug("Is logout request.");
        }
        doLogout(httpSession, token);
        httpResponse.sendRedirect(getVzdnSiteURL());
    }

    if (isNormalRequest) {

        if (logger.isDebugEnabled()) {
            logger.debug("Is Normal Request");
        }

        String principal = getOpenSSOClient().getPrincipal(token);
        String originalPrincipal = principal;

        if (USERS.contains(principal) == true) {
            logger.debug("Special User.... " + principal);
            principal = principal.split("@")[0];
            //            principal += ".";
        }

        if (logger.isDebugEnabled()) {
            logger.debug("principal: " + principal);
        }

        User user = (User) httpSession.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
        if (user == null) {
            String roleId = "";
            String userRoles = (String) httpRequest.getHeader(AlfrescoFacade.PARAM_CMS_ROLE);

            logger.debug("Roles from OpenSSO = " + userRoles);
            if (userRoles != null && userRoles.trim().length() > 0) {

                if (userRoles.contains(AlfrescoFacade.ROLE_SUPER_ADMIN)) {
                    roleId = AlfrescoFacade.ROLE_SUPER_ADMIN;
                } else if (userRoles.contains(AlfrescoFacade.ROLE_CONTENT_MANAGER)) {
                    roleId = AlfrescoFacade.ROLE_CONTENT_MANAGER;
                } else if (userRoles.contains(AlfrescoFacade.ROLE_CONTENT_PUBLISHER)) {
                    roleId = AlfrescoFacade.ROLE_CONTENT_PUBLISHER;
                } else if (userRoles.contains(AlfrescoFacade.ROLE_CONTENT_REVIEWER)) {
                    roleId = AlfrescoFacade.ROLE_CONTENT_REVIEWER;
                } else if (userRoles.contains(AlfrescoFacade.ROLE_CONTENT_CONTRIBUTOR)) {
                    roleId = AlfrescoFacade.ROLE_CONTENT_CONTRIBUTOR;
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("User does not have appropriate role so go back on login page.");
                    }
                    //                  doLogout(httpSession, token);
                    httpSession.invalidate();
                    httpResponse.sendRedirect(getVzdnSiteURL());
                    return;
                }
            }

            if (!getAlfrescoFacade().existUser(principal)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Going to create user in CMS");
                }

                //            String email = getOpenSSOClient().getUserAttribute(OpenSSOClientAdapter.ATTR_EMAIL, token);
                //            String fullName = getOpenSSOClient().getUserAttribute(OpenSSOClientAdapter.ATTR_FULL_NAME, token);
                //            String firstName = getOpenSSOClient().getUserAttribute(OpenSSOClientAdapter.ATTR_LAST_NAME, token);
                String email = originalPrincipal;
                String firstName = httpRequest.getHeader(AlfrescoFacade.OPENSSO_FRIST_NAME);
                String lastName = httpRequest.getHeader(AlfrescoFacade.OPENSSO_LAST_NAME);
                if (logger.isDebugEnabled()) {
                    logger.debug("Principle: " + principal);
                    logger.debug("Email: " + email);
                    logger.debug("FirstName: " + firstName);
                    logger.debug("LastName: " + lastName);
                }
                getAlfrescoFacade().createUser(principal, email, firstName, lastName);

                if (logger.isDebugEnabled()) {
                    logger.debug("User created successfully.");
                }
            }

            getAlfrescoFacade().createOrUpdateRoles(principal, roleId);
        }

        getAlfrescoFacade().setAuthenticatedUser(httpRequest, httpSession, principal);
        chain.doFilter(request, response);
    }

}

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = { "**/login**" }, method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws IOException {
    ModelAndView model = new ModelAndView();
    ResultSet rs = null;// w  w w  .j  a  va  2s  . c o  m
    try {
        boolean flag = false;
        String correct_time = "";
        String userName = "";
        String system_time = "";
        int web_sec = 0;
        int sys_sec = 0;
        correct_time = TimeUtility.generateSysDateMethod();
        system_time = TimeUtility.generateSysDateMethod();
        web_sec = TimeUtility.generateSysSecondsMethod();
        sys_sec = TimeUtility.generateSysSecondsMethod();
        session = request.getSession();
        if (!session.isNew()) {
            LOG.error("New session created");
        } else {
            model = new ModelAndView();
            LoginHandler handler = new LoginHandler();
            model.setViewName("index");
            if (userName != null && !flag) {
                userName = (String) session.getAttribute("USERNAME");
                handler.updateLoggedInFlag(userName, 0);
                session.invalidate();

                return model;
            }
        }

        if (correct_time.equals(system_time) && Math.abs(web_sec - sys_sec) < 1800) {
            model = new ModelAndView();
            String password = "";
            String captchaData = "";
            String captchaString = "";
            if (request.getParameter("submit") != null) {
                userName = request.getParameter("username");
                password = request.getParameter("password");
                captchaData = request.getParameter("captcha");
                captchaString = (String) session.getAttribute("CAPTCHA");

                if (userName.equals("") || password.equals("") || captchaData.equals("")) {
                    flag = true;
                    session.setAttribute("FLAG", flag);
                    model.addObject("emptyFields", "All fields are mandatory");
                    model.setViewName("login");
                }

                else if (!captchaData.equals(captchaString)) {
                    flag = true;
                    session.setAttribute("FLAG", flag);
                    model.addObject("wrongCaptcha", "Please re-enter captcha");
                    model.setViewName("login");
                }

                else {
                    LoginHandler handler = new LoginHandler();
                    rs = handler.requestLoginHandler(userName);
                    if (rs.next()) {
                        String uName = rs.getString("username");
                        String fName = rs.getString("firstname");
                        String pass = rs.getString("usercurrentpassword");
                        String role = rs.getString("usertype");
                        int loggedIn = rs.getInt("isloggedin");
                        String ispwdchange = rs.getString("ispasswordchange");
                        int lock = rs.getInt("islocked");
                        session.setAttribute("USERNAME", userName);
                        if (lock == 0) {
                            boolean correctPass;
                            if (ispwdchange.equals("1")) {
                                correctPass = password.equals(pass);
                            } else {
                                SaltModule saltPass = new SaltModule();
                                correctPass = saltPass.isPasswordValid(password, pass);
                            }
                            if (uName.equals(userName) && correctPass) {
                                if (loggedIn == 0) {

                                    if (ispwdchange.equals("1")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        model.addObject("user", userName);
                                        model.setViewName("resetpassword");
                                        return model;
                                    }
                                    handler.updateLoggedInFlag(userName, 1);
                                    request.getSession().setAttribute("Role", role);
                                    if (role.equals("MANAGER")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Manager", fName);
                                        model.setViewName("managerhome");
                                    } else if (role.equals("EMPLOYEE")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Employee", fName);
                                        model.setViewName("employeehome");
                                    } else if (role.equals("ADMIN")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Admin", fName);
                                        model.setViewName("admin");
                                    } else if (role.equals("MERCHANT")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Merchant", fName);
                                        model.setViewName("merchanthome");
                                    } else if (role.equals("USER")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("User", fName);
                                        model.setViewName("customerhome");
                                    } else if (role.equals("GOVERNMENT")) {
                                        flag = false;
                                        session.setAttribute("FLAG", flag);
                                        session.setAttribute("USERNAME", userName);
                                        request.getSession().setAttribute("Government", fName);
                                        model.setViewName("government");
                                    }
                                } else {
                                    flag = true;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("loggedIn",
                                            "User is already logged in to the other system");
                                    model.setViewName("login");
                                }
                            } else {
                                count++;
                                if (count > 2) {
                                    flag = false;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("user", userName);
                                    handler.updateLockedFlag(userName, 1);
                                    model.addObject("lock",
                                            "Your account has been locked. Please fill in the below details to make a request for unlock account.");
                                    model.setViewName("unlockaccount");
                                } else {
                                    flag = true;
                                    session.setAttribute("FLAG", flag);
                                    model.addObject("wrongCredentials", "Username and Password do not match");
                                    model.setViewName("login");
                                }
                            }
                        } else {
                            flag = false;
                            session.setAttribute("FLAG", flag);
                            model.addObject("user", userName);
                            model.addObject("lock",
                                    "Your account has been locked. Please fill in the below details to make a request for unlock account.");
                            model.setViewName("unlockaccount");
                        }
                    } else {
                        flag = true;
                        session.setAttribute("FLAG", flag);
                        model.addObject("wrongCredentials",
                                "Username does not exist. Please enter correct username");
                        model.setViewName("login");
                    }
                }
            } else if (request.getParameter("imgCaptcha") != null) {
                flag = true;
                session.setAttribute("FLAG", flag);
                CaptchaUtility captcha = new CaptchaUtility();
                captcha.generateCaptcha(request, response);
                model.setViewName("login");
            } else {
                flag = false;
                session.setAttribute("FLAG", flag);
                LoginHandler handler;
                handler = new LoginHandler();
                String userSessionName = (String) session.getAttribute("USERNAME");
                handler.updateLoggedInFlag(userSessionName, 0);
                model.setViewName("login");
            }
        } else {
            flag = false;
            session.setAttribute("FLAG", flag);
            model = new ModelAndView();
            model.addObject("Timetampering", "System time is not updated");
            model.setViewName("login");
        }
    } catch (Exception e) {
        LoginHandler handler;
        handler = new LoginHandler();
        String userSessionName = (String) session.getAttribute("USERNAME");
        handler.updateLoggedInFlag(userSessionName, 0);
        model.setViewName("login");
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            LoginHandler handler;
            handler = new LoginHandler();
            String userSessionName = (String) session.getAttribute("USERNAME");
            handler.updateLoggedInFlag(userSessionName, 0);
            model.setViewName("login");
        }
    }
    return model;
}

From source file:mercury.BaseHandler.java

private String processMenu(HttpServletRequest request, String submitButton) {
    HttpSession session = request.getSession();

    if (submitButton.equals("LOGIN")) {
        String username = request.getParameter("USERNAME");
        String password = request.getParameter("PASSWORD");

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            Dialog.showWarning(request, "ERROR_ACCESS_DENIED");
            return "/jsp/login.jsp";
        }//  w ww.j a  v  a2 s.com

        LoginBO bo = new LoginBO();
        LoginDTO user = bo.login(username, password);

        if (user != null) {
            AuthorizationBO authBO = new AuthorizationBO();
            AuthorizationPoints atps = authBO.getUserAuthPoints(user);
            atps.setAdmin(user.getLoginId() == 1);

            session.setAttribute("LOGGED_USER", user);
            session.setAttribute("LOGGED_USER_ATPS", atps);

            if (atps.isAdmin()) {
                boolean warningPassword = password.toLowerCase().equals("abracadabra");
                session.setAttribute("SYSTEM_WARNING_PASSWORD", warningPassword);
            }

            if (atps.isAllowed(AuthorizationPointTypes.ADMIN_BACKUP)) {
                boolean warningBackup = false;
                AdminBO adminBO = new AdminBO();

                Date lastBackup = adminBO.getLastBackupDate();
                if (lastBackup == null) {
                    String path = request.getSession().getServletContext().getRealPath(".");
                    //String path = session.getServletContext().getRealPath("/WEB-INF/sqldump/");
                    Date now = new Date();

                    boolean b = (new BackupBO()).doBackup(path, String.valueOf(now.getTime()));
                    if (b) {
                        adminBO.insertLastBackupDate(now);
                    }
                } else {
                    int diff = DateUtils.dateDiff(lastBackup, new Date());
                    warningBackup = (diff >= 7);
                }

                session.setAttribute("SYSTEM_WARNING_BACKUP", warningBackup);
            }

            if (atps.isAllowed(AuthorizationPointTypes.ADMIN_REINDEX)) {
                session.setAttribute("SYSTEM_WARNING_REINDEX", new AdminBO().isIndexOutdated());
            }

            Dialog.showNormal(request, "DIALOG_WELCOME_MESSAGE");
            return "/jsp/logged.jsp";
        } else {
            Dialog.showWarning(request, "ERROR_ACCESS_DENIED");
            return "/jsp/login.jsp";
        }

    } else if (submitButton.equals("LOGOUT")) {
        String lang = (String) session.getAttribute("I18N");
        session.invalidate();
        session = request.getSession();
        session.setAttribute("I18N", lang);
        session.removeAttribute("LOGGED_USER");

        Dialog.showNormal(request, "DIALOG_GOODBYE_MESSAGE");
        return "/jsp/login.jsp";

    } else if (submitButton.equals("SEARCH_BIBLIO")) {
        Dialog.showNormal(request, "DIALOG_BIBLIO_SEARCH");
        return "/jsp/search/biblio.jsp";

    } else if (submitButton.equals("SEARCH_AUTH")) {
        Dialog.showNormal(request, "DIALOG_AUTH_SEARCH");
        return "/jsp/search/auth.jsp";

    } else if (submitButton.equals("SEARCH_THESAURUS")) {
        Dialog.showNormal(request, "DIALOG_THESAURUS_SEARCH");
        return "/jsp/search/vocabulary.jsp";

    } else if (submitButton.equals("SEARCH_Z3950")) {
        Z3950BO bo = new Z3950BO();
        session.setAttribute("z3950_server_list", bo.listServers());

        Dialog.showNormal(request, "DIALOG_Z3950_SEARCH");
        return "/jsp/search/distributed.jsp";

    } else if (submitButton.equals("CIRCULATION_REGISTER")) {
        CirculationBO circulationBO = new CirculationBO();
        Collection<UserTypeDTO> listAllUserType = circulationBO.findAllUserType();
        session.setAttribute("LIST_USERS_TYPE", listAllUserType);

        Dialog.showNormal(request, "DIALOG_REGISTER");
        return "/jsp/circulation/user.jsp";

    } else if (submitButton.equals("CIRCULATION_LENDING")) {
        new ReservationBO().deleteExpired();

        Dialog.showNormal(request, "DIALOG_LENDING");
        return "/jsp/circulation/lending.jsp";

    } else if (submitButton.equals("CIRCULATION_RESERVATION")) {
        new ReservationBO().deleteExpired();

        Dialog.showNormal(request, "DIALOG_RESERVATION");
        return "/jsp/circulation/reservation.jsp";

    } else if (submitButton.equals("CIRCULATION_ACCESS")) {
        Dialog.showNormal(request, "DIALOG_ACCESS");
        return "/jsp/circulation/access.jsp";

    } else if (submitButton.equals("CIRCULATION_USER_CARDS")) {
        Dialog.showNormal(request, "DIALOG_USER_CARDS");
        return "/jsp/circulation/user_cards.jsp";

    } else if (submitButton.equals("CATALOGING_BIBLIO")) {
        Dialog.showNormal(request, "DIALOG_BIBLIO_CATALOGING");
        return "/jsp/cataloging/biblio.jsp";

    } else if (submitButton.equals("CATALOGING_AUTH")) {
        Dialog.showNormal(request, "DIALOG_AUTH_CATALOGING");
        return "/jsp/cataloging/auth.jsp";

    } else if (submitButton.equals("CATALOGING_VOCABULARY")) {
        Dialog.showNormal(request, "DIALOG_THESAURUS_CATALOGING");
        return "/jsp/cataloging/vocabulary.jsp";

    } else if (submitButton.equals("CATALOGING_IMPORT")) {
        Dialog.showNormal(request, "DIALOG_IMPORT");
        return "/jsp/cataloging/import.jsp";

    } else if (submitButton.equals("CATALOGING_LABEL")) {
        Dialog.showNormal(request, "DIALOG_LABELS");
        return "/jsp/cataloging/label.jsp";

    } else if (submitButton.equals("CATALOGING_BIBLIO_MOVE")) {
        Dialog.showNormal(request, "DIALOG_BIBLIO_MOVE");
        return "/jsp/cataloging/move.jsp";

    } else if (submitButton.equals("ACQUISITION_SUPPLIER")) {
        Dialog.showNormal(request, "DIALOG_SUPPLIER");
        return "/jsp/acquisition/supplier.jsp";

    } else if (submitButton.equals("ACQUISITION_REQUISITION")) {
        Dialog.showNormal(request, "DIALOG_REQUISITION");
        return "/jsp/acquisition/requisition.jsp";

    } else if (submitButton.equals("ACQUISITION_QUOTATION")) {
        SupplierBO bo = new SupplierBO();
        List<SupplierDTO> suppliers = bo.listAllSuppliers();
        session.setAttribute("supplierList", suppliers);
        RequestBO rbo = new RequestBO();
        List<RequestDTO> requests = rbo.listAllPendingRequests();
        session.setAttribute("requestList", requests);

        Dialog.showNormal(request, "DIALOG_QUOTATION");
        return "/jsp/acquisition/quotation.jsp";

    } else if (submitButton.equals("ACQUISITION_ORDER")) {
        SupplierBO bo = new SupplierBO();
        List<SupplierDTO> suppliers = bo.listAllSuppliers();
        session.setAttribute("supplierList", suppliers);
        QuotationBO qbo = new QuotationBO();
        List<QuotationDTO> quotations = qbo.listAllQuotations();
        session.setAttribute("quotationList", quotations);

        Dialog.showNormal(request, "DIALOG_ORDER");
        return "/jsp/acquisition/order.jsp";

    } else if (submitButton.equals("ADMINISTRATION_MAINTENANCE")) {
        session.setAttribute("MOVE_RECORDS", "ESCONDER");
        session.setAttribute("BUTTON_MOVE_RECORDS", "EXIBIR");
        session.setAttribute("TOTAL_WORK_REC", new AdminBO().totalRecords("WORK"));
        session.setAttribute("TOTAL_MAIN_REC", new AdminBO().totalRecords("MAIN"));
        session.removeAttribute("LIST_RECORDS");

        String defaultFormat = I18nUtils.getText(session, "biblivre3", "DEFAULT_DATETIME_FORMAT");
        SimpleDateFormat formatter = new SimpleDateFormat(defaultFormat);
        AdminBO bo = new AdminBO();
        List<Date> dates = bo.getLastFiveBackups();
        List<String[]> formattedDates = new ArrayList<String[]>();
        for (Date date : dates) {
            formattedDates.add(new String[] { formatter.format(date), String.valueOf(date.getTime()) });
        }
        session.setAttribute("SYSTEM_LAST_FIVE_BACKUPS", formattedDates);

        Dialog.showNormal(request, "DIALOG_MAINTENANCE");
        return "/jsp/administration/maintenance.jsp";

    } else if (submitButton.equals("ADMINISTRATION_PASSWORD")) {
        Dialog.showNormal(request, "DIALOG_PASSWORD");
        return "/jsp/administration/password.jsp";

    } else if (submitButton.equals("ADMINISTRATION_REPORTS")) {
        Dialog.showNormal(request, "DIALOG_REPORTS");
        return "/jsp/administration/reports.jsp";

    } else if (submitButton.equals("ADMINISTRATION_PERMISSIONS")) {
        Dialog.showNormal(request, "DIALOG_PERMISSIONS");
        return "/jsp/administration/permissions.jsp";

    } else if (submitButton.equals("ADMINISTRATION_USER_TYPES")) {
        Dialog.showNormal(request, "DIALOG_USER_TYPES_ADMIN");
        return "/jsp/administration/usertypes.jsp";

    } else if (submitButton.equals("ADMINISTRATION_ACCESSCARDS")) {
        Dialog.showNormal(request, "DIALOG_ACCESSCARDS");
        return "/jsp/administration/accesscards.jsp";

    } else if (submitButton.equals("ADMINISTRATION_Z3950SERVERS")) {
        final Z3950BO bo = new Z3950BO();
        session.setAttribute("serverStatus", bo.getServerStatus());

        Dialog.showNormal(request, "DIALOG_Z3950SERVER");
        return "/jsp/administration/z3950.jsp";

    } else if (submitButton.equals("ADMINISTRATION_CONFIGURATION")) {
        Dialog.showNormal(request, "DIALOG_CONFIGURATION");
        return "/jsp/administration/configuration.jsp";

    } else if (submitButton.equals("HELP_ABOUT")) {
        Dialog.showNormal(request, "DIALOG_ABOUT");
        return "/jsp/help/about.jsp";
    }

    Dialog.showNormal(request, "DIALOG_VOID");
    return null;
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

private SAMLAuthenticationToken renewSecurityToken(HttpSession session, SAMLAuthenticationToken savedToken)
        throws ServletException, WSSecurityException {
    if (session != null) {
        SecurityAssertion savedAssertion = new SecurityAssertionImpl(
                ((SecurityToken) savedToken.getCredentials()));

        if (savedAssertion.getIssuer() != null && !savedAssertion.getIssuer().equals(SystemBaseUrl.getHost())) {
            return null;
        }//from  ww  w .j a  v  a  2s  . c  o  m

        if (savedAssertion.getNotOnOrAfter() == null) {
            return null;
        }

        long afterMil = savedAssertion.getNotOnOrAfter().getTime();
        long timeoutMillis = (afterMil - System.currentTimeMillis());

        if (timeoutMillis <= 0) {
            String msg = "SAML assertion has expired.";
            LOGGER.info(msg);
            throw new InvalidSAMLReceivedException(msg);
        }

        if (timeoutMillis <= 60000) { // within 60 seconds
            try {
                LOGGER.debug("Attempting to refresh user's SAML assertion.");

                Subject subject = securityManager.getSubject(savedToken);
                LOGGER.debug("Refresh of user assertion successful");
                for (Object principal : subject.getPrincipals()) {
                    if (principal instanceof SecurityAssertion) {
                        SecurityToken token = ((SecurityAssertion) principal).getSecurityToken();
                        SAMLAuthenticationToken samlAuthenticationToken = new SAMLAuthenticationToken(
                                (java.security.Principal) savedToken.getPrincipal(), token,
                                savedToken.getRealm());
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Setting session token - class: {}  classloader: {}",
                                    token.getClass().getName(), token.getClass().getClassLoader());
                        }
                        ((SecurityTokenHolder) session.getAttribute(SecurityConstants.SAML_ASSERTION))
                                .addSecurityToken(savedToken.getRealm(), token);

                        LOGGER.debug("Saved new user assertion to session.");

                        return samlAuthenticationToken;
                    }
                }

            } catch (SecurityServiceException e) {
                LOGGER.warn("Unable to refresh user's SAML assertion. User will log out prematurely.", e);
                session.invalidate();
            } catch (Exception e) {
                LOGGER.warn("Unhandled exception occurred.", e);
                session.invalidate();
            }
        }
    }
    return null;
}

From source file:org.josso.liferay5.agent.LiferaySSOAgentFilter.java

@Override
protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    // URI pattern matching is implemented programmatically in case this filter is bound to the root web context
    // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs.
    if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI)
            && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI)
            && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI)
            && !hreq.getRequestURI().contains(LIFERAY_USER_URI)
            && !hreq.getRequestURI().contains(LIFERAY_WEB_URI)
            && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) {
        filterChain.doFilter(hreq, hres);
        return;//from  ww w .ja  va  2 s .  co  m
    }

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        long companyId = PortalUtil.getCompanyId(request);

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the Liferay application required its login form [/c/portal/login]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'");
            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check if the Liferay application required its logout form [/c/portal/logout]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId)
                && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        LiferayLocalSession localSession = new LiferayLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(
                    cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession,
                    null, hreq, hres);

            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            LiferaySSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not supported : session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:org.alfresco.repo.webdav.auth.SSOFallbackBasicAuthenticationDriver.java

@Override
public boolean authenticateRequest(ServletContext context, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    String authHdr = request.getHeader("Authorization");
    HttpSession session = request.getSession(false);
    SessionUser user = session == null ? null : (SessionUser) session.getAttribute(userAttributeName);
    if (user == null) {
        if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("Basic")) {
            String basicAuth = new String(Base64.decodeBase64(authHdr.substring(5).getBytes()));
            String username = null;
            String password = null;

            int pos = basicAuth.indexOf(":");
            if (pos != -1) {
                username = basicAuth.substring(0, pos);
                password = basicAuth.substring(pos + 1);
            } else {
                username = basicAuth;//w w  w . ja  v a 2 s  .  c  o  m
                password = "";
            }

            try {
                if (logger.isDebugEnabled())
                    logger.debug("Authenticating user '" + username + "'");

                Authorization auth = new Authorization(username, password);
                if (auth.isTicket()) {
                    authenticationService.validate(auth.getTicket());
                } else {
                    authenticationService.authenticate(username, password.toCharArray());
                }

                final RetryingTransactionCallback<SessionUser> callback = new RetryingTransactionCallback<SessionUser>() {
                    @Override
                    public SessionUser execute() throws Throwable {
                        NodeRef personNodeRef = personService
                                .getPerson(authenticationService.getCurrentUserName());
                        String username = (String) nodeService.getProperty(personNodeRef,
                                ContentModel.PROP_USERNAME);
                        NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personNodeRef,
                                ContentModel.PROP_HOMEFOLDER);

                        return new WebDAVUser(username, authenticationService.getCurrentTicket(), homeSpaceRef);
                    }
                };

                user = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<SessionUser>() {
                    public SessionUser doWork() throws Exception {
                        return transactionService.getRetryingTransactionHelper().doInTransaction(callback,
                                true);
                    }
                }, AuthenticationUtil.SYSTEM_USER_NAME);

                if (logger.isDebugEnabled())
                    logger.debug("Authenticated user '" + username + "'");

                request.getSession().setAttribute(userAttributeName, user);
                return true;
            } catch (AuthenticationException ex) {
                // Do nothing, user object will be null
            }
        }
    } else {
        try {
            authenticationService.validate(user.getTicket());
            return true;
        } catch (AuthenticationException ex) {
            session.invalidate();
        }
    }

    return false;
}

From source file:org.josso.liferay6.agent.LiferaySSOAgentFilter.java

@Override
protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    // URI pattern matching is implemented programmatically in case this filter is bound to the root web context
    // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs.
    if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI)
            && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI)
            && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI)
            && !hreq.getRequestURI().contains(LIFERAY_USER_URI)
            && !hreq.getRequestURI().contains(LIFERAY_WEB_URI)
            && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) {
        filterChain.doFilter(hreq, hres);
        return;/*from  w  w w.j  a v  a 2s.  c  om*/
    }

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        long companyId = PortalUtil.getCompanyId(request);

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            if (log.isDebugEnabled())
                log.debug("Context is not a josso partner app : " + hreq.getContextPath());

            return;
        }

        String nodeId = hreq.getParameter("josso_node");
        if (nodeId != null) {
            if (log.isDebugEnabled())
                log.debug("Storing JOSSO Node id : " + nodeId);
            _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId);
        } else {
            nodeId = _agent.getAttribute(hreq, "JOSSO_NODE");
            if (log.isDebugEnabled())
                log.debug("Found JOSSO Node id : " + nodeId);
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the Liferay application required its login form [/c/portal/login]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'");
            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check if the Liferay application required its logout form [/c/portal/logout]
        // ------------------------------------------------------------------
        if (JossoLiferayProps.isEnabled(companyId)
                && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) {
            if (log.isDebugEnabled())
                log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;
        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        LiferayLocalSession localSession = new LiferayLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled()) {
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(
                    cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession,
                    null, hreq, hres);

            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            LiferaySSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(),
                SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq,
                hres);
        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // Not supported : session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can co back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                //set non cache headers
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:cz.muni.fi.webmias.ProcessServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w w w .ja  va 2 s. co m
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    HttpSession session = request.getSession(true);

    int page = Integer.parseInt(request.getParameter("n"));
    String query = request.getParameter(QUERY_PARAMETER);
    boolean debug = request.getParameter("debug") != null;
    boolean extractSubformulae = request.getParameter("extractSubformulae") != null;
    boolean reduceWeighting = request.getParameter("reduceWeighting") != null;
    String indexNo = request.getParameter("index");
    int indexNumber = 0;
    if (indexNo != null) {
        indexNumber = Integer.parseInt(indexNo);
    }
    String qc = request.getParameter("qc");
    String variant = request.getParameter("variant");
    MathMLType mmlType = getType(variant);

    IndexDef currentIndexDef = Indexes.getIndexDef(indexNumber);
    IndexSearcher searcher = currentIndexDef.getIndexSearcher();
    request.setAttribute("index", indexNumber);
    request.setAttribute(QUERY_PARAMETER, query);
    request.setAttribute("debug", debug);
    request.setAttribute("extractSubformulae", extractSubformulae);
    request.setAttribute("reduceWeighting", reduceWeighting);
    request.setAttribute("qc", qc);
    request.setAttribute("variant", variant);
    request.setAttribute("forbidden", forbidden);

    request.setAttribute("indexes", Indexes.getIndexNames());

    if (query != null && !query.isEmpty()) {
        logQuery(request, query);
        String[] sep = MathSeparator.separate(query, "");
        query = sep[1];
        if (sep[0] != null && !sep[0].isEmpty()) {
            query += " " + TeXConverter.convertTexLatexML(sep[0]);
        }

        s = new Searching(searcher, currentIndexDef.getStorage());
        page = page == 0 ? page : page - 1;
        SearchResult searchResult = s.search(query, false, page * resPerPage, resPerPage, debug, mmlType,
                extractSubformulae, reduceWeighting);
        int totalResults = searchResult.getTotalResults();
        request.setAttribute("processedQuery", searchResult.getProcessedQuery());
        request.setAttribute("luceneQuery", searchResult.getLuceneQuery());
        request.setAttribute("total", searchResult.getTotalResults());
        request.setAttribute("coreTime", searchResult.getCoreSearchTime());
        request.setAttribute("totalTime", searchResult.getTotalSearchTime());
        request.setAttribute("resPerPage", resPerPage);
        totalResults = Math.min(totalResults, Settings.getMaxResults());
        if (totalResults > 0 && page >= 0) {
            List<Integer> pages = new ArrayList<>();
            for (int i = 0; i < (totalResults / resPerPage) + 1; i++) {
                pages.add(i + 1);
            }
            request.setAttribute("pages", pages);
            request.setAttribute("n", page);
            for (Result r : searchResult.getResults()) {
                r.setInfo(r.getInfo().replaceAll("\n", "<br/>"));
            }
            request.setAttribute("results", searchResult.getResults());
        } else if (page == -1) {
            session.invalidate();
        } else {
            request.setAttribute("nores", "No results.");
        }
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Sessions01() {
    final AtomicBoolean valueBound = new AtomicBoolean(false);
    final AtomicBoolean valueUnbound = new AtomicBoolean(false);
    final HttpSessionBindingListener bindingListener = new HttpSessionBindingListener() {

        @Override//from w  w w.j av a2s.co  m
        public void valueUnbound(HttpSessionBindingEvent event) {
            valueUnbound.set(true);
        }

        @Override
        public void valueBound(HttpSessionBindingEvent event) {
            valueBound.set(true);
        }
    };
    final AtomicBoolean sessionCreated = new AtomicBoolean(false);
    final AtomicBoolean sessionDestroyed = new AtomicBoolean(false);
    HttpSessionListener sessionListener = new HttpSessionListener() {

        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            sessionDestroyed.set(true);
        }

        @Override
        public void sessionCreated(HttpSessionEvent se) {
            sessionCreated.set(true);
        }
    };
    HttpServlet sessionServlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            HttpSession session = request.getSession();
            if (session.getAttribute("test.attribute") == null) {
                session.setAttribute("test.attribute", bindingListener);
                response.getWriter().print("created");
            } else {
                session.invalidate();
                response.getWriter().print("invalidated");
            }
        }

    };
    ServiceRegistration<Servlet> servletReg = null;
    ServiceRegistration<HttpSessionListener> sessionListenerReg = null;
    Dictionary<String, Object> servletProps = new Hashtable<String, Object>();
    servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/sessions");
    String actual = null;
    CookieHandler previous = CookieHandler.getDefault();
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    try {
        servletReg = getBundleContext().registerService(Servlet.class, sessionServlet, servletProps);
        Dictionary<String, String> listenerProps = new Hashtable<String, String>();
        listenerProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, "true");
        sessionListenerReg = getBundleContext().registerService(HttpSessionListener.class, sessionListener,
                listenerProps);

        sessionCreated.set(false);
        valueBound.set(false);
        sessionDestroyed.set(false);
        valueUnbound.set(false);
        // first call will create the session
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "created", actual);
        assertTrue("No sessionCreated called", sessionCreated.get());
        assertTrue("No valueBound called", valueBound.get());
        assertFalse("sessionDestroyed was called", sessionDestroyed.get());
        assertFalse("valueUnbound was called", valueUnbound.get());

        sessionCreated.set(false);
        valueBound.set(false);
        sessionDestroyed.set(false);
        valueUnbound.set(false);
        // second call will invalidate the session
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "invalidated", actual);
        assertFalse("sessionCreated was called", sessionCreated.get());
        assertFalse("valueBound was called", valueBound.get());
        assertTrue("No sessionDestroyed called", sessionDestroyed.get());
        assertTrue("No valueUnbound called", valueUnbound.get());

        sessionCreated.set(false);
        sessionDestroyed.set(false);
        valueBound.set(false);
        valueUnbound.set(false);
        // calling again should create the session again
        actual = requestAdvisor.request("sessions");
        assertEquals("Wrong result", "created", actual);
        assertTrue("No sessionCreated called", sessionCreated.get());
        assertTrue("No valueBound called", valueBound.get());
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    } finally {
        if (servletReg != null) {
            servletReg.unregister();
        }
        if (sessionListenerReg != null) {
            sessionListenerReg.unregister();
        }
        CookieHandler.setDefault(previous);
    }
}