Example usage for javax.servlet.http HttpSession removeAttribute

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

Introduction

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

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the object bound with the specified name from this session.

Usage

From source file:dk.itst.oiosaml.sp.service.LoginHandler.java

public void handleGet(RequestContext context) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("Go to login...");

    IdpMetadata idpMetadata = context.getIdpMetadata();
    Configuration conf = context.getConfiguration();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    Metadata metadata;//  w  w  w .j  a v a  2  s  .co  m
    if (idpMetadata.enableDiscovery()) {
        log.debug("Discovery profile is active");
        String samlIdp = request.getParameter(Constants.DISCOVERY_ATTRIBUTE);
        if (samlIdp == null) {
            String discoveryLocation = conf.getString(Constants.DISCOVERY_LOCATION);
            log.debug("No _saml_idp discovery value found, redirecting to discovery service at "
                    + discoveryLocation);
            String url = request.getRequestURL().toString();
            if (request.getQueryString() != null) {
                url += "?" + request.getQueryString();
            }
            Audit.log(Operation.DISCOVER, true, "", discoveryLocation);
            HTTPUtils.sendMetaRedirect(response, discoveryLocation, "r=" + URLEncoder.encode(url, "UTF-8"),
                    true);
            return;
        } else if ("".equals(samlIdp)) {
            String defaultIdP = conf.getString(Constants.PROP_DISCOVERY_DEFAULT_IDP, null);
            if (defaultIdP != null) {
                log.debug("No IdP discovered, using default IdP from configuration: " + defaultIdP);
                metadata = idpMetadata.getMetadata(defaultIdP);
            } else {
                if (conf.getBoolean(Constants.PROP_DISCOVERY_PROMPT, false)) {
                    String url = request.getRequestURL().toString();
                    url += "?RelayState=" + request.getParameter(Constants.SAML_RELAYSTATE);
                    promptIdp(context, url);

                    return;
                } else {
                    log.debug("No IdP discovered, using first from metadata");
                    metadata = idpMetadata.getFirstMetadata();
                }
            }
        } else {
            String[] entityIds = SAMLUtil.decodeDiscoveryValue(samlIdp);
            Audit.log(Operation.DISCOVER, false, "", Arrays.asList(entityIds).toString());
            metadata = idpMetadata.findSupportedEntity(entityIds);
            log.debug("Discovered idp " + metadata.getEntityID());
        }
    } else {
        metadata = idpMetadata.getFirstMetadata();
    }
    Audit.log(Operation.DISCOVER, metadata.getEntityID());

    Endpoint signonLocation = metadata
            .findLoginEndpoint(conf.getStringArray(Constants.PROP_SUPPORTED_BINDINGS));
    if (signonLocation == null) {
        String msg = "Could not find a valid IdP signon location. Supported bindings: "
                + conf.getString(Constants.PROP_SUPPORTED_BINDINGS) + ", available: "
                + metadata.getSingleSignonServices();
        log.error(msg);
        throw new RuntimeException(msg);
    }
    log.debug("Signing on at " + signonLocation);

    BindingHandler bindingHandler = context.getBindingHandlerFactory()
            .getBindingHandler(signonLocation.getBinding());
    log.info("Using idp " + metadata.getEntityID() + " at " + signonLocation.getLocation() + " with binding "
            + signonLocation.getBinding());

    HttpSession session = context.getSession();
    UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION);
    session.removeAttribute(Constants.SESSION_USER_ASSERTION);
    UserAssertionHolder.set(null);

    String relayState = context.getRequest().getParameter(Constants.SAML_RELAYSTATE);
    OIOAuthnRequest authnRequest = OIOAuthnRequest.buildAuthnRequest(signonLocation.getLocation(),
            context.getSpMetadata().getEntityID(),
            context.getSpMetadata().getDefaultAssertionConsumerService().getBinding(),
            context.getSessionHandler(), relayState,
            context.getSpMetadata().getDefaultAssertionConsumerService().getLocation());
    authnRequest.setNameIDPolicy(conf.getString(Constants.PROP_NAMEID_POLICY, null),
            conf.getBoolean(Constants.PROP_NAMEID_POLICY_ALLOW_CREATE, false));
    authnRequest.setForceAuthn(isForceAuthnEnabled(request, conf));

    if (ua == null) {
        authnRequest.setPasive(conf.getBoolean(Constants.PROP_PASSIVE, false));
    }
    Audit.log(Operation.AUTHNREQUEST_SEND, true, authnRequest.getID(), authnRequest.toXML());

    context.getSessionHandler().registerRequest(authnRequest.getID(), metadata.getEntityID());
    bindingHandler.handle(request, response, context.getCredential(), authnRequest);
}

