Java Code Examples for javax.servlet.http.HttpSession#invalidate()

The following examples show how to use javax.servlet.http.HttpSession#invalidate() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public boolean validateSession(HttpServletRequest request) throws ServiceLayerException {
    HttpSession httpSession = request.getSession();
    String authToken = getCurrentToken();
    String userName = getCurrentUser();

    if (userName != null) {

        UserDetails userDetails = this.userDetailsManager.loadUserByUsername(userName);

        if (SessionTokenUtils.validateToken(authToken, userDetails.getUsername())) {
            return true;
        }

    }

    httpSession.removeAttribute(HTTP_SESSION_ATTRIBUTE_AUTHENTICATION);
    httpSession.invalidate();
    return false;
}
 
Example 2
Source Project: auth-server   File: LogoutController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * One click logout. Invalidates the session.
 * </p>
 */
@PostMapping("/logout")
public String logout(HttpServletRequest request) {
  log.debug("Direct logout");

  // Current user was validated -> Clear securityContext
  SecurityContextHolder.getContext().setAuthentication(null);
  SecurityContextHolder.clearContext();

  // Invalidate session
  final HttpSession session = request.getSession(false);
  if (session != null) {
    session.invalidate();
  }

  return "redirect:/login?logout";
}
 
Example 3
@PostMapping("/logout")
public ModelAndView clear(ModelAndView modelAndView, HttpServletRequest request) {
    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");
    List<Movie> movies = movieDBHelper.getAll();

    List<MovieCartItem> movieList = movies.stream()
        .map((Movie movie) -> MovieCartItem.builder()
            .movie(movie)
            .quantity(0)
            .total(0)
            .build())
        .collect(Collectors.toList());

    HttpSession session = request.getSession(false);

    if (session != null) {
        log.info("Invalidating session:{}", session.getId());
        session.invalidate();
    }

    log.info("New Session");
    modelAndView.addObject("movies", movieList);
    modelAndView.setViewName("home");
    modelAndView.addObject("hostname", hostname);
    return modelAndView;
}
 
Example 4
@POST
@Path("/" + Constants.RP_LOGOUT_PATH)
@Produces({MediaType.APPLICATION_JSON})
public Response logout() {
    try {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return generateResponse(Response.Status.OK, "");
        }
        session.invalidate();
        return generateResponse(Response.Status.OK, "");
    } catch (Exception ex) {
        ex.printStackTrace();
        WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "isLoggedIn", "WEBAUTHN-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1000"));
    }
}
 
Example 5
/**
    * Unregisteres the session for the given user.
    */
   public static void removeSessionByLogin(String login, boolean invalidate) {
HttpSession session = SessionManager.loginMapping.get(login);
if (session == null) {
    return;
}
SessionManager.loginMapping.remove(login);

if (invalidate) {
    try {
	session.invalidate();
    } catch (Exception e) {
	log.warn("SessionMananger invalidation exception", e);
	// if it was already invalidated, do nothing
    }
}
   }
 
Example 6
/**
 * Validates the provided CSRF token value from
 * the request with the session CSRF token value.
 *
 * @param request
 * @param response
 * @return true if the token is valid
 * @throws IOException
 */
protected boolean doTokenValidation(HttpServletRequest request, HttpServletResponse response) throws IOException {

  HttpSession session = request.getSession();
  String tokenHeader = getCSRFTokenHeader(request);
  String tokenSession = (String) getCSRFTokenSession(session);
  boolean isValid = true;

  if (isBlank(tokenHeader)) {
    session.invalidate();
    response.setHeader(CsrfConstants.CSRF_TOKEN_HEADER_NAME, CsrfConstants.CSRF_TOKEN_HEADER_REQUIRED);
    response.sendError(getDenyStatus(), "CSRFPreventionFilter: Token provided via HTTP Header is absent/empty.");
    isValid = false;
  } else if (isBlank(tokenSession) || !tokenSession.equals(tokenHeader)) {
    session.invalidate();
    response.sendError(getDenyStatus(), "CSRFPreventionFilter: Invalid HTTP Header Token.");
    isValid = false;
  }

  return isValid;
}
 
Example 7
/**
 * 退出
 * @param session
 * @return
 */
@RequestMapping("logout")
@ResponseBody
public ReturnResult logout(HttpSession session) {
	session.invalidate();
	return returnResult.setStatus(ReturnCodeType.SUCCESS);
}
 
Example 8
Source Project: ssm-demo   File: UserController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 退出系统
 *
 * @return
 * @throws Exception
 */
@RequestMapping("/logout")
public String logout(HttpSession session) throws Exception {
    session.invalidate();
    log.info("request: user/logout");
    return "redirect:/login.jsp";
}
 
Example 9
Source Project: olingo-odata4   File: TomcatTestServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void invalidateAllSession() {
  synchronized (ALL_SESSIONS) {
    LOG.info("Invalidated sessions...");
    for (Map.Entry<ServletContext, Set<HttpSession>> e : ALL_SESSIONS.entrySet()) {
      for (HttpSession s : e.getValue()) {
        s.invalidate();
      }
    }
    ALL_SESSIONS.clear();
    LOG.info("...Invalidated all sessions.");
  }
}
 
