use of jakarta.servlet.http.HttpSession in project spring-framework by spring-projects.
the class ServletRequestAttributesTests method doSkipImmutableValue.
private void doSkipImmutableValue(Object immutableValue) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpSession session = mock(HttpSession.class);
given(request.getSession(anyBoolean())).willReturn(session);
given(session.getAttribute(KEY)).willReturn(immutableValue);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
attrs.requestCompleted();
verify(session, times(2)).getAttribute(KEY);
verifyNoMoreInteractions(session);
}
use of jakarta.servlet.http.HttpSession in project tomcat by apache.
the class CsrfPreventionFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletResponse wResponse = null;
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
boolean skipNonceCheck = false;
if (Constants.METHOD_GET.equals(req.getMethod()) && entryPoints.contains(getRequestedPath(req))) {
if (log.isTraceEnabled()) {
log.trace("Skipping CSRF nonce-check for GET request to entry point " + getRequestedPath(req));
}
skipNonceCheck = true;
}
HttpSession session = req.getSession(false);
@SuppressWarnings("unchecked") LruCache<String> nonceCache = (session == null) ? null : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
if (!skipNonceCheck) {
String previousNonce = req.getParameter(nonceRequestParameterName);
if (previousNonce == null) {
if (log.isDebugEnabled()) {
log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " with no CSRF nonce found in request");
}
res.sendError(getDenyStatus());
return;
} else if (nonceCache == null) {
if (log.isDebugEnabled()) {
log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " due to empty / missing nonce cache");
}
res.sendError(getDenyStatus());
return;
} else if (!nonceCache.contains(previousNonce)) {
if (log.isDebugEnabled()) {
log.debug("Rejecting request for " + getRequestedPath(req) + ", session " + (null == session ? "(none)" : session.getId()) + " due to invalid nonce " + previousNonce);
}
res.sendError(getDenyStatus());
return;
}
if (log.isTraceEnabled()) {
log.trace("Allowing request to " + getRequestedPath(req) + " with valid CSRF nonce " + previousNonce);
}
}
if (nonceCache == null) {
if (log.isDebugEnabled()) {
log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " + (null == session ? "(will create)" : session.getId()));
}
nonceCache = new LruCache<>(nonceCacheSize);
if (session == null) {
if (log.isDebugEnabled()) {
log.debug("Creating new session to store CSRF nonce cache");
}
session = req.getSession(true);
}
session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache);
}
String newNonce = generateNonce();
nonceCache.add(newNonce);
// Take this request's nonce and put it into the request
// attributes so pages can make direct use of it, rather than
// requiring the use of response.encodeURL.
request.setAttribute(Constants.CSRF_NONCE_REQUEST_ATTR_NAME, newNonce);
wResponse = new CsrfResponseWrapper(res, nonceRequestParameterName, newNonce);
} else {
wResponse = response;
}
chain.doFilter(request, wResponse);
}
use of jakarta.servlet.http.HttpSession in project tomcat by apache.
the class SessionUtils method guessUserFromSession.
/**
* Try to get user from the session, if possible.
* @param in_session The session
* @return the user
*/
public static Object guessUserFromSession(final Session in_session) {
if (null == in_session) {
return null;
}
if (in_session.getPrincipal() != null) {
return in_session.getPrincipal().getName();
}
HttpSession httpSession = in_session.getSession();
if (httpSession == null) {
return null;
}
try {
Object user = null;
// First search "known locations"
for (String userTestAttribute : USER_TEST_ATTRIBUTES) {
Object obj = httpSession.getAttribute(userTestAttribute);
if (null != obj) {
user = obj;
break;
}
obj = httpSession.getAttribute(userTestAttribute.toLowerCase(Locale.ENGLISH));
if (null != obj) {
user = obj;
break;
}
obj = httpSession.getAttribute(userTestAttribute.toUpperCase(Locale.ENGLISH));
if (null != obj) {
user = obj;
break;
}
}
if (null != user) {
return user;
}
// Last guess: iterate over all attributes, to find a java.security.Principal or javax.security.auth.Subject
// If there is only one, consider it to be /the/ user
final List<Object> principalArray = new ArrayList<>();
for (Enumeration<String> enumeration = httpSession.getAttributeNames(); enumeration.hasMoreElements(); ) {
String name = enumeration.nextElement();
Object obj = httpSession.getAttribute(name);
if (obj instanceof Principal || obj instanceof Subject) {
principalArray.add(obj);
}
}
if (principalArray.size() == 1) {
user = principalArray.get(0);
}
if (null != user) {
return user;
}
return user;
} catch (IllegalStateException ise) {
// ignore: invalidated session
return null;
}
}
use of jakarta.servlet.http.HttpSession in project tomcat by apache.
the class ApplicationHttpRequest method getSession.
/**
* Return the session associated with this Request, creating one
* if necessary and requested.
*
* @param create Create a new session if one does not exist
*/
@Override
public HttpSession getSession(boolean create) {
if (crossContext) {
// There cannot be a session if no context has been assigned yet
if (context == null) {
return null;
}
// Return the current session if it exists and is valid
if (session != null && session.isValid()) {
return session.getSession();
}
HttpSession other = super.getSession(false);
if (create && (other == null)) {
// First create a session in the first context: the problem is
// that the top level request is the only one which can
// create the cookie safely
other = super.getSession(true);
}
if (other != null) {
Session localSession = null;
try {
localSession = context.getManager().findSession(other.getId());
if (localSession != null && !localSession.isValid()) {
localSession = null;
}
} catch (IOException e) {
// Ignore
}
if (localSession == null && create) {
localSession = context.getManager().createSession(other.getId());
}
if (localSession != null) {
localSession.access();
session = localSession;
return session.getSession();
}
}
return null;
} else {
return super.getSession(create);
}
}
use of jakarta.servlet.http.HttpSession in project tomcat by apache.
the class CGIServlet method printServletEnvironment.
/**
* Logs important Servlet API and container information.
*
* <p>
* Based on SnoopAllServlet by Craig R. McClanahan
* </p>
*
* @param req HttpServletRequest object used as source of information
*
* @exception IOException if a write operation exception occurs
*/
private void printServletEnvironment(HttpServletRequest req) throws IOException {
// Document the properties from ServletRequest
log.trace("ServletRequest Properties");
Enumeration<String> attrs = req.getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
log.trace("Request Attribute: " + attr + ": [ " + req.getAttribute(attr) + "]");
}
log.trace("Character Encoding: [" + req.getCharacterEncoding() + "]");
log.trace("Content Length: [" + req.getContentLengthLong() + "]");
log.trace("Content Type: [" + req.getContentType() + "]");
Enumeration<Locale> locales = req.getLocales();
while (locales.hasMoreElements()) {
Locale locale = locales.nextElement();
log.trace("Locale: [" + locale + "]");
}
Enumeration<String> params = req.getParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
for (String value : req.getParameterValues(param)) {
log.trace("Request Parameter: " + param + ": [" + value + "]");
}
}
log.trace("Protocol: [" + req.getProtocol() + "]");
log.trace("Remote Address: [" + req.getRemoteAddr() + "]");
log.trace("Remote Host: [" + req.getRemoteHost() + "]");
log.trace("Scheme: [" + req.getScheme() + "]");
log.trace("Secure: [" + req.isSecure() + "]");
log.trace("Server Name: [" + req.getServerName() + "]");
log.trace("Server Port: [" + req.getServerPort() + "]");
// Document the properties from HttpServletRequest
log.trace("HttpServletRequest Properties");
log.trace("Auth Type: [" + req.getAuthType() + "]");
log.trace("Context Path: [" + req.getContextPath() + "]");
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
log.trace("Cookie: " + cookie.getName() + ": [" + cookie.getValue() + "]");
}
}
Enumeration<String> headers = req.getHeaderNames();
while (headers.hasMoreElements()) {
String header = headers.nextElement();
log.trace("HTTP Header: " + header + ": [" + req.getHeader(header) + "]");
}
log.trace("Method: [" + req.getMethod() + "]");
log.trace("Path Info: [" + req.getPathInfo() + "]");
log.trace("Path Translated: [" + req.getPathTranslated() + "]");
log.trace("Query String: [" + req.getQueryString() + "]");
log.trace("Remote User: [" + req.getRemoteUser() + "]");
log.trace("Requested Session ID: [" + req.getRequestedSessionId() + "]");
log.trace("Requested Session ID From Cookie: [" + req.isRequestedSessionIdFromCookie() + "]");
log.trace("Requested Session ID From URL: [" + req.isRequestedSessionIdFromURL() + "]");
log.trace("Requested Session ID Valid: [" + req.isRequestedSessionIdValid() + "]");
log.trace("Request URI: [" + req.getRequestURI() + "]");
log.trace("Servlet Path: [" + req.getServletPath() + "]");
log.trace("User Principal: [" + req.getUserPrincipal() + "]");
// Process the current session (if there is one)
HttpSession session = req.getSession(false);
if (session != null) {
// Document the session properties
log.trace("HttpSession Properties");
log.trace("ID: [" + session.getId() + "]");
log.trace("Creation Time: [" + new Date(session.getCreationTime()) + "]");
log.trace("Last Accessed Time: [" + new Date(session.getLastAccessedTime()) + "]");
log.trace("Max Inactive Interval: [" + session.getMaxInactiveInterval() + "]");
// Document the session attributes
attrs = session.getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
log.trace("Session Attribute: " + attr + ": [" + session.getAttribute(attr) + "]");
}
}
// Document the servlet configuration properties
log.trace("ServletConfig Properties");
log.trace("Servlet Name: [" + getServletConfig().getServletName() + "]");
// Document the servlet configuration initialization parameters
params = getServletConfig().getInitParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
String value = getServletConfig().getInitParameter(param);
log.trace("Servlet Init Param: " + param + ": [" + value + "]");
}
// Document the servlet context properties
log.trace("ServletContext Properties");
log.trace("Major Version: [" + getServletContext().getMajorVersion() + "]");
log.trace("Minor Version: [" + getServletContext().getMinorVersion() + "]");
log.trace("Real Path for '/': [" + getServletContext().getRealPath("/") + "]");
log.trace("Server Info: [" + getServletContext().getServerInfo() + "]");
// Document the servlet context initialization parameters
log.trace("ServletContext Initialization Parameters");
params = getServletContext().getInitParameterNames();
while (params.hasMoreElements()) {
String param = params.nextElement();
String value = getServletContext().getInitParameter(param);
log.trace("Servlet Context Init Param: " + param + ": [" + value + "]");
}
// Document the servlet context attributes
log.trace("ServletContext Attributes");
attrs = getServletContext().getAttributeNames();
while (attrs.hasMoreElements()) {
String attr = attrs.nextElement();
log.trace("Servlet Context Attribute: " + attr + ": [" + getServletContext().getAttribute(attr) + "]");
}
}
Aggregations