From source file:com.pearson.pdn.demos.chainoflearning.CalendarServlet.java

@Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
    // account for a forced re-register from doGet
    if (req.getAttribute("email") != null) {
        return (String) req.getAttribute("email");
    }/*from w w  w .  j  a v a2s. c o m*/

    // return user ID
    String email = req.getParameter("e");
    String verifyCode = req.getParameter("v");

    if (email != null && verifyCode != null) {
        // TODO - do this better. auth will not be in the session
        HttpSession session = req.getSession();
        if (session != null) {
            String auth = (String) session.getAttribute("auth");

            String authMatch = Base64.encodeBase64String((email + ":" + verifyCode).getBytes());
            if (auth.equals(authMatch)) {
                session.removeAttribute("auth");
                session.setAttribute("email", email);
                return email;
            }
        }
    }

    return null;
}

From source file:com.epam.training.storefront.controllers.pages.AbstractLoginPageController.java

protected String getDefaultLoginPage(final boolean loginError, final HttpSession session, final Model model)
        throws CMSItemNotFoundException {
    final LoginForm loginForm = new LoginForm();
    model.addAttribute(loginForm);// w  ww. j av  a 2 s .  c  om
    model.addAttribute(new RegisterForm());

    final String username = (String) session.getAttribute(SPRING_SECURITY_LAST_USERNAME);
    if (username != null) {
        session.removeAttribute(SPRING_SECURITY_LAST_USERNAME);
    }

    loginForm.setJ_username(username);
    storeCmsPageInModel(model, getCmsPage());
    setUpMetaDataForContentPage(model, (ContentPageModel) getCmsPage());
    model.addAttribute("metaRobots", "index,no-follow");

    final Breadcrumb loginBreadcrumbEntry = new Breadcrumb("#",
            getMessageSource().getMessage("header.link.login", null, getI18nService().getCurrentLocale()),
            null);
    model.addAttribute("breadcrumbs", Collections.singletonList(loginBreadcrumbEntry));

    if (loginError) {
        GlobalMessages.addErrorMessage(model, "login.error.account.not.found.title");
    }

    return getView();
}

From source file:com.salesmanager.core.module.impl.application.logon.CustomerJAASLogonImpl.java

public void logout(HttpServletRequest request) throws ServiceException {
    LoginContext context = null;/*from www. j  av a  2  s  .  c o m*/
    SalesManagerJAASConfiguration jaasc = new SalesManagerJAASConfiguration(
            "com.salesmanager.core.module.impl.application.logon.JAASSecurityCustomerLoginModule");

    try {
        HttpSession session = request.getSession();
        context = (LoginContext) session.getAttribute("LOGINCONTEXT");
        if (context != null) {
            context.logout();
        }

        session.removeAttribute("PRINCIPAL");
        session.removeAttribute("LOGINCONTEXT");

    } catch (Exception e) {
        throw new RuntimeException("Unable to Create Logout Context, configuration file may be missing", e);
    }

}

From source file:com.adito.core.CoreUtil.java

