Java Code Examples for io.undertow.server.session.Session#setAttribute()

The following examples show how to use io.undertow.server.session.Session#setAttribute() . 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: ServletFormAuthenticationMechanism.java    From quarkus-http with Apache License 2.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 2
Source File: SavedRequest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void tryRestoreRequest(final HttpServerExchange exchange, HttpSession session) {
    if(session instanceof HttpSessionImpl) {

        Session underlyingSession;
        if(System.getSecurityManager() == null) {
            underlyingSession = ((HttpSessionImpl) session).getSession();
        } else {
            underlyingSession = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
        }
        io.undertow.servlet.util.SavedRequest request = (io.undertow.servlet.util.SavedRequest) underlyingSession.removeAttribute(SESSION_KEY);
        if (request != null) {
            underlyingSession.setAttribute(io.undertow.servlet.util.SavedRequest.class.getName(), request);
            io.undertow.servlet.util.SavedRequest.tryRestoreRequest(exchange, session);

        }

     }
}
 
Example 3
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 4
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void registerSessionIfRequired(SingleSignOn sso, Session session) {
    if (!sso.contains(session)) {
        if(log.isTraceEnabled()) {
            log.tracef("Session %s added to SSO %s", session.getId(), sso.getId());
        }
        sso.add(session);
    }
    if(session.getAttribute(SSO_SESSION_ATTRIBUTE) == null) {
        if(log.isTraceEnabled()) {
            log.tracef("SSO_SESSION_ATTRIBUTE not found. Creating it with SSO ID %s as value.", sso.getId());
        }
        session.setAttribute(SSO_SESSION_ATTRIBUTE, sso.getId());
    }
    SessionManager manager = session.getSessionManager();
    if (seenSessionManagers.add(manager)) {
        manager.registerSessionListener(listener);
    }
}
 
Example 5
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private void registerSessionIfRequired(SingleSignOn sso, Session session) {
    if (!sso.contains(session)) {
        if (log.isTraceEnabled()) {
            log.tracef("Session %s added to SSO %s", session.getId(), sso.getId());
        }
        sso.add(session);
    }
    if (session.getAttribute(SSO_SESSION_ATTRIBUTE) == null) {
        if (log.isTraceEnabled()) {
            log.tracef("SSO_SESSION_ATTRIBUTE not found. Creating it with SSO ID %s as value.", sso.getId());
        }
        session.setAttribute(SSO_SESSION_ATTRIBUTE, sso.getId());
    }
    SessionManager manager = session.getSessionManager();
    if (seenSessionManagers.add(manager)) {
        manager.registerSessionListener(listener);
    }
}
 
Example 6
Source File: CachedAuthenticatedSessionHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleNotification(SecurityNotification notification) {
    EventType eventType = notification.getEventType();
    HttpServerExchange exchange = notification.getExchange();
    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sessionManager == null || sessionConfig == null) {
        return;
    }
    Session httpSession = sessionManager.getSession(exchange, sessionConfig);
    switch (eventType) {
        case AUTHENTICATED:
            if (isCacheable(notification)) {
                if (httpSession == null) {
                    httpSession = sessionManager.createSession(exchange, sessionConfig);
                }

                // It is normal for this notification to be received when using a previously cached session - in that
                // case the IDM would have been given an opportunity to re-load the Account so updating here ready for
                // the next request is desired.
                httpSession.setAttribute(ATTRIBUTE_NAME,
                        new AuthenticatedSession(notification.getAccount(), notification.getMechanism()));
            }
            break;
        case LOGGED_OUT:
            if (httpSession != null) {
                httpSession.removeAttribute(ATTRIBUTE_NAME);
                httpSession.removeAttribute(NO_ID_CHANGE_REQUIRED);
            }
            break;
    }
}
 
Example 7
Source File: CachedAuthenticatedSessionHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void handleNotification(SecurityNotification notification) {
    EventType eventType = notification.getEventType();
    HttpServerExchange exchange = notification.getExchange();
    SessionManager sessionManager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
    SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
    if (sessionManager == null || sessionConfig == null) {
        return;
    }
    Session httpSession = sessionManager.getSession(exchange, sessionConfig);
    switch (eventType) {
        case AUTHENTICATED:
            if (isCacheable(notification)) {
                if (httpSession == null) {
                    httpSession = sessionManager.createSession(exchange, sessionConfig);
                }

                // It is normal for this notification to be received when using a previously cached session - in that
                // case the IDM would have been given an opportunity to re-load the Account so updating here ready for
                // the next request is desired.
                httpSession.setAttribute(ATTRIBUTE_NAME,
                        new AuthenticatedSession(notification.getAccount(), notification.getMechanism()));
            }
            break;
        case LOGGED_OUT:
            if (httpSession != null) {
                httpSession.removeAttribute(ATTRIBUTE_NAME);
                httpSession.removeAttribute(NO_ID_CHANGE_REQUIRED);
            }
            break;
    }
}
 
