Search in sources :

Example 1 with SessionInformation

use of org.springframework.security.core.session.SessionInformation in project spring-security by spring-projects.

the class ConcurrentSessionFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);
    if (session != null) {
        SessionInformation info = sessionRegistry.getSessionInformation(session.getId());
        if (info != null) {
            if (info.isExpired()) {
                // Expired - abort processing
                if (logger.isDebugEnabled()) {
                    logger.debug("Requested session ID " + request.getRequestedSessionId() + " has expired.");
                }
                doLogout(request, response);
                this.sessionInformationExpiredStrategy.onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));
                return;
            } else {
                // Non-expired - update last request date/time
                sessionRegistry.refreshLastRequest(info.getSessionId());
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SessionInformation(org.springframework.security.core.session.SessionInformation) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 2 with SessionInformation

use of org.springframework.security.core.session.SessionInformation in project spring-security by spring-projects.

the class SessionRegistryImplTests method testTwoSessionsOnePrincipalExpiring.

@Test
public void testTwoSessionsOnePrincipalExpiring() throws Exception {
    Object principal = "Some principal object";
    String sessionId1 = "1234567890";
    String sessionId2 = "9876543210";
    sessionRegistry.registerNewSession(sessionId1, principal);
    List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal, false);
    assertThat(sessions).hasSize(1);
    assertThat(contains(sessionId1, principal)).isTrue();
    sessionRegistry.registerNewSession(sessionId2, principal);
    sessions = sessionRegistry.getAllSessions(principal, false);
    assertThat(sessions).hasSize(2);
    assertThat(contains(sessionId2, principal)).isTrue();
    // Expire one session
    SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
    session.expireNow();
    // Check retrieval still correct
    assertThat(sessionRegistry.getSessionInformation(sessionId2).isExpired()).isTrue();
    assertThat(sessionRegistry.getSessionInformation(sessionId1).isExpired()).isFalse();
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) Test(org.junit.Test)

Example 3 with SessionInformation

use of org.springframework.security.core.session.SessionInformation in project webcert by sklintyg.

the class WebcertLoggingSessionRegistryImpl method removeSessionInformation.

@Override
public void removeSessionInformation(String sessionId) {
    LOGGER.debug("Attempting to remove session '{}'", sessionId);
    SessionInformation sessionInformation = getSessionInformation(sessionId);
    if (sessionInformation == null) {
        super.removeSessionInformation(sessionId);
        return;
    }
    Object principal = sessionInformation.getPrincipal();
    if (principal instanceof WebCertUser) {
        WebCertUser user = (WebCertUser) principal;
        if (sessionInformation.isExpired()) {
            monitoringService.logUserSessionExpired(user.getHsaId(), user.getAuthenticationScheme());
        } else {
            monitoringService.logUserLogout(user.getHsaId(), user.getAuthenticationScheme());
        }
    }
    super.removeSessionInformation(sessionId);
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) WebCertUser(se.inera.intyg.webcert.web.service.user.dto.WebCertUser)

Example 4 with SessionInformation

use of org.springframework.security.core.session.SessionInformation in project ma-core-public by infiniteautomation.

the class MangoSessionRegistry method userUpdated.

/**
 * This method should be called if a user is updated via HTTP (e.g. via our UserRestController).
 * If the user's ID is the same as the current HTTP user's ID then the Spring Security context and
 * session attributes will be updated.
 *
 * @param request
 * @param user
 */