/**
 * Reset the main navigation menu so it gets rebuilt upon the next request
 * /*from  w w  w  .j  av a  2 s.  co  m*/
 * @param session
 * 
 */
public static void resetMainNavigation(HttpSession session) {
    session.removeAttribute(Constants.MENU_TREE);
    session.removeAttribute(Constants.NAV_BAR);
}

From source file:com.epam.cme.storefront.controllers.pages.AbstractLoginPageController.java

protected String getDefaultLoginPage(final AuthenticationException loginException, final HttpSession session,
        final Model model) throws CMSItemNotFoundException {
    final LoginForm loginForm = new LoginForm();
    model.addAttribute(loginForm);//from   w  ww . j  ava  2 s. c o m
    model.addAttribute(new RegisterForm());

    final String username = (String) session.getAttribute(SPRING_SECURITY_LAST_USERNAME);
    if (username != null) {
        session.removeAttribute(SPRING_SECURITY_LAST_USERNAME);
    }

    loginForm.setJ_username(username);
    storeCmsPageInModel(model, getCmsPage());
    setUpMetaDataForContentPage(model, (ContentPageModel) getCmsPage());
    model.addAttribute("metaRobots", "index,no-follow");

    final Breadcrumb loginBreadcrumbEntry = new Breadcrumb("#",
            getMessageSource().getMessage("header.link.login", null, getI18nService().getCurrentLocale()),
            null);
    model.addAttribute("breadcrumbs", Collections.singletonList(loginBreadcrumbEntry));

    if (loginException instanceof BadCredentialsException) {
        GlobalMessages.addErrorMessage(model, "login.error.account.not.found.title");
    } else if (loginException instanceof LockedException) {
        GlobalMessages.addErrorMessage(model, "login.error.user.blocked.title");
    }
    return getView();
}

From source file:br.bireme.web.AuthenticationServlet.java

