001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *      http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.apache.shiro.ee.filters;
015
016import static org.apache.shiro.ee.cdi.ShiroScopeContext.isWebContainerSessions;
017import static org.apache.shiro.ee.filters.FormResubmitSupport.getNativeSessionManager;
018import java.net.HttpCookie;
019import java.time.Duration;
020import java.util.List;
021import java.util.Map;
022import java.util.stream.Collectors;
023import java.util.stream.Stream;
024import javax.servlet.ServletContext;
025import javax.servlet.ServletRequest;
026import javax.servlet.http.Cookie;
027import javax.servlet.http.HttpServletResponse;
028import lombok.AccessLevel;
029import lombok.NoArgsConstructor;
030import lombok.NonNull;
031import lombok.extern.slf4j.Slf4j;
032import org.apache.shiro.ee.listeners.EnvironmentLoaderListener;
033import static org.apache.shiro.web.servlet.ShiroHttpSession.DEFAULT_SESSION_ID_NAME;
034
035/**
036 * Cookie Support methods
037 */
038@Slf4j
039@NoArgsConstructor(access = AccessLevel.PRIVATE)
040@SuppressWarnings("HideUtilityClassConstructor")
041public class FormResubmitSupportCookies {
042    static final String DONT_ADD_ANY_MORE_COOKIES = "org.apache.shiro.no-more-cookies";
043
044    static void addCookie(@NonNull HttpServletResponse response, ServletContext servletContext,
045            @NonNull String cookieName, @NonNull String cookieValue, int maxAge) {
046        var cookie = new Cookie(cookieName, cookieValue);
047        cookie.setPath(servletContext.getContextPath());
048        cookie.setMaxAge(maxAge);
049        if (EnvironmentLoaderListener.isFormResubmitSecureCookies(servletContext)) {
050            cookie.setSecure(true);
051        }
052        response.addCookie(cookie);
053    }
054
055    static void deleteCookie(@NonNull HttpServletResponse response, ServletContext servletContext,
056            @NonNull String cookieName) {
057        var cookieToDelete = new Cookie(cookieName, "tbd");
058        cookieToDelete.setPath(servletContext.getContextPath());
059        cookieToDelete.setMaxAge(0);
060        if (EnvironmentLoaderListener.isFormResubmitSecureCookies(servletContext)) {
061            cookieToDelete.setSecure(true);
062        }
063        response.addCookie(cookieToDelete);
064    }
065
066    static int getCookieAge(ServletRequest request, org.apache.shiro.mgt.SecurityManager securityManager) {
067        var nativeSessionManager = getNativeSessionManager(securityManager);
068        if (nativeSessionManager != null) {
069            return (int) Duration.ofMillis(nativeSessionManager.getGlobalSessionTimeout()).toSeconds();
070        } else {
071            try {
072                return (int) Duration.ofMinutes(request.getServletContext().getSessionTimeout()).toSeconds();
073            } catch (NoSuchMethodError noSuchMethodError) {
074                // Older servers (e.g. Jetty 9.x) do not support getSessionTimeout() at all
075                log.debug("ServletContext.getSessionTimeout() not supported", noSuchMethodError);
076                return (int) Duration.ofHours(1).toSeconds();
077            }
078        }
079    }
080
081    static String getSessionCookieName(ServletContext context, org.apache.shiro.mgt.SecurityManager securityManager) {
082        if (!isWebContainerSessions(securityManager) && getNativeSessionManager(securityManager) != null) {
083            return getNativeSessionManager(securityManager).getSessionIdCookie().getName();
084        } else {
085            return context.getSessionCookieConfig().getName() != null
086                    ? context.getSessionCookieConfig().getName() : DEFAULT_SESSION_ID_NAME;
087        }
088    }
089
090    static Map<String, String> transformCookieHeader(@NonNull List<String> cookies) {
091        return cookieStreamFromHeader(cookies)
092                .collect(Collectors.toMap(HttpCookie::getName, HttpCookie::getValue));
093    }
094
095    static Stream<HttpCookie> cookieStreamFromHeader(@NonNull List<String> cookies) {
096        return cookies.stream().map(HttpCookie::parse).map(list -> list.get(0));
097    }
098}