Example 10
Source Project: keycloak   File: HttpSessionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logoutAll() {
    log.info("Received request to log out all users.");
    for (HttpSession session : sessions.getAll()) {
        session.invalidate();
    }
    sessions.clear();
}
 
Example 11
Source Project: keycloak   File: OIDCFilterSessionStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void checkCurrentToken() {
    HttpSession httpSession = request.getSession(false);
    if (httpSession == null) return;
    SerializableKeycloakAccount account = (SerializableKeycloakAccount)httpSession.getAttribute(KeycloakAccount.class.getName());
    if (account == null) {
        return;
    }

    RefreshableKeycloakSecurityContext session = account.getKeycloakSecurityContext();
    if (session == null) return;

    // just in case session got serialized
    if (session.getDeployment() == null) session.setCurrentRequestInfo(deployment, this);

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return;

    // FYI: A refresh requires same scope, so same roles will be set.  Otherwise, refresh will fail and token will
    // not be updated
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) return;

    // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session
    //log.fine("Cleanup and expire session " + httpSession.getId() + " after failed refresh");
    cleanSession(httpSession);
    httpSession.invalidate();
}
 
Example 12
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  // you can also make an authenticated request to logout, but here we choose to
  // simply delete the session variables for simplicity
  HttpSession session =  req.getSession(false);
  if (session != null) {
    session.invalidate();
  }
  // rebuild session
  req.getSession();
}
 
Example 13
/**
 * Remove the user from the session and expire the session - after failed ticket auth.
 * 
 * @param req HttpServletRequest
 */
protected void invalidateSession(HttpServletRequest req)
{
    HttpSession session = req.getSession(false);
    if (session != null)
    {
        setExternalAuth(session, false);
        session.removeAttribute(getUserAttributeName());
        session.invalidate();
    }
}
 
Example 14
Source Project: Java-EE-VulnWeb   File: LoginServlet.java    License: MIT License 5 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	BusinessServer bs = new BusinessServerImpl();
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	if(username.equals("")||password.equals("")) {
		request.setAttribute("message", "用户名或密码为空");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		return;
	}
	HttpSession session = request.getSession(false);
	User user = new User();
	try {
		user = bs.loginUser(username, password);
	} catch (SQLException e) {
		request.setAttribute("message", "未知错误");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		return;
	}
	if (user != null) {
		request.setAttribute("message", "登录成功");
		session.invalidate();
		session = request.getSession();
		request.setAttribute("user", user);
		request.getRequestDispatcher("/message.jsp").forward(request, response);
		return;
	}
	request.setAttribute("message", "用户名或密码错误");
	request.getRequestDispatcher("/message.jsp").forward(request, response);
	return;
}
 
Example 15
Source Project: shiro-jersey   File: SessionResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invalidate the session without logging out the Shiro subject. For testing the remember me token.
 */
@DELETE
public String invalidateHttpSession() {
    HttpSession session = request.getSession(false);
    if (session == null) throw new WebApplicationException(Status.BAD_REQUEST);

    session.invalidate();
    return "session invalidated";
}
 
Example 16
Source Project: shiro-jersey   File: SessionResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invalidate the session without logging out the Shiro subject. For testing the remember me token.
 */
@DELETE
public String invalidateHttpSession() {
    HttpSession session = request.getSession(false);
    if (session == null) throw new WebApplicationException(Status.BAD_REQUEST);

    session.invalidate();
    return "session invalidated";
}
 
Example 17
public static void invalidateSession(HttpSession session)
{
    try
    {
        session.invalidate();
    }
    catch (IllegalStateException e)
    {
        // session was already invalidated
    }
}
 
Example 18
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    
    if (isRequestUrlExcluded(request)) {
        log.debug("Request is ignored.");
        filterChain.doFilter(request, response);
        return;
    }
    
    final HttpSession session = request.getSession(false);
    final Assertion assertion = session != null ? (Assertion) session.getAttribute(CONST_CAS_ASSERTION) : null;

    if (assertion != null && loggedOutOfSakai()) {
        log.debug("found a CAS assertion and we are logged out of Sakai. Invalidating the session so we don't get logged back on by an old assertion.");
        session.invalidate();
    }  else if (assertion != null) {
        filterChain.doFilter(request, response);
        return;
    }

    final String serviceUrl = constructServiceUrl(request, response);
    final String ticket = retrieveTicketFromRequest(request);
    final boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);

    if (CommonUtils.isNotBlank(ticket) || wasGatewayed) {
        filterChain.doFilter(request, response);
        return;
    }

    final String modifiedServiceUrl;

    log.debug("no ticket and no assertion found");
    if (this.gateway) {
        log.debug("setting gateway attribute in session");
        modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);
    } else {
        modifiedServiceUrl = serviceUrl;
    }

    if (log.isDebugEnabled()) {
    	log.debug("Constructed service url: {}", modifiedServiceUrl);
    }

    final String urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway);

    if (log.isDebugEnabled()) {
    	log.debug("redirecting to \"{}\"", urlToRedirectTo);
    }
    this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
}
 