/**
 * Processes requests for both HTTP//  ww w. ja  v  a2  s .  c o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding(CODEC);

    final String username = request.getParameter("email");
    final String password = request.getParameter("password");
    final String lang = request.getParameter("lang");
    final ServletContext context = getServletContext();
    final HttpSession session = request.getSession();
    final ResourceBundle messages = Tools.getMessages(lang);

    boolean isAccountsWorking = true;
    RequestDispatcher dispatcher;

    session.removeAttribute("collCenter");
    session.removeAttribute("user");

    if (isAccountsWorking) {
        if ((username == null) || (username.isEmpty()) || (password == null) || (password.isEmpty())) {
            response.sendRedirect(
                    "index.jsp?lang=" + lang + "&errMsg=" + messages.getString("login_is_required"));
            return;
        }

        try {
            final Authentication auth = new Authentication(context.getInitParameter("accounts_host"));
            final JSONObject user = auth.getUser(username, password);
            Set<String> centerIds = auth.getCenterIds(user);

            //if (auth.isAuthenticated(user) && (centerIds != null)) {
            if (auth.isAuthenticated(user)) {
                if (centerIds == null) {
                    centerIds = new HashSet<String>();
                }
                centerIds.add(auth.getColCenter(user)); // cc may not belong to a net (it not appear in centerIds)

                session.setAttribute("user", username); // Login user.
                session.setAttribute("centerIds", centerIds);
                dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
            } else {
                session.removeAttribute("user");
                session.removeAttribute("centerIds");
                dispatcher = context.getRequestDispatcher(
                        "/index.jsp?lang=" + lang + "&errMsg=" + messages.getString("authentication_failed"));
            }
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            dispatcher = context.getRequestDispatcher("/index.jsp?lang=" + lang + "&errMsg="
                    + messages.getString("exception_found") + "<br/><br/>" + ex.getMessage());
            dispatcher.forward(request, response);
        }
    } else {
        final Set<String> ccs = new HashSet<String>();
        ccs.add("PE1.1");
        ccs.add("BR1.1");
        dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
        session.setAttribute("user", username); // Login user.
        session.setAttribute("centerIds", ccs);
        dispatcher.forward(request, response);
    }
}

From source file:info.magnolia.cms.servlets.RequestInterceptor.java

/**
 * Request and Response here is same as receivced by the original page so it includes all post/get data. Sub action
 * could be called from here once this action finishes, it will continue loading the requested page.
 *///from   ww w  . ja  va  2 s . co  m
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String action = request.getParameter(EntryServlet.INTERCEPT);
    String repository = request.getParameter(PARAM_REPOSITORY);
    if (repository == null) {
        repository = ContentRepository.WEBSITE;
    }
    HierarchyManager hm = MgnlContext.getHierarchyManager(repository);
    synchronized (ExclusiveWrite.getInstance()) {
        if (action.equals(ACTION_PREVIEW)) {
            // preview mode (button in main bar)
            String preview = request.getParameter(Resource.MGNL_PREVIEW_ATTRIBUTE);
            if (preview != null) {

                // @todo IMPORTANT remove use of http session
                HttpSession httpsession = request.getSession(true);
                if (BooleanUtils.toBoolean(preview)) {
                    httpsession.setAttribute(Resource.MGNL_PREVIEW_ATTRIBUTE, Boolean.TRUE);
                } else {
                    httpsession.removeAttribute(Resource.MGNL_PREVIEW_ATTRIBUTE);
                }
            }
        } else if (action.equals(ACTION_NODE_DELETE)) {
            // delete paragraph
            try {
                String path = request.getParameter(PARAM_PATH);
                // deactivate
                updatePageMetaData(request, hm);
                hm.delete(path);
                hm.save();
            } catch (RepositoryException e) {
                log.error("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
            }
        } else if (action.equals(ACTION_NODE_SORT)) {
            // sort paragrpahs
            try {
                String pathSelected = request.getParameter(PARAM_PATH_SELECTED);
                String pathSortAbove = request.getParameter(PARAM_PATH_SORT_ABOVE);
                String pathParent = StringUtils.substringBeforeLast(pathSelected, "/"); //$NON-NLS-1$
                String srcName = StringUtils.substringAfterLast(pathSelected, "/");
                String destName = StringUtils.substringAfterLast(pathSortAbove, "/");
                if (StringUtils.equalsIgnoreCase(destName, "mgnlNew")) {
                    destName = null;
                }
                hm.getContent(pathParent).orderBefore(srcName, destName);
                hm.save();
            } catch (RepositoryException e) {
                if (log.isDebugEnabled())
                    log.debug("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
            }
        }
    }
}

From source file:org.workspace7.moviestore.controller.ShoppingCartController.java

/**
 *
 *///from  www .  jav  a  2s.c om
@PostMapping("/cart/pay")
public ModelAndView checkout(ModelAndView modelAndView, HttpSession session,
        RedirectAttributes redirectAttributes) {
    MovieCart movieCart = (MovieCart) session.getAttribute(SESSION_ATTR_MOVIE_CART);
    if (movieCart != null) {
        log.info("Your request {} will be processed, thank your for shopping", movieCart);
        session.removeAttribute(SESSION_ATTR_MOVIE_CART);
    }
    modelAndView.setViewName("redirect:/");
    redirectAttributes.addFlashAttribute("orderStatus", 1);
    return modelAndView;
}

From source file:com.jmu.service.Patchca.PatchcaService.java

/**
 * ???? ?????/* w w  w  . j  av a2  s  .c  om*/
 * @param session
 * @param value
 * @return
 */
public Boolean validatePatchca(HttpSession session, String value) {
    boolean b = false;
    String patchca = (String) session.getAttribute("patchca");
    if (StringUtils.isNotEmpty(patchca)) {
        b = value.equalsIgnoreCase(patchca);
    }
    session.removeAttribute("patchca");
    return b;
}