use of io.undertow.server.session.Session in project undertow by undertow-io.
the class ServletContextImpl method getSession.
public HttpSessionImpl getSession(final ServletContextImpl originalServletContext, final HttpServerExchange exchange, boolean create) {
SessionConfig c = originalServletContext.getSessionConfig();
HttpSessionImpl httpSession = exchange.getAttachment(sessionAttachmentKey);
if (httpSession != null && httpSession.isInvalid()) {
exchange.removeAttachment(sessionAttachmentKey);
httpSession = null;
}
if (httpSession == null) {
final SessionManager sessionManager = deployment.getSessionManager();
Session session = sessionManager.getSession(exchange, c);
if (session != null) {
httpSession = SecurityActions.forSession(session, this, false);
exchange.putAttachment(sessionAttachmentKey, httpSession);
} else if (create) {
String existing = c.findSessionId(exchange);
Boolean isRequestedSessionIdSaved = exchange.getAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET);
if (isRequestedSessionIdSaved == null || !isRequestedSessionIdSaved) {
exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET, Boolean.TRUE);
exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID, existing);
}
if (originalServletContext != this) {
// this is a cross context request
// we need to make sure there is a top level session
final HttpSessionImpl topLevel = originalServletContext.getSession(originalServletContext, exchange, true);
// override the session id to just return the same ID as the top level session
c = new SessionConfig() {
@Override
public void setSessionId(HttpServerExchange exchange, String sessionId) {
// noop
}
@Override
public void clearSession(HttpServerExchange exchange, String sessionId) {
// noop
}
@Override
public String findSessionId(HttpServerExchange exchange) {
return topLevel.getId();
}
@Override
public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) {
return SessionCookieSource.NONE;
}
@Override
public String rewriteUrl(String originalUrl, String sessionId) {
return null;
}
};
// first we check if there is a session with this id already
// this can happen with a shared session manager
session = sessionManager.getSession(exchange, c);
if (session != null) {
httpSession = SecurityActions.forSession(session, this, false);
exchange.putAttachment(sessionAttachmentKey, httpSession);
}
} else if (existing != null) {
if (getDeploymentInfo().isCheckOtherSessionManagers()) {
boolean found = false;
for (String deploymentName : deployment.getServletContainer().listDeployments()) {
DeploymentManager deployment = this.deployment.getServletContainer().getDeployment(deploymentName);
if (deployment != null) {
if (deployment.getDeployment().getSessionManager().getSession(existing) != null) {
found = true;
break;
}
}
}
if (!found) {
c.clearSession(exchange, existing);
}
} else {
c.clearSession(exchange, existing);
}
}
if (httpSession == null) {
final Session newSession = sessionManager.createSession(exchange, c);
httpSession = SecurityActions.forSession(newSession, this, true);
exchange.putAttachment(sessionAttachmentKey, httpSession);
}
}
}
return httpSession;
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class SSLSessionTestCase method testSslSession.
@Test
public void testSslSession() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
InMemorySessionManager sessionManager = new InMemorySessionManager("");
final SslSessionConfig sessionConfig = new SslSessionConfig(sessionManager);
final SessionAttachmentHandler handler = new SessionAttachmentHandler(sessionManager, sessionConfig).setNext(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
Session session = manager.getSession(exchange, sessionConfig);
if (session == null) {
session = manager.createSession(exchange, sessionConfig);
session.setAttribute(COUNT, 0);
}
Integer count = (Integer) session.getAttribute(COUNT);
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
}
});
DefaultServer.startSSLServer();
client.setSSLContext(DefaultServer.getClientSSLContext());
DefaultServer.setRootHandler(handler);
HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
Header[] header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("1", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("2", header[0].getValue());
Assert.assertEquals(0, client.getCookieStore().getCookies().size());
} finally {
DefaultServer.stopSSLServer();
client.getConnectionManager().shutdown();
}
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class ServletFormAuthenticationMechanism method storeInitialLocation.
/**
* 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);
}
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class SessionListenerBridge method sessionDestroyed.
@Override
public void sessionDestroyed(final Session session, final HttpServerExchange exchange, final SessionDestroyedReason reason) {
if (reason == SessionDestroyedReason.TIMEOUT) {
try {
// we need to perform thread setup actions
destroyedAction.call(exchange, session);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
doDestroy(session);
}
ServletRequestContext current = SecurityActions.currentServletRequestContext();
Session underlying = null;
if (current != null && current.getSession() != null) {
if (System.getSecurityManager() == null) {
underlying = current.getSession().getSession();
} else {
underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(current.getSession()));
}
}
if (current != null && underlying == session) {
current.setSession(null);
}
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class JsrWebSocketFilter method doFilter.
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (req.getHeader(Headers.UPGRADE_STRING) != null) {
final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
String path;
if (req.getPathInfo() == null) {
path = req.getServletPath();
} else {
path = req.getServletPath() + req.getPathInfo();
}
if (!path.startsWith("/")) {
path = "/" + path;
}
PathTemplateMatcher.PathMatchResult<WebSocketHandshakeHolder> matchResult = pathTemplateMatcher.match(path);
if (matchResult != null) {
Handshake handshaker = null;
for (Handshake method : matchResult.getValue().handshakes) {
if (method.matches(facade)) {
handshaker = method;
break;
}
}
if (handshaker != null) {
if (container.isClosed()) {
resp.sendError(StatusCodes.SERVICE_UNAVAILABLE);
return;
}
facade.putAttachment(HandshakeUtil.PATH_PARAMS, matchResult.getParameters());
facade.putAttachment(HandshakeUtil.PRINCIPAL, req.getUserPrincipal());
final Handshake selected = handshaker;
ServletRequestContext src = ServletRequestContext.requireCurrent();
final HttpSessionImpl session = src.getCurrentServletContext().getSession(src.getExchange(), false);
facade.upgradeChannel(new HttpUpgradeListener() {
@Override
public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
peerConnections.add(channel);
if (session != null) {
final Session underlying;
if (System.getSecurityManager() == null) {
underlying = session.getSession();
} else {
underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
}
List<WebSocketChannel> connections;
synchronized (underlying) {
connections = (List<WebSocketChannel>) underlying.getAttribute(SESSION_ATTRIBUTE);
if (connections == null) {
underlying.setAttribute(SESSION_ATTRIBUTE, connections = new ArrayList<>());
}
connections.add(channel);
}
final List<WebSocketChannel> finalConnections = connections;
channel.addCloseTask(new ChannelListener<WebSocketChannel>() {
@Override
public void handleEvent(WebSocketChannel channel) {
synchronized (underlying) {
finalConnections.remove(channel);
}
}
});
}
callback.onConnect(facade, channel);
}
});
handshaker.handshake(facade);
return;
}
}
}
chain.doFilter(request, response);
}
Aggregations