List of usage examples for javax.servlet.http HttpServletRequest logout
public void logout() throws ServletException;
null
as the value returned when getUserPrincipal
, getRemoteUser
, and getAuthType
is called on the request. From source file:com.castlemock.war.config.SecurityInterceptor.java
/** * The method will check if the logged in user is still valid. * @param request The incoming request.//from w w w .ja v a2 s . c om * @param response The outgoing response * @param handler The handler contains information about the method and controller that will process the incoming request * @return Returns true if the logged in users information is still valid. Returns false if the user is not valid * @throws IOException Upon unable to send a redirect as a response * @throws ServletException Upon unable to logout the user */ @Override public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws IOException, ServletException { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { return true; } final String loggedInUsername = authentication.getName(); if (ANONYMOUS_USER.equals(loggedInUsername)) { return true; } final ReadUserByUsernameInput readUserByUsernameInput = new ReadUserByUsernameInput(loggedInUsername); final ReadUserByUsernameOutput readUserByUsernameOutput = serviceProcessor.process(readUserByUsernameInput); final UserDto loggedInUser = readUserByUsernameOutput.getUser(); if (loggedInUser == null) { LOGGER.info("The following logged in user is not valid anymore: " + loggedInUsername); request.logout(); response.sendRedirect(request.getContextPath()); return false; } else if (!Status.ACTIVE.equals(loggedInUser.getStatus())) { LOGGER.info("The following logged in user is not active anymore: " + loggedInUsername); request.logout(); response.sendRedirect(request.getContextPath()); return false; } else { for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { Role role = Role.valueOf(grantedAuthority.getAuthority()); if (!loggedInUser.getRole().equals(role)) { LOGGER.info("The following logged in user's authorities has been updated: " + loggedInUsername); final UserDetails userDetails = userDetailSecurityService.loadUserByUsername(loggedInUsername); final Authentication newAuthentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); } } return true; } }
From source file:photosharing.api.bss.LogoutDefinition.java
/** * redirects the user to the logout SSO to destroy the login tokens and login sessions * //w ww . j ava2s . com * @see photosharing.api.conx.APIDefinition#run(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void run(HttpServletRequest request, HttpServletResponse response) { Configuration config = Configuration.getInstance(request); String api = config.getValue(Configuration.BASEURL) + apiUrl; try { //Invalidating photosharing session on the AppServer and IBM Connections Cloud HttpSession session = request.getSession(false); if (session != null) { logger.info(session.getId() + " is being logged out"); Request get = Request.Get(api); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes and if 200, convert to String */ int code = hr.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { } else { logger.log(Level.SEVERE, "Exception Encountered with IBM Connections Cloud Session"); } } catch (IOException e) { //Catches Exception Related to a Request logger.log(Level.SEVERE, "Exception Encountered"); response.setHeader("X-Application-Error", className); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } //Indvalidates the User's current session and logs them out session.invalidate(); request.logout(); //Sets the Status to SC_OK (Http Status Code 200) to indicate a successful logout response.setStatus(HttpStatus.SC_NO_CONTENT); } else { //Something bad has happened logger.log(Level.SEVERE, "Invalid Request"); response.setStatus(HttpStatus.SC_BAD_REQUEST); } } catch (Exception e) { logger.log(Level.SEVERE, "Exception Encountered - " + e.toString()); //Sets the Status to SC_INTERNAL_SERVER_ERROR (Http Status Code 500) //Indicates an issue with the Server response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
From source file:de.hska.ld.oidc.controller.OIDCController.java
@RequestMapping(method = RequestMethod.POST, value = "/document") @Transactional(readOnly = false, rollbackFor = RuntimeException.class) public Document createDocument(HttpServletRequest request, @RequestBody Document document, @RequestParam(defaultValue = "https://api.learning-layers.eu/o/oauth2") String issuer, @RequestHeader(required = false) String Authorization, @RequestParam(required = false) String discussionId, @RequestParam(required = false) String episodeId) throws IOException, ServletException { _authenticate(request, issuer, Authorization); // 3. Create the document in the database Document newDocument = documentService.save(document); if (document.getDescription() != null) { Attachment mainAttachment = newDocument.getAttachmentList().get(0); mainAttachment.setSource(document.getDescription().getBytes()); //document.setDescription(""); documentService.save(newDocument); if (episodeId != null) { DocumentSSSInfo documentSSSInfo = new DocumentSSSInfo(); documentSSSInfo.setDocument(newDocument); documentSSSInfo.setEpisodeId(episodeId); documentSSSInfoService.addDocumentInfo(documentSSSInfo); }// w ww . j a v a 2 s . co m } // 4. Create the document in the SSS together with the link to the discussion // 4.1 Authenticate with the SSS // SSS auth Endpoint: http://test-ll.know-center.tugraz.at/layers.test/auth/auth/ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); //if (auth instanceof AnonymousAuthenticationToken) { OIDCAuthenticationToken token = (OIDCAuthenticationToken) auth; SSSAuthDto sssAuthDto = null; try { sssAuthDto = sssClient.authenticate(token.getAccessTokenValue()); } catch (UserNotAuthorizedException e) { request.logout(); e.printStackTrace(); throw new UnauthorizedClientException("oidc token invalid"); } // 4.2 Create the according SSSLivingdocs entity try { SSSLivingdocsResponseDto sssLivingdocsResponseDto = sssClient.createDocument(document, discussionId, token.getAccessTokenValue()); } catch (AuthenticationNotValidException eAuth) { throw new UserNotAuthorizedException(); } // 4.3 Retrieve the list of email addresses that have access to the livingdocument in the SSS // TODO retrieve email addresses return newDocument; /*} else { throw new UnauthorizedClientException("anonymous user session"); }*/ }
From source file:com.example.AzureADAuthenticationFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try {/*from w w w . j av a 2 s. co m*/ String currentUri = AuthHelper.getCurrentUri(request); // Check if current session contains user authentication info. if (!AuthHelper.isAuthenticated(request)) { if (log.isTraceEnabled()) { log.trace("AuthHelper.isAuthenticated = false"); } if (AuthHelper.containsAuthenticationData(request)) { // The request contains authentication data, which means this request is returned from AzureAD login page // after authentication process is completed. The result should have been processed by AzureADResponseFilter. } else { if (log.isTraceEnabled()) { log.trace("AuthHelper.containsAuthenticationData = false"); } // when not authenticated and request does not contains authentication data (not come from Azure AD login process), // redirect to Azure login page. // get csrf token CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); if (log.isDebugEnabled()) { log.debug("Current csrf token before going to AzureAD login {} {} = {}", token.getHeaderName(), token.getParameterName(), token.getToken()); } // add the csrf token to login request and go login... response.setStatus(302); String redirectTo = getRedirectUrl(currentUri) + "&state=" + token.getToken(); if (log.isDebugEnabled()) { log.debug("302 redirect to " + redirectTo); } response.sendRedirect(redirectTo); return; } } else { if (log.isTraceEnabled()) { log.trace("AuthHelper.isAuthenticated = true"); } // if authenticated, how to check for valid session? AuthenticationResult result = AuthHelper.getAuthSessionObject(request); if (request.getParameter("refresh") != null) { result = getAccessTokenFromRefreshToken(result.getRefreshToken(), currentUri); } else { if (request.getParameter("cc") != null) { result = getAccessTokenFromClientCredentials(); } else { if (result.getExpiresOnDate().before(new Date())) { result = getAccessTokenFromRefreshToken(result.getRefreshToken(), currentUri); } } } AuthHelper.setAuthSessionObject(request, result); // Handle logout if (logout.equals(request.getRequestURI())) { if (log.isTraceEnabled()) { log.trace("Logout..."); } // Clear spring security context so spring thinks this user is gone. request.logout(); SecurityContextHolder.clearContext(); // Clear Azure principal AuthHelper.remoteAuthSessionObject(request); // Go to AzureAD and logout. response.setStatus(302); String logoutPage = "https://login.windows.net/" + tenant + "/oauth2/logout"; if (log.isDebugEnabled()) { log.debug("302 redirect to " + logoutPage); } response.sendRedirect(logoutPage); return; } else { if (log.isTraceEnabled()) { log.trace("URI: " + request.getRequestURI() + " does not match " + logout + ". It is not a logout request"); } } } } catch (Throwable exc) { response.setStatus(500); request.setAttribute("error", exc.getMessage()); response.sendRedirect(((HttpServletRequest) request).getContextPath() + error); } filterChain.doFilter(request, response); }
From source file:org.shareok.data.webserv.filters.UserSessionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try {/*w w w . j ava 2s. com*/ HttpServletRequest httpRequest = (HttpServletRequest) request; String contextPath = httpRequest.getServletPath(); if (contextPath.contains("/")) { contextPath = contextPath.split("/")[1]; } //.getContextPath(); if (null != contextPath && !"".equals(contextPath) && ShareokdataManager.requiredUserAuthentication(contextPath)) { SessionRepository<Session> repo = (SessionRepository<Session>) httpRequest .getAttribute(SessionRepository.class.getName()); if (contextPath.equals("register")) { String email = (String) httpRequest.getParameter("email"); String password = (String) httpRequest.getParameter("password"); String userName = (String) httpRequest.getParameter("nickname"); if (null == email || "".equals(email)) { throw new UserRegisterInfoNotFoundException( "Valid email register information is required!"); } if (null == password || "".equals(password)) { throw new UserRegisterInfoNotFoundException("Valid password is required for registration!"); } /***************** * Some password validation logic here: */ ExpiringSession session = (ExpiringSession) repo.createSession(); session.setMaxInactiveIntervalInSeconds(600); String sessionId = session.getId(); RedisUser user = redisUserService.findUserByUserEmail(email); if (null != user && password.equals(user.getPassword())) { session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user); user.setSessionKey(sessionId); user.setUserName(userName); redisUserService.updateUser(user); } else if (null == user) { ApplicationContext context = new ClassPathXmlApplicationContext("redisContext.xml"); user = (RedisUser) context.getBean("redisUser"); user.setEmail(email); user.setPassword(password); user.setSessionKey(sessionId); redisUserService.addUser(user); } else if (null != user && !password.equals(user.getPassword())) { throw new UserRegisterInfoNotFoundException( "Your login information does not match our records!`"); } session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user); repo.save(session); chain.doFilter(request, response); // HttpServletResponse httpReponse = (HttpServletResponse)response; // httpReponse.sendRedirect("/webserv/home"); } else { boolean sessionValidated = false; HttpSession session = (HttpSession) httpRequest.getSession(false); if (null != session) { ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId()); if (null != exSession) { RedisUser user = (RedisUser) session .getAttribute(ShareokdataManager.getSessionRedisUserAttributeName()); if (null != user) { RedisUser userPersisted = redisUserService.findAuthenticatedUser(user.getEmail(), session.getId()); if (null != userPersisted) { sessionValidated = true; } } } } if (!sessionValidated) { if (null != session) { repo.delete(session.getId()); session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null); session.invalidate(); } httpRequest.logout(); //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response); HttpServletResponse httpReponse = (HttpServletResponse) response; httpReponse.sendRedirect("/webserv/login"); } else { chain.doFilter(request, response); } } } else { chain.doFilter(request, response); } } catch (IOException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (ServletException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (UserRegisterInfoNotFoundException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } }
From source file:org.shareok.data.webserv.UserSessionInterceptor.java
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { try {//from w w w. ja v a2 s . c o m String contextPath = request.getServletPath(); if (contextPath.contains("/")) { contextPath = contextPath.split("/")[1]; } if (null != contextPath && !"".equals(contextPath) && ShareokdataManager.requiredUserAuthentication(contextPath)) { SessionRepository<Session> repo = (SessionRepository<Session>) request .getAttribute(SessionRepository.class.getName()); if (contextPath.equals("register")) { if (!configService.getRegistrationConfig()) { throw new NoNewUserRegistrationException("The registraion of new users has been closed!"); } String email = (String) request.getParameter("email"); String password = pwAuthenService.hash((String) request.getParameter("password")); String userName = (String) request.getParameter("nickname"); if (null == email || "".equals(email)) { throw new UserRegisterInfoNotFoundException( "Valid email register information is required!"); } if (null == password || "".equals(password)) { throw new UserRegisterInfoNotFoundException("Valid password is required for registration!"); } /***************** * Some password validation logic here: */ HttpSession httpSession = (HttpSession) request.getSession(); ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId()); if (null == session) { session = (ExpiringSession) repo.createSession(); } String sessionId = session.getId(); RedisUser user = redisUserService.findUserByUserEmail(email); if (null != user) { throw new RegisterUserInfoExistedException("User Email has already Existed!"); } else { user = redisUserService.getNewUser(); user.setEmail(email); user.setPassword(password); if (null == userName || userName.equals("")) { userName = email; } user.setUserName(userName); user.setSessionKey(sessionId); redisUserService.addUser(user); } setSessionUserInfo(session, httpSession, user); repo.save(session); } else if (contextPath.equals("userLogin")) { String email = (String) request.getParameter("email"); String password = (String) request.getParameter("password"); if (null == email || "".equals(email)) { throw new UserRegisterInfoNotFoundException( "Valid email information is required for logging in!"); } if (null == password || "".equals(password)) { throw new UserRegisterInfoNotFoundException("Valid password is required for logging in!"); } /***************** * Some password validation logic here: */ HttpSession httpSession = (HttpSession) request.getSession(); ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId()); if (null == session || session.isExpired()) { session = (ExpiringSession) repo.createSession(); } String sessionId = session.getId(); RedisUser user = redisUserService.findUserByUserEmail(email); if (null == user || !pwAuthenService.authenticate(password, user.getPassword())) { throw new UserRegisterInfoNotFoundException("User information cannot be found!"); } user.setSessionKey(sessionId); redisUserService.updateUser(user); setSessionUserInfo(session, httpSession, user); httpSession.setAttribute("email", email); repo.save(session); } else if (contextPath.equals("logout")) { HttpSession session = (HttpSession) request.getSession(false); if (null != session) { ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId()); if (null != exSession) { String email = (String) session.getAttribute("email"); if (null != email) { redisUserService.invalidateUserSessionIdByEmail(email); } exSession.isExpired(); repo.delete(exSession.getId()); } session.invalidate(); } } // *** The following situation applies to authentication logic based on session information *** else { boolean sessionValidated = false; HttpSession session = (HttpSession) request.getSession(false); if (null != session) { ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId()); if (null != exSession && !exSession.isExpired()) { String email = (String) session.getAttribute("email"); if (null != email) { RedisUser userPersisted = redisUserService.findAuthenticatedUser(email, session.getId()); if (null != userPersisted) { sessionValidated = true; } } } } if (!sessionValidated) { if (null != session) { repo.delete(session.getId()); session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null); session.invalidate(); } request.logout(); //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response); HttpServletResponse httpReponse = (HttpServletResponse) response; httpReponse.sendRedirect("/webserv/login"); } } } else { ; } } catch (IOException ex) { request.setAttribute("errorMessage", ex.getMessage()); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (ServletException ex) { request.setAttribute("errorMessage", ex.getMessage()); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (UserRegisterInfoNotFoundException ex) { request.setAttribute("errorMessage", ex.getMessage()); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (RegisterUserInfoExistedException ex) { request.setAttribute("errorMessage", ex.getMessage()); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (NoNewUserRegistrationException ex) { request.setAttribute("errorMessage", ex.getMessage()); request.getRequestDispatcher("/WEB-INF/jsp/closedRegistration.jsp").forward(request, response); } return true; }
From source file:org.jasig.cas.client.session.SingleSignOutHandler.java
/** * Destroys the current HTTP session for the given CAS logout request. * * @param request HTTP request containing a CAS logout message. *//*from w w w.j a v a 2 s . c om*/ private void destroySession(final HttpServletRequest request) { final String logoutMessage; // front channel logout -> the message needs to be base64 decoded + decompressed if (isFrontChannelLogoutRequest(request)) { logoutMessage = uncompressLogoutMessage( CommonUtils.safeGetParameter(request, this.frontLogoutParameterName)); } else { logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); } logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session [{}] for token [{}]", sessionID, token); try { session.invalidate(); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } try { request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } } } }
From source file:org.structr.core.auth.AuthHelper.java
public static void doLogout(final HttpServletRequest request, final Principal user) throws FrameworkException { final HttpSession session = request.getSession(false); // We need a session to logout a user if (session != null) { AuthHelper.clearSession(session.getId()); user.removeSessionId(session.getId()); Actions.call(Actions.NOTIFICATION_LOGOUT, user); try {/*w w w .j a v a2s .c o m*/ request.logout(); request.changeSessionId(); } catch (Throwable t) { } } }
From source file:org.structr.rest.auth.AuthHelper.java
public static void doLogout(final HttpServletRequest request, final Principal user) throws FrameworkException { final HttpSession session = request.getSession(false); // We need a session to logout a user if (session != null) { SessionHelper.clearSession(session.getId()); SessionHelper.invalidateSession(session); Actions.call(Actions.NOTIFICATION_LOGOUT, user); try {/* ww w.j a v a 2 s . co m*/ request.logout(); request.changeSessionId(); } catch (Throwable t) { } } }
From source file:org.structr.rest.auth.SessionHelper.java
public static Principal checkSessionAuthentication(final HttpServletRequest request) throws FrameworkException { String requestedSessionId = request.getRequestedSessionId(); String sessionId = null;// w w w .ja v a 2 s .c o m logger.debug("0. Requested session id: " + requestedSessionId + ", request says is valid? " + request.isRequestedSessionIdValid()); //HttpSession session = request.getSession(false); boolean isNotTimedOut = false; if (requestedSessionId == null) { logger.debug("1b. Empty requested session id, creating a new one."); // No session id requested => create new session SessionHelper.newSession(request); // Store info in request that session is new => saves us a lookup later request.setAttribute(SESSION_IS_NEW, true); // we just created a totally new session, there can't // be a user with this session ID, so don't search. return null; } else { requestedSessionId = getShortSessionId(requestedSessionId); // Existing session id, check if we have an existing session if (request.getSession(false) != null) { logger.debug("1a. Requested session id without worker id suffix: " + requestedSessionId); sessionId = request.getSession(false).getId(); logger.debug("2a. Current session id: " + sessionId); if (sessionId.equals(requestedSessionId)) { logger.debug("3a. Current session id equals requested session id"); } else { logger.debug("3b. Current session id does not equal requested session id."); } } else { logger.debug("2b. Current session is null."); // Try to find session in session cache if (getSessionBySessionId(requestedSessionId) == null) { // Not found, create new SessionHelper.newSession(request); logger.debug("3a. Created new session"); // remove session ID without session SessionHelper.clearSession(requestedSessionId); logger.debug("4. Cleared unknown session " + requestedSessionId); // we just created a totally new session, there can't // be a user with this session ID, so don't search. return null; } else { logger.debug("3b. Session with requested id " + requestedSessionId + " found, continuing."); sessionId = requestedSessionId; } } if (SessionHelper.isSessionTimedOut(request.getSession(false))) { isNotTimedOut = false; // invalidate session SessionHelper.invalidateSession(sessionId); // remove invalid session ID SessionHelper.clearSession(sessionId); logger.debug("4a. Cleared timed-out session " + sessionId); SessionHelper.newSession(request); // we just created a totally new session, there can't // be a user with this session ID, so don't search. return null; } else { logger.debug("4b. Session " + sessionId + " is not timed-out."); isNotTimedOut = true; } } if (isNotTimedOut) { final Principal user = AuthHelper.getPrincipalForSessionId(sessionId); //logger.debug("Valid session found: {}, last accessed {}, authenticated with user {}", new Object[]{session, session.getLastAccessedTime(), user}); return user; } else { final Principal user = AuthHelper.getPrincipalForSessionId(sessionId); if (user != null) { //logger.info("Timed-out session: {}, last accessed {}, authenticated with user {}", new Object[]{session, (session != null ? session.getLastAccessedTime() : ""), user}); logger.debug("Logging out user {}", new Object[] { user }); AuthHelper.doLogout(request, user); try { request.logout(); } catch (Throwable t) { } } SessionHelper.newSession(request); return null; } }