Example 8
Source File: ServletFormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sessionIdChanged(Session session, String oldSessionId) {
    String oldLocation = (String)session.getAttribute(SESSION_KEY);
    if(oldLocation != null) {
        //todo: in theory this could break if there are multiple path parameters
        //but this is such an edge case this is probably fine
        String oldPart = ";jsessionid=" + oldSessionId;
        if (oldLocation.contains(oldPart)) {
            session.setAttribute(ServletFormAuthenticationMechanism.SESSION_KEY, oldLocation.replace(oldPart, ";jsessionid=" + session.getId()));
        }
    }
}
 
Example 9
Source File: SavedRequest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange, final byte[] buffer, int length) {
    int maxSize = exchange.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
        HttpHeaders headers = new DefaultHttpHeaders();
        for (String entry : exchange.getRequestHeaderNames()) {
            if (entry.equals(HttpHeaderNames.CONTENT_LENGTH) ||
                    entry.equals(HttpHeaderNames.TRANSFER_ENCODING) ||
                    entry.equals(HttpHeaderNames.CONNECTION)) {
                continue;
            }
            headers.set(entry, exchange.getRequestHeaders(entry));
        }
        SavedRequest request = new SavedRequest(buffer, length, exchange.getRequestMethod(), exchange.getRelativePath(), headers);
        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 10
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 11
Source File: SsoHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Notifies authentication mechanism where it should redirect after log in. Based on
    * ServletFormAuthenticationMechanism method.
    */
   private static void handleRedirectBack(ServletRequestContext context, String redirectURL) {
/*
 * Prevent HTTP Response Splitting attack by sanitizing redirectURL.
 * The attack was possible by changing action of login form to, for example,
 * "j_security_check?redirectURL=%0d%0aAppScanHeader:%20AppScanValue%2f1%2e2%2d3%0d%0aSecondAppScanHeader:%20whatever"
 * Putting it in redirectURL form field or using another GET parameter ("something", "j_username") did not work.
 * The result was a split HTTP response with AppScanHeader and SecondAppScanHeader set, resultint in a security
 * threat.
 */
if (redirectURL.contains("\n") || redirectURL.contains("\r")) {
    throw new SecurityException(
	    "redirectURL contains forbidden characters: \\n or \\r. Possible HTTP Response Splitting attack.");
}

HttpSessionImpl httpSession = context.getCurrentServletContext().getSession(context.getExchange(), true);
if (httpSession != null) {
    Session session;
    if (System.getSecurityManager() == null) {
	session = httpSession.getSession();
    } else {
	session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
    }

    session.setAttribute(SsoHandler.REDIRECT_KEY, redirectURL);
}
   }
 
Example 12
Source File: UndertowSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
    Session session = Sessions.getOrCreateSession(exchange);
    session.setAttribute(KeycloakUndertowAccount.class.getName(), account);
    session.setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
    sessionManagement.login(session.getSessionManager());
}
 
Example 13
Source File: SavedRequest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void trySaveRequest(final HttpServerExchange exchange) {
    io.undertow.servlet.util.SavedRequest.trySaveRequest(exchange);
    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));
    }
    io.undertow.servlet.util.SavedRequest request = (io.undertow.servlet.util.SavedRequest) underlyingSession.removeAttribute(io.undertow.servlet.util.SavedRequest.class.getName());
    if (request != null) underlyingSession.setAttribute(SESSION_KEY, request);


}
 
Example 14
Source File: ServletFormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionIdChanged(Session session, String oldSessionId) {
    String oldLocation = (String)session.getAttribute(SESSION_KEY);
    if(oldLocation != null) {
        //todo: in theory this could break if there are multiple path parameters
        //but this is such an edge case this is probably fine
        String oldPart = ";jsessionid=" + oldSessionId;
        if (oldLocation.contains(oldPart)) {
            session.setAttribute(ServletFormAuthenticationMechanism.SESSION_KEY, oldLocation.replace(oldPart, ";jsessionid=" + session.getId()));
        }
    }
}
 
Example 15
Source File: FormAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
protected void storeInitialLocation(final HttpServerExchange exchange) {
    Session session = Sessions.getOrCreateSession(exchange);
    session.setAttribute(LOCATION_ATTRIBUTE, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
}
 
Example 16
Source File: FormAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void storeInitialLocation(final HttpServerExchange exchange) {
    Session session = Sessions.getOrCreateSession(exchange);
    session.setAttribute(LOCATION_ATTRIBUTE, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
}
 
Example 17
Source File: LightFormAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
protected void storeInitialLocation(final HttpServerExchange exchange) {
    Session session = Sessions.getOrCreateSession(exchange);
    session.setAttribute(LOCATION_ATTRIBUTE, RedirectBuilder.redirect(exchange, exchange.getRelativePath()));
}