下面列出了怎么用javax.servlet.SessionCookieConfig的API类实例代码及写法,或者点击链接到github查看源代码。
private static String getConfiguredSessionCookieName(Context context) {
// Priority is:
// 1. Cookie name defined in context
// 2. Cookie name configured for app
// 3. Default defined by spec
if (context != null) {
String cookieName = context.getSessionCookieName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
cookieName = scc.getName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
}
return null;
}
private static String getConfiguredSessionCookieName(Context context) {
// Priority is:
// 1. Cookie name defined in context
// 2. Cookie name configured for app
// 3. Default defined by spec
if (context != null) {
String cookieName = context.getSessionCookieName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
cookieName = scc.getName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
}
return null;
}
private static String getConfiguredSessionCookieName(Context context) {
// Priority is:
// 1. Cookie name defined in context
// 2. Cookie name configured for app
// 3. Default defined by spec
if (context != null) {
String cookieName = context.getSessionCookieName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
cookieName = scc.getName();
if (cookieName != null && cookieName.length() > 0) {
return cookieName;
}
}
return null;
}
private WebAppContext createWebAppContext( Topology topology, File warFile, String warPath ) {
String topoName = topology.getName();
WebAppContext context = new WebAppContext();
String contextPath;
contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName, warPath );
context.setContextPath( contextPath );
SessionCookieConfig sessionCookieConfig = context.getServletContext().getSessionCookieConfig();
sessionCookieConfig.setName(KNOXSESSIONCOOKIENAME);
context.setWar( warFile.getAbsolutePath() );
context.setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName );
context.setAttribute( "org.apache.knox.gateway.frontend.uri", getFrontendUri( context, config ) );
context.setAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config );
// Add support for JSPs.
context.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
context.setTempDirectory( FileUtils.getFile( warFile, "META-INF", "temp" ) );
context.setErrorHandler( createErrorHandler() );
context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
ClassLoader jspClassLoader = new URLClassLoader(new URL[0], this.getClass().getClassLoader());
context.setClassLoader(jspClassLoader);
return context;
}
@Test
public void shouldSetSessionCookieConfig() throws Exception {
when(systemEnvironment.isSessionCookieSecure()).thenReturn(true);
jetty9Server.configure();
jetty9Server.setSessionConfig();
jetty9Server.startHandlers();
WebAppContext webAppContext = (WebAppContext) getLoadedHandlers().get(WebAppContext.class);
SessionCookieConfig sessionCookieConfig = webAppContext.getSessionHandler().getSessionCookieConfig();
assertThat(sessionCookieConfig.isHttpOnly(), is(true));
assertThat(sessionCookieConfig.isSecure(), is(true));
assertThat(sessionCookieConfig.getMaxAge(), is(5678));
when(systemEnvironment.isSessionCookieSecure()).thenReturn(false);
jetty9Server.setSessionConfig();
assertThat(sessionCookieConfig.isSecure(), is(false));
}
/**
* Determine the value to use for the session cookie path for the provided
* context.
*
* @param context The context
* @return the parameter name for the session
*/
public static String getSessionCookiePath(Context context) {
SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
String contextPath = context.getSessionCookiePath();
if (contextPath == null || contextPath.length() == 0) {
contextPath = scc.getPath();
}
if (contextPath == null || contextPath.length() == 0) {
contextPath = context.getEncodedPath();
}
if (context.getSessionCookiePathUsesTrailingSlash()) {
// Handle special case of ROOT context where cookies require a path of
// '/' but the servlet spec uses an empty string
// Also ensure the cookies for a context with a path of /foo don't get
// sent for requests with a path of /foobar
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
} else {
// Only handle special case of ROOT context where cookies require a
// path of '/' but the servlet spec uses an empty string
if (contextPath.length() == 0) {
contextPath = "/";
}
}
return contextPath;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
if (SecurityUtil.isPackageProtectionEnabled()) {
return (SessionCookieConfig)
doPrivileged("getSessionCookieConfig", null);
} else {
return context.getSessionCookieConfig();
}
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
if (SecurityUtil.isPackageProtectionEnabled()) {
return (SessionCookieConfig)
doPrivileged("getSessionCookieConfig", null);
} else {
return context.getSessionCookieConfig();
}
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
if (SecurityUtil.isPackageProtectionEnabled()) {
return (SessionCookieConfig)
doPrivileged("getSessionCookieConfig", null);
} else {
return context.getSessionCookieConfig();
}
}
@SuppressWarnings("deprecation")
@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
}
};
}
private CookieSerializer createDefaultCookieSerializer() {
DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
if (this.servletContext != null) {
SessionCookieConfig sessionCookieConfig = null;
try {
sessionCookieConfig = this.servletContext.getSessionCookieConfig();
}
catch (UnsupportedOperationException ex) {
this.logger.warn("Unable to obtain SessionCookieConfig: " + ex.getMessage());
}
if (sessionCookieConfig != null) {
if (sessionCookieConfig.getName() != null) {
cookieSerializer.setCookieName(sessionCookieConfig.getName());
}
if (sessionCookieConfig.getDomain() != null) {
cookieSerializer.setDomainName(sessionCookieConfig.getDomain());
}
if (sessionCookieConfig.getPath() != null) {
cookieSerializer.setCookiePath(sessionCookieConfig.getPath());
}
if (sessionCookieConfig.getMaxAge() != -1) {
cookieSerializer.setCookieMaxAge(sessionCookieConfig.getMaxAge());
}
}
}
if (this.usesSpringSessionRememberMeServices) {
cookieSerializer.setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR);
}
return cookieSerializer;
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext);
ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class);
SessionCookieConfig config = servletContext.getSessionCookieConfig();
config.setHttpOnly(true);
config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
// force log initialization, then disable it
XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
XRLog.setLoggingEnabled(false);
};
}
private void configureSessionCookie(ServletContext servletContext) {
SessionCookieConfig config = servletContext.getSessionCookieConfig();
config.setHttpOnly(true);
Validate.notNull(environment, "environment cannot be null!");
// set secure cookie only if current environment doesn't strictly need HTTP
config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
// https://issues.jboss.org/browse/WFLY-3448 ?
config.setPath(servletContext.getContextPath() + "/");
}
private void copyConfig(WebConfig.SessionsConfig.CookieConfig src, SessionCookieConfig dest) {
Optional.ofNullable(src.getComment()).ifPresent(dest::setComment);
Optional.ofNullable(src.getDomain()).ifPresent(dest::setDomain);
Optional.ofNullable(src.getName()).ifPresent(dest::setName);
Optional.ofNullable(src.getPath()).ifPresent(dest::setPath);
dest.setHttpOnly(src.isHttpOnly());
dest.setSecure(src.isSecure());
dest.setMaxAge(src.getMaxAge());
}
private static void addSessionCookieConfigMessages(Map<String, Object> messages, SessionCookieConfig sessionCookieConfig) {
if(sessionCookieConfig==null) {
return;
}
StringBuilder builder=new StringBuilder();
builder.append(NEW_LINE).append(VALUE_PREFIX).append("Name").append(VALUE_SEPARATOR).append(sessionCookieConfig.getName());
builder.append(NEW_LINE).append(VALUE_PREFIX).append("Comment").append(VALUE_SEPARATOR).append(sessionCookieConfig.getComment());
builder.append(NEW_LINE).append(VALUE_PREFIX).append("Domain").append(VALUE_SEPARATOR).append(sessionCookieConfig.getDomain());
builder.append(NEW_LINE).append(VALUE_PREFIX).append("Path").append(VALUE_SEPARATOR).append(sessionCookieConfig.getPath());
builder.append(NEW_LINE).append(VALUE_PREFIX).append("Max age").append(VALUE_SEPARATOR).append(sessionCookieConfig.getMaxAge());
addMessage(messages,"Session cookie config",builder.toString());
}
@Override
public void setSessionConfig() {
SessionHandler sessionHandler = webAppContext.getSessionHandler();
SessionCookieConfig sessionCookieConfig = sessionHandler.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setSecure(systemEnvironment.isSessionCookieSecure());
sessionCookieConfig.setMaxAge(systemEnvironment.sessionCookieMaxAgeInSeconds());
sessionHandler.setMaxInactiveInterval(systemEnvironment.sessionTimeoutInSeconds());
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return sessionCookieConfig;
}
/**
* Creates a new session cookie for the given session ID
*
* @param context The Context for the web application
* @param sessionId The ID of the session for which the cookie will be
* created
* @param secure Should session cookie be configured as secure
* @return the cookie for the session
*/
public static Cookie createSessionCookie(Context context,
String sessionId, boolean secure) {
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
// NOTE: The priority order for session cookie configuration is:
// 1. Context level configuration
// 2. Values from SessionCookieConfig
// 3. Defaults
Cookie cookie = new Cookie(
SessionConfig.getSessionCookieName(context), sessionId);
// Just apply the defaults.
cookie.setMaxAge(scc.getMaxAge());
cookie.setComment(scc.getComment());
if (context.getSessionCookieDomain() == null) {
// Avoid possible NPE
if (scc.getDomain() != null) {
cookie.setDomain(scc.getDomain());
}
} else {
cookie.setDomain(context.getSessionCookieDomain());
}
// Always set secure if the request is secure
if (scc.isSecure() || secure) {
cookie.setSecure(true);
}
// Always set httpOnly if the context is configured for that
if (scc.isHttpOnly() || context.getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
cookie.setPath(SessionConfig.getSessionCookiePath(context));
return cookie;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return null;
}
private void runValve(String jkActivation,
boolean validSessionId,
boolean expectInvokeNext,
boolean enableIgnore,
String queryString) throws Exception {
IMocksControl control = EasyMock.createControl();
ServletContext servletContext = control.createMock(ServletContext.class);
Context ctx = control.createMock(Context.class);
Request request = control.createMock(Request.class);
Response response = control.createMock(Response.class);
String sessionCookieName = "JSESSIONID";
String sessionId = "cafebabe";
String requestURI = "/test/path";
SessionCookieConfig cookieConfig = new CookieConfig();
cookieConfig.setDomain("example.com");
cookieConfig.setName(sessionCookieName);
cookieConfig.setPath("/");
// Valve.init requires all of this stuff
EasyMock.expect(ctx.getMBeanKeyProperties()).andStubReturn("");
EasyMock.expect(ctx.getName()).andStubReturn("");
EasyMock.expect(ctx.getPipeline()).andStubReturn(new StandardPipeline());
EasyMock.expect(ctx.getDomain()).andStubReturn("foo");
EasyMock.expect(ctx.getLogger()).andStubReturn(org.apache.juli.logging.LogFactory.getLog(LoadBalancerDrainingValve.class));
EasyMock.expect(ctx.getServletContext()).andStubReturn(servletContext);
// Set up the actual test
EasyMock.expect(request.getAttribute(LoadBalancerDrainingValve.ATTRIBUTE_KEY_JK_LB_ACTIVATION)).andStubReturn(jkActivation);
EasyMock.expect(Boolean.valueOf(request.isRequestedSessionIdValid())).andStubReturn(Boolean.valueOf(validSessionId));
ArrayList<Cookie> cookies = new ArrayList<>();
if(enableIgnore) {
cookies.add(new Cookie("ignore", "true"));
}
if(!validSessionId) {
MyCookie cookie = new MyCookie(cookieConfig.getName(), sessionId);
cookie.setPath(cookieConfig.getPath());
cookie.setValue(sessionId);
cookies.add(cookie);
EasyMock.expect(request.getRequestedSessionId()).andStubReturn(sessionId);
EasyMock.expect(request.getRequestURI()).andStubReturn(requestURI);
EasyMock.expect(request.getCookies()).andStubReturn(cookies.toArray(new Cookie[cookies.size()]));
EasyMock.expect(request.getContext()).andStubReturn(ctx);
EasyMock.expect(ctx.getSessionCookieName()).andStubReturn(sessionCookieName);
EasyMock.expect(servletContext.getSessionCookieConfig()).andStubReturn(cookieConfig);
EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
EasyMock.expect(ctx.getSessionCookiePath()).andStubReturn("/");
if (!enableIgnore) {
EasyMock.expect(Boolean.valueOf(ctx.getSessionCookiePathUsesTrailingSlash())).andStubReturn(Boolean.TRUE);
EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
// Response will have cookie deleted
MyCookie expectedCookie = new MyCookie(cookieConfig.getName(), "");
expectedCookie.setPath(cookieConfig.getPath());
expectedCookie.setMaxAge(0);
// These two lines just mean EasyMock.expect(response.addCookie) but for a void method
response.addCookie(expectedCookie);
EasyMock.expect(ctx.getSessionCookieName()).andReturn(sessionCookieName); // Indirect call
String expectedRequestURI = requestURI;
if(null != queryString)
expectedRequestURI = expectedRequestURI + '?' + queryString;
response.setHeader("Location", expectedRequestURI);
response.setStatus(307);
}
}
Valve next = control.createMock(Valve.class);
if(expectInvokeNext) {
// Expect the "next" Valve to fire
// Next 2 lines are basically EasyMock.expect(next.invoke(req,res)) but for a void method
next.invoke(request, response);
EasyMock.expectLastCall();
}
// Get set to actually test
control.replay();
LoadBalancerDrainingValve valve = new LoadBalancerDrainingValve();
valve.setContainer(ctx);
valve.init();
valve.setNext(next);
valve.setIgnoreCookieName("ignore");
valve.setIgnoreCookieValue("true");
valve.invoke(request, response);
control.verify();
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return sessionCookieConfig;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return this.sessionCookieConfig;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return this.sessionCookieConfig;
}
public SessionCookieConfigImpl(final ServletContextImpl servletContext) {
this.servletContext = servletContext;
this.delegate = new io.undertow.server.session.SessionCookieConfig();
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return this.sessionCookieConfig;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return this.sessionCookieConfig;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return null;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return null;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return null;
}
public SessionCookieConfig getSessionCookieConfig() {
return null;
}