io.undertow.server.session.Session Java Examples

The following examples show how to use io.undertow.server.session.Session. 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
Source File: ChangeSessionId.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String changeSessionId(HttpServerExchange exchange, boolean create) {
    final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletContextImpl currentServletContext = sc.getCurrentServletContext();
    HttpSessionImpl session = currentServletContext.getSession(exchange, create);
    if (session == null) {
        return null;
    }
    Session underlyingSession;
    if(System.getSecurityManager() == null) {
        underlyingSession = session.getSession();
    } else {
        underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }


    return underlyingSession.changeSessionId(exchange, currentServletContext.getSessionConfig());
}
 
Example #2
Source File: HttpServletRequestImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String changeSessionId() {
    HttpSessionImpl session = servletContext.getSession(originalServletContext, exchange, false);
    if (session == null) {
        throw UndertowServletMessages.MESSAGES.noSession();
    }
    String oldId = session.getId();
    Session underlyingSession;
    if(System.getSecurityManager() == null) {
        underlyingSession = session.getSession();
    } else {
        underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
    String newId = underlyingSession.changeSessionId(exchange, originalServletContext.getSessionConfig());
    servletContext.getDeployment().getApplicationListeners().httpSessionIdChanged(session, oldId);
    return newId;
}
 
Example #3
Source File: JsrWebSocketFilter.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent se) {
    HttpSessionImpl session = (HttpSessionImpl) se.getSession();
    final Session underlying;
    if (System.getSecurityManager() == null) {
        underlying = session.getSession();
    } else {
        underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
    List<UndertowSession> connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE);
    if (connections != null) {
        synchronized (underlying) {
            for (UndertowSession c : connections) {
                try {
                    c.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, ""));
                } catch (IOException e) {
                    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                }
            }
        }
    }
}
 
Example #4
Source File: ServletFormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method doesn't save content of request but instead uses data from parameter.
 * This should be used in case that data from request was already read and therefore it is not possible to save them.
 *
 * @param exchange
 * @param bytes
 * @param contentLength
 */