Example 19
@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, final InetAddress remoteAddress, final String responseType,
                           final StringBuilder auditTrailSb,
                           final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    // Disallow non POST requests
    if (HTTPMethod.valueOf(req.getMethod()) != HTTPMethod.POST) {
        throw new ServerApiException(ApiErrorCode.METHOD_NOT_ALLOWED, "Please use HTTP POST to authenticate using this API");
    }
    // FIXME: ported from ApiServlet, refactor and cleanup
    final String[] username = (String[]) params.get(ApiConstants.USERNAME);
    final String[] password = (String[]) params.get(ApiConstants.PASSWORD);
    String[] domainIdArr = (String[]) params.get(ApiConstants.DOMAIN_ID);

    if (domainIdArr == null) {
        domainIdArr = (String[]) params.get(ApiConstants.DOMAIN__ID);
    }
    final String[] domainName = (String[]) params.get(ApiConstants.DOMAIN);
    Long domainId = null;
    if ((domainIdArr != null) && (domainIdArr.length > 0)) {
        try {
            //check if UUID is passed in for domain
            domainId = _apiServer.fetchDomainId(domainIdArr[0]);
            if (domainId == null) {
                domainId = Long.parseLong(domainIdArr[0]);
            }
            auditTrailSb.append(" domainid=" + domainId);// building the params for POST call
        } catch (final NumberFormatException e) {
            s_logger.warn("Invalid domain id entered by user");
            auditTrailSb.append(" " + HttpServletResponse.SC_UNAUTHORIZED + " " + "Invalid domain id entered, please enter a valid one");
            throw new ServerApiException(ApiErrorCode.UNAUTHORIZED,
                    _apiServer.getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid domain id entered, please enter a valid one", params,
                            responseType));
        }
    }

    String domain = null;
    if (domainName != null) {
        domain = domainName[0];
        auditTrailSb.append(" domain=" + domain);
        if (domain != null) {
            // ensure domain starts with '/' and ends with '/'
            if (!domain.endsWith("/")) {
                domain += '/';
            }
            if (!domain.startsWith("/")) {
                domain = "/" + domain;
            }
        }
    }

    String serializedResponse = null;
    if (username != null) {
        final String pwd = ((password == null) ? null : password[0]);
        try {
            return ApiResponseSerializer.toSerializedString(_apiServer.loginUser(session, username[0], pwd, domainId, domain, remoteAddress, params),
                    responseType);
        } catch (final CloudAuthenticationException ex) {
            // TODO: fall through to API key, or just fail here w/ auth error? (HTTP 401)
            try {
                session.invalidate();
            } catch (final IllegalStateException ise) {
            }
            auditTrailSb.append(" " + ApiErrorCode.ACCOUNT_ERROR + " " + ex.getMessage() != null ? ex.getMessage()
                    : "failed to authenticate user, check if username/password are correct");
            serializedResponse =
                    _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), ex.getMessage() != null ? ex.getMessage()
                            : "failed to authenticate user, check if username/password are correct", params, responseType);
        }
    }
    // We should not reach here and if we do we throw an exception
    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, serializedResponse);
}
 
Example 20
@RequestMapping("enable-user")
public void enableUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
	JSONObject data = (JSONObject) ServletUtils.getRequestJson(request);
	
	ID user = ID.valueOf(data.getString("user"));
	User u = Application.getUserStore().getUser(user);
	final boolean beforeDisabled = u.isDisabled();
	
	ID deptNew = null;
	ID roleNew = null;
	if (data.containsKey("dept")) {
		deptNew = ID.valueOf(data.getString("dept"));
		if (u.getOwningDept() != null && u.getOwningDept().getIdentity().equals(deptNew)) {
			deptNew = null;
		}
	}
	if (data.containsKey("role")) {
		roleNew = ID.valueOf(data.getString("role"));
		if (u.getOwningRole() != null && u.getOwningRole().getIdentity().equals(roleNew)) {
			roleNew = null;
		}
	}
	
	Boolean enableNew = null;
	if (data.containsKey("enable")) {
		enableNew = data.getBoolean("enable");
	}
	
	Application.getBean(UserService.class).updateEnableUser(user, deptNew, roleNew, enableNew);

	// 是否需要发送激活通知
	u = Application.getUserStore().getUser(user);
	if (beforeDisabled && u.isActive() && SMSender.availableMail() && u.getEmail() != null) {
		Object did = Application.createQuery(
				"select logId from LoginLog where user = ?")
				.setParameter(1, u.getId())
				.unique();
		if (did == null) {
			String homeUrl = SysConfiguration.getHomeUrl();
			String content = Languages.defaultBundle().formatLang("NewUserAccountActive",
                       u.getFullName(), homeUrl, homeUrl);
			SMSender.sendMailAsync(u.getEmail(),
                       Languages.defaultBundle().lang("YourAccountActive"), content);
		}
	}

	// 登录失效
	if (!u.isActive()) {
		HttpSession s = Application.getSessionStore().getSession(u.getId());
		if (s != null) {
			LOG.warn("Force destroy user session : " + u.getId());
			s.invalidate();
		}
	}
	
	writeSuccess(response);
}