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);
}
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();
}
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);
}
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);
}
}
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;
}
Aggregations