public void userUpdated(HttpServletRequest request, User user) {
    User currentUser = Common.getHttpUser();
    if (currentUser == null || currentUser.getId() != user.getId()) {
        return;
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        SessionInformation info = this.getSessionInformation(session.getId());
        if (info == null) {
            if (logger.isWarnEnabled()) {
                logger.warn("Unknown session " + session.getId());
            }
        } else if (info.isExpired() && !user.isDisabled()) {
            // Session was set to expire via a call to exireSessionsForUser() from the DAO.
            // Invalidate the current session and register a new one right now so the user can continue working.
            // Copy all attributes as per SessionFixationProtectionStrategy
            Enumeration<String> names = session.getAttributeNames();
            Map<String, Object> attributes = new HashMap<>();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                attributes.put(name, session.getAttribute(name));
            }
            this.removeSessionInformation(session.getId());
            session.invalidate();
            HttpSession newSession = request.getSession(true);
            this.registerNewSession(newSession.getId(), user);
            for (Entry<String, Object> entry : attributes.entrySet()) {
                newSession.setAttribute(entry.getKey(), entry.getValue());
            }
            session = newSession;
        }
        // update the session attribute for legacy pages with the new user
        session.setAttribute(Common.SESSION_USER, user);
    }
    // Set the spring security context (thread local) to a new Authentication with the updated user and authorities.
    // Updates the SPRING_SECURITY_CONTEXT session attribute as well.
    // Should always be a UsernamePasswordAuthenticationToken a user cannot update themselves via a JWT.
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (currentAuthentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken newAuthentication = MangoPasswordAuthenticationProvider.createAuthenticatedToken(user);
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);
    }
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) Entry(java.util.Map.Entry) User(com.serotonin.m2m2.vo.User) Enumeration(java.util.Enumeration) HttpSession(javax.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with SessionInformation

use of org.springframework.security.core.session.SessionInformation in project ma-core-public by infiniteautomation.

the class MangoWebSocketPublisher method getUser.

/**
 * Gets the Mango user for a WebSocketSession. If there is no user and closeOnLogout is true then the WebSocketSession is closed.
 *
 * Will return null when:
 * <ul>
 *   <li>There never was a user</li>
 *   <li>Session was invalidated (user logged out, admin disabled them or changed their password)</li>
 *   <li>JWT auth token has expired, been revoked or the private/public keys changed</li>
 * </ul>
 *
 * TODO Mango 3.4 store the user and authentication in the WebSocketSession attributes using the handshake intercepter.
 * Use the sessionDestroyed/user modified/JWT key changed events to replace the user in the attributes or close the session as appropriate.
 * If we have a user modified and JWT key changed event we don't have to re-parse and re-validate the JWT token every time.
 *
 * @param session
 * @return user or null
 */
protected User getUser(WebSocketSession session) {
    User user = null;
    Authentication authentication = null;
    // get the user at the time of HTTP -> websocket upgrade
    Principal principal = session.getPrincipal();
    if (principal instanceof Authentication) {
        authentication = (Authentication) principal;
        Object authenticationPrincipal = authentication.getPrincipal();
        if (authenticationPrincipal instanceof User) {
            user = (User) authenticationPrincipal;
        }
    }
    // user should never be null as long as the websocket URLs are protected by Spring Security
    if (user != null) {
        String httpSessionId = httpSessionIdForSession(session);
        if (httpSessionId != null) {
            SessionInformation sessionInformation = sessionRegistry.getSessionInformation(httpSessionId);
            if (sessionInformation != null && !sessionInformation.isExpired()) {
                // we dont have to check if the user is disabled etc as the session would be invalidated if the user was modified
                return user;
            }
        }
        // no valid session, check for an authentication token
        if (authentication instanceof PreAuthenticatedAuthenticationToken) {
            PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) authentication;
            Object credentials = token.getCredentials();
            if (credentials instanceof String) {
                String jwtString = (String) credentials;
                BearerAuthenticationToken bearerToken = new BearerAuthenticationToken(jwtString);
                /**
                 * Re-authenticate the token as
                 * a) The user might have been disabled
                 * b) The user's tokens might have been revoked
                 * c) The JWT private key might have changed
                 */
                try {
                    Authentication newAuthentication = this.authenticationManager.authenticate(bearerToken);
                    Object newPrincipal = newAuthentication.getPrincipal();
                    if (newPrincipal instanceof User) {
                        return (User) newPrincipal;
                    }
                } catch (AuthenticationException e) {
                // token is no longer valid
                // do nothing, just return null
                }
            }
        }
    }
    // TODO Mango 3.4 don't close sessions here
    if (this.closeOnLogout) {
        this.closeSession(session, NOT_AUTHENTICATED);
    }
    return null;
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) User(com.serotonin.m2m2.vo.User) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) BearerAuthenticationToken(com.serotonin.m2m2.web.mvc.spring.security.authentication.BearerAuthenticationToken) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) Principal(java.security.Principal)

Aggregations

SessionInformation (org.springframework.security.core.session.SessionInformation)27 Date (java.util.Date)10 Test (org.junit.jupiter.api.Test)8 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)7 SessionRegistry (org.springframework.security.core.session.SessionRegistry)7 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 Test (org.junit.Test)5 MockFilterChain (org.springframework.mock.web.MockFilterChain)5 MockHttpSession (org.springframework.mock.web.MockHttpSession)5 ConcurrentSessionFilter (org.springframework.security.web.session.ConcurrentSessionFilter)5 ArrayList (java.util.ArrayList)3 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 Authentication (org.springframework.security.core.Authentication)3 RedirectStrategy (org.springframework.security.web.RedirectStrategy)3 MapSession (org.springframework.session.MapSession)3 Session (org.springframework.session.Session)3 GuiProfiledPrincipal (com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal)2 PrismObject (com.evolveum.midpoint.prism.PrismObject)2 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)2 User (com.serotonin.m2m2.vo.User)2