protected void storeInitialLocation(final HttpServerExchange exchange, byte[] bytes, int contentLength) {
    if(!saveOriginalRequest) {
        return;
    }
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    Session session;
    if (System.getSecurityManager() == null) {
        session = httpSession.getSession();
    } else {
        session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
    }
    SessionManager manager = session.getSessionManager();
    if (seenSessionManagers.add(manager)) {
        manager.registerSessionListener(LISTENER);
    }
    session.setAttribute(SESSION_KEY, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
    if(bytes == null) {
        SavedRequest.trySaveRequest(exchange);
    } else {
        SavedRequest.trySaveRequest(exchange, bytes, contentLength);
    }
}
 
Example #5
Source File: ServletFormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void handleRedirectBack(final HttpServerExchange exchange) {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpServletResponse resp = (HttpServletResponse) servletRequestContext.getServletResponse();
    HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, false);
    if (httpSession != null) {
        Session session;
        if (System.getSecurityManager() == null) {
            session = httpSession.getSession();
        } else {
            session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
        }
        String path = (String) session.getAttribute(SESSION_KEY);
        if (path != null) {
            try {
                resp.sendRedirect(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
 
Example #6
Source File: SessionListenerBridge.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void attributeUpdated(final Session session, final String name, final Object value, final Object old) {
    if (name.startsWith(IO_UNDERTOW)) {
        return;
    }
    final HttpSessionImpl httpSession = SecurityActions.forSession(session, servletContext, false);
    if (old != value) {
        if (old instanceof HttpSessionBindingListener) {
            ((HttpSessionBindingListener) old).valueUnbound(new HttpSessionBindingEvent(httpSession, name, old));
        }
        applicationListeners.httpSessionAttributeReplaced(httpSession, name, old);
    }
    if (value instanceof HttpSessionBindingListener) {
        ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(httpSession, name, value));
    }
}
 
Example #7
Source File: SessionListenerBridge.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void attributeRemoved(final Session session, final String name, final Object old) {
    if (name.startsWith(IO_UNDERTOW)) {
        return;
    }
    final HttpSessionImpl httpSession = SecurityActions.forSession(session, servletContext, false);
    if (old != null) {
        applicationListeners.httpSessionAttributeRemoved(httpSession, name, old);
        if (old instanceof HttpSessionBindingListener) {
            ((HttpSessionBindingListener) old).valueUnbound(new HttpSessionBindingEvent(httpSession, name, old));
        }
    }
}
 
Example #8
Source File: SecurityActions.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
static HttpSessionImpl forSession(final Session session, final ServletContext servletContext, final boolean newSession) {
    if (System.getSecurityManager() == null) {
        return HttpSessionImpl.forSession(session, servletContext, newSession);
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<HttpSessionImpl>() {
            @Override
            public HttpSessionImpl run() {
                return HttpSessionImpl.forSession(session, servletContext, newSession);
            }
        });
    }
}
 
Example #9
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    Cookie cookie = exchange.getRequestCookies().get(cookieName);
    if (cookie != null) {
        final String ssoId = cookie.getValue();
        log.tracef("Found SSO cookie %s", ssoId);
        try (SingleSignOn sso = this.singleSignOnManager.findSingleSignOn(ssoId)) {
            if (sso != null) {
                if(log.isTraceEnabled()) {
                    log.tracef("SSO session with ID: %s found.", ssoId);
                }
                Account verified = getIdentityManager(securityContext).verify(sso.getAccount());
                if (verified == null) {
                    if(log.isTraceEnabled()) {
                        log.tracef("Account not found. Returning 'not attempted' here.");
                    }
                    //we return not attempted here to allow other mechanisms to proceed as normal
                    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
                }
                final Session session = getSession(exchange);
                registerSessionIfRequired(sso, session);
                securityContext.authenticationComplete(verified, sso.getMechanismName(), false);
                securityContext.registerNotificationReceiver(new NotificationReceiver() {
                    @Override
                    public void handleNotification(SecurityNotification notification) {
                        if (notification.getEventType() == SecurityNotification.EventType.LOGGED_OUT) {
                            singleSignOnManager.removeSingleSignOn(sso);
                        }
                    }
                });
                log.tracef("Authenticated account %s using SSO", verified.getPrincipal().getName());
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            }
        }
        clearSsoCookie(exchange);
    }
    exchange.addResponseWrapper(responseListener);
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #10
Source File: SessionListenerBridge.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void attributeAdded(final Session session, final String name, final Object value) {
    if (name.startsWith(IO_UNDERTOW)) {
        return;
    }
    final HttpSessionImpl httpSession = SecurityActions.forSession(session, servletContext, false);
    applicationListeners.httpSessionAttributeAdded(httpSession, name, value);
    if (value instanceof HttpSessionBindingListener) {
        ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(httpSession, name, value));
    }
}
 
Example #11
Source File: SecurityActions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static HttpSessionImpl forSession(final Session session, final ServletContext servletContext, final boolean newSession) {
    if (System.getSecurityManager() == null) {
        return HttpSessionImpl.forSession(session, servletContext, newSession);
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<HttpSessionImpl>() {
            @Override
            public HttpSessionImpl run() {
                return HttpSessionImpl.forSession(session, servletContext, newSession);
            }
        });
    }
}
 
Example #12
Source File: IdMapperUpdaterSessionListener.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionIdChanged(Session session, String oldSessionId) {
    Object value = session.getAttribute(SamlSession.class.getName());
    if (value != null) {
        unmap(oldSessionId, value);
        map(session.getId(), value);
    }
}
 
Example #13
Source File: SavedRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.DEFAULT_MAX_BUFFERED_REQUEST_SIZE);
    if (maxSize > 0) {
        if (length > maxSize) {
            UndertowLogger.REQUEST_LOGGER.debugf("Request to %s was to large to save", exchange.getRequestURI());
            return;//failed to save the request, we just return
        }
        //TODO: we should really be used pooled buffers
        //TODO: we should probably limit the number of saved requests at any given time
        HeaderMap headers = new HeaderMap();
        for (HeaderValues entry : exchange.getRequestHeaders()) {
            if (entry.getHeaderName().equals(Headers.CONTENT_LENGTH) ||
                    entry.getHeaderName().equals(Headers.TRANSFER_ENCODING) ||
                    entry.getHeaderName().equals(Headers.CONNECTION)) {
                continue;
            }
            headers.putAll(entry.getHeaderName(), entry);
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), exchange.getRequestHeaders());
        final ServletRequestContext sc = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl session = sc.getCurrentServletContext().getSession(exchange, true);
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = session.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        underlyingSession.setAttribute(SESSION_KEY, request);
    }
}
 
Example #14
Source File: CachedAuthenticatedSessionHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticatedSession lookupSession(HttpServerExchange exchange) {

    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sessionManager == null || sessionConfig == null) {
        return null;
    }
    Session httpSession = sessionManager.getSession(exchange, sessionConfig);
    if (httpSession != null) {
        return (AuthenticatedSession) httpSession.getAttribute(ATTRIBUTE_NAME);
    }
    return null;
}
 
Example #15
Source File: IdMapperUpdaterSessionListener.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void attributeUpdated(Session session, String name, Object newValue, Object oldValue) {
    if (Objects.equals(name, SamlSession.class.getName())) {
        unmap(session.getId(), oldValue);
        map(session.getId(), newValue);
    }
}
 
Example #16
Source File: HttpSessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public Session getSession() {
    SecurityManager sm = System.getSecurityManager();
    if(sm != null) {
        sm.checkPermission(PERMISSION);
    }
    return session;
}
 
Example #17
Source File: SecurityActions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static HttpSessionImpl forSession(final Session session, final ServletContext servletContext, final boolean newSession) {
    if (System.getSecurityManager() == null) {
        return HttpSessionImpl.forSession(session, servletContext, newSession);
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<HttpSessionImpl>() {
            @Override
            public HttpSessionImpl run() {
                return HttpSessionImpl.forSession(session, servletContext, newSession);
            }
        });
    }
}
 
Example #18
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void updateSessionAccessTime(final HttpServerExchange exchange) {
    HttpSessionImpl httpSession = getSession(exchange, false);
    if (httpSession != null) {
        Session underlyingSession;
        if (System.getSecurityManager() == null) {
            underlyingSession = httpSession.getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
        }
        underlyingSession.requestDone(exchange);
    }
}
 
Example #19
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeCommit(HttpServerExchange exchange) {

    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account != null) {
        try (SingleSignOn sso = singleSignOnManager.createSingleSignOn(account, sc.getMechanismName())) {
            Session session = getSession(exchange);
            registerSessionIfRequired(sso, session);
            exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName, sso.getId()).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
        }
    }
}
 
Example #20
Source File: SessionListenerBridge.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void attributeRemoved(final Session session, final String name, final Object old) {
    if (name.startsWith(IO_UNDERTOW)) {
        return;
    }
    final HttpSessionImpl httpSession = SecurityActions.forSession(session, servletContext, false);
    if (old != null) {
        applicationListeners.httpSessionAttributeRemoved(httpSession, name, old);
        if (old instanceof HttpSessionBindingListener) {
            ((HttpSessionBindingListener) old).valueUnbound(new HttpSessionBindingEvent(httpSession, name, old));
        }
    }
}
 
Example #21
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDestroyed(Session session, HttpServerExchange exchange, SessionDestroyedReason reason) {
    String ssoId = (String) session.getAttribute(SSO_SESSION_ATTRIBUTE);
    if (ssoId != null) {
        if (log.isTraceEnabled()) {
            log.tracef("Removing SSO ID %s from destroyed session %s.", ssoId, session.getId());
        }
        List<Session> sessionsToRemove = new LinkedList<>();
        try (SingleSignOn sso = singleSignOnManager.findSingleSignOn(ssoId)) {
            if (sso != null) {
                sso.remove(session);
                if (reason == SessionDestroyedReason.INVALIDATED) {
                    for (Session associatedSession : sso) {
                        sso.remove(associatedSession);
                        sessionsToRemove.add(associatedSession);
                    }
                }
                // If there are no more associated sessions, remove the SSO altogether
                if (!sso.iterator().hasNext()) {
                    singleSignOnManager.removeSingleSignOn(sso);
                }
            }
        }
        // Any consequential session invalidations will trigger this listener recursively,
        // so make sure we don't attempt to invalidate session until after the sso is removed.
        for (Session sessionToRemove : sessionsToRemove) {
            sessionToRemove.invalidate(null);
        }
    }
}
 
Example #22
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Session underlyingSession(HttpSessionImpl httpSession) {
    Session session;
    if (System.getSecurityManager() == null) {
        session = httpSession.getSession();
    } else {
        session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
    }
    return session;
}
 
Example #23
Source File: UndertowSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    Session session = Sessions.getSession(exchange);
    if (session == null) {
        log.debug("session was null, returning null");
        return false;
    }
    KeycloakUndertowAccount account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
    if (account == null) {
        log.debug("Account was not in session, returning null");
        return false;
    }

    if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
        log.debug("Account in session belongs to a different realm than for this request.");
        return false;
    }

    account.setCurrentRequestInfo(deployment, this);
    if (account.checkActive()) {
        log.debug("Cached account found");
        securityContext.authenticationComplete(account, "KEYCLOAK", false);
        ((AbstractUndertowRequestAuthenticator)authenticator).propagateKeycloakContext(account);
        return true;
    } else {
        log.debug("Account was not active, returning false");
        session.removeAttribute(KeycloakUndertowAccount.class.getName());
        session.removeAttribute(KeycloakSecurityContext.class.getName());
        session.invalidate(exchange);
        return false;
    }
}
 
Example #24
Source File: SessionListenerBridge.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SessionListenerBridge(final Deployment deployment, final ApplicationListeners applicationListeners, final ServletContext servletContext) {
    this.applicationListeners = applicationListeners;
    this.servletContext = servletContext;
    this.destroyedAction = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Session>() {
        @Override
        public Void call(HttpServerExchange exchange, Session session) throws ServletException {
            doDestroy(session);
            return null;
        }
    });
}
 
Example #25
Source File: LearningPushHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Session getSession(HttpServerExchange exchange) {
    SessionConfig sc = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    if (sc == null || sm == null) {
        return null;
    }
    Session session = sm.getSession(exchange, sc);
    if (session == null) {
        return sm.createSession(exchange, sc);
    }
    return session;
}
 
Example #26
Source File: ServletSingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Session getSession(HttpServerExchange exchange) {
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    final HttpSessionImpl session = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    if(System.getSecurityManager() == null) {
        return session.getSession();
    } else {
        return AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
    }
}
 
Example #27
Source File: UndertowSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void logout() {
    Session session = Sessions.getSession(exchange);
    if (session == null) return;
    KeycloakUndertowAccount account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
    if (account == null) return;
    session.removeAttribute(KeycloakUndertowAccount.class.getName());
    session.removeAttribute(KeycloakSecurityContext.class.getName());
}
 
Example #28
Source File: Sessions.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private static Session getSession(final HttpServerExchange exchange, boolean create) {
    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if(sessionManager == null) {
        throw UndertowMessages.MESSAGES.sessionManagerNotFound();
    }
    Session session = sessionManager.getSession(exchange, sessionConfig);
    if(session == null && create) {
        session = sessionManager.createSession(exchange, sessionConfig);
    }
    return session;
}
 
Example #29
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AuthenticatedSession lookupSession(HttpServerExchange exchange) {
    HttpSessionImpl httpSession = servletContext.getSession(exchange, false);
    if (httpSession != null) {
        Session session = underlyingSession(httpSession);
        return (AuthenticatedSession) session.getAttribute(ATTRIBUTE_NAME);
    }
    return null;
}
 
Example #30
Source File: LearningPushHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
protected Session getSession(HttpServerExchange exchange) {
    SessionConfig sc = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    if (sc == null || sm == null) {
        return null;
    }
    Session session = sm.getSession(exchange, sc);
    if (session == null) {
        return sm.createSession(exchange, sc);
    }
    return session;
}