下面列出了javax.servlet.http.Cookie#setSecure() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void multipleCookies() {
Cookie safeSecureCookie = new Cookie("cookie 3", "foo");
safeSecureCookie.setSecure(true);
// The line bellow should stay line 72 - It is used with the .atLine() annotation in the test
Cookie unsafeSecureCookie = new Cookie("cookie 4", "bar");
unsafeSecureCookie.setSecure(false);
// The line bellow should stay line 76 - It is used with the .atLine() annotation in the test
Cookie unsafeCookie = new Cookie("cookie 3", "foo");
Cookie mixedCookiesSafe = new Cookie("cookie 4", "bar");
// The line bellow should stay line 76 - It is used with the .atLine() annotation in the test
Cookie mixedCookies = new Cookie("cookie 5", "bar");
mixedCookiesSafe.setSecure(true);
// The line bellow should stay line 84 - It is used with the .atLine() annotation in the test
Cookie unsafeCookie2 = new Cookie("c1", "foo");
unsafeCookie2.setSecure(false);
Cookie safeCookie2 = new Cookie("c2", "bar");
safeCookie2.setSecure(true);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
Cookie[] allCookies = req.getCookies();
if (allCookies != null) {
Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null);
if (session != null) {
session.setHttpOnly(true);
session.setSecure(true);
res.addCookie(session);
}
}
chain.doFilter(req, res);
}
/**
* Remove the cookie that this generator describes from the response.
* Will generate a cookie with empty value and max age 0.
* <p>Delegates to {@link #createCookie} for cookie creation.
* @param response the HTTP response to remove the cookie from
* @see #setCookieName
* @see #setCookieDomain
* @see #setCookiePath
*/
public void removeCookie(HttpServletResponse response) {
Assert.notNull(response, "HttpServletResponse must not be null");
Cookie cookie = createCookie("");
cookie.setMaxAge(0);
if (isCookieSecure()) {
cookie.setSecure(true);
}
if (isCookieHttpOnly()) {
cookie.setHttpOnly(true);
}
response.addCookie(cookie);
if (logger.isDebugEnabled()) {
logger.debug("Removed cookie with name [" + getCookieName() + "]");
}
}
/**
* Creates a new pxt cookie with the specified session id and timeout.
*
* @param pxtSessionId The id of the pxt session for which the cookie is being created.
*
* @param request The current request.
*
* @param timeout The max age of the cookie in seconds.
*
* @return a new pxt cookie.
*/
public Cookie createPxtCookie(Long pxtSessionId, HttpServletRequest request,
int timeout) {
String cookieName = PXT_SESSION_COOKIE_NAME;
String cookieValue = pxtSessionId + "x" +
SessionManager.generateSessionKey(pxtSessionId.toString());
Cookie pxtCookie = new Cookie(cookieName, cookieValue);
// BZ #454876
// when not using setDomain, default "Host" will be set for the cookie
// there's no need to use domain and besides that it causes trouble,
// when accessing the server within the local network (without FQDN)
// pxtCookie.setDomain(request.getServerName());
if (!userAgentContains(request, "msie")) {
pxtCookie.setMaxAge(timeout);
}
pxtCookie.setPath(DEFAULT_PATH);
pxtCookie.setSecure(ConfigDefaults.get().isSSLAvailable());
return pxtCookie;
}
/**
* Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and renames cookie to avoid
* collisions.
*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) {
List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
String path = getServletContext().getServletContextName();
if (path == null) {
path = "";
}
path += servletRequest.getServletPath();
for (HttpCookie cookie : cookies) {
// set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
String proxyCookieName = getCookieNamePrefix() + cookie.getName();
Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
servletCookie.setComment(cookie.getComment());
servletCookie.setMaxAge((int) cookie.getMaxAge());
servletCookie.setPath(path); // set to the path of the proxy servlet
// don't set cookie domain
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
servletResponse.addCookie(servletCookie);
}
}
public static Cookie convert(org.jboss.netty.handler.codec.http.Cookie nettyCookie){
Cookie servletCookie = new Cookie(nettyCookie.getName(),nettyCookie.getValue());
servletCookie.setDomain(nettyCookie.getDomain());
servletCookie.setMaxAge(nettyCookie.getMaxAge());
servletCookie.setHttpOnly(nettyCookie.isHttpOnly());
servletCookie.setPath(nettyCookie.getPath());
servletCookie.setSecure(nettyCookie.isSecure());
servletCookie.setVersion(nettyCookie.getVersion());
servletCookie.setComment(nettyCookie.getComment());
return servletCookie;
}
protected Cookie createSessionCookie(HttpServletRequest request, String data) {
Cookie cookie = new Cookie(settings.getCookieName(), data);
// cookie.setHttpOnly(true);
cookie.setSecure(request.isSecure());
cookie.setMaxAge(settings.getMaxAge());
// cookie.setPath(request.getContextPath() + "/");
cookie.setPath(settings.getPath());
if (settings.getDomain() != null) {
cookie.setDomain(settings.getDomain());
}
return cookie;
}
/**
* <p>
* 根据SSOToken生成登录信息Cookie
* </p>
*
* @param request
* @param token SSO 登录信息票据
* @return Cookie 登录信息Cookie {@link Cookie}
*/
protected Cookie generateCookie(HttpServletRequest request, Token token) {
try {
Cookie cookie = new Cookie(config.getCookieName(), token.getToken());
cookie.setPath(config.getCookiePath());
cookie.setSecure(config.isCookieSecure());
/**
* domain 提示
* <p>
* 有些浏览器 localhost 无法设置 cookie
* </p>
*/
String domain = config.getCookieDomain();
if (null != domain) {
cookie.setDomain(domain);
if ("".equals(domain) || domain.contains("localhost")) {
log.warn("if you can't login, please enter normal domain. instead:" + domain);
}
}
/**
* 设置Cookie超时时间
*/
int maxAge = config.getCookieMaxAge();
Integer attrMaxAge = (Integer) request.getAttribute(SSOConstants.SSO_COOKIE_MAXAGE);
if (attrMaxAge != null) {
maxAge = attrMaxAge;
}
if (maxAge >= 0) {
cookie.setMaxAge(maxAge);
}
return cookie;
} catch (Exception e) {
throw new KissoException("Generate sso cookie exception ", e);
}
}
/**
* Sets a cookie.
* @param name the name
* @param value the value
* @param req HTTP request
* @param res HTTP response
* @param httpOnly HTTP only flag
* @param maxAge max age
*/
public static void setRawCookie(String name, String value, HttpServletRequest req,
HttpServletResponse res, boolean httpOnly, int maxAge) {
if (StringUtils.isBlank(name) || value == null || req == null || res == null) {
return;
}
Cookie cookie = new Cookie(name, value);
cookie.setHttpOnly(httpOnly);
cookie.setMaxAge(maxAge < 0 ? Config.SESSION_TIMEOUT_SEC : maxAge);
cookie.setPath(CONTEXT_PATH.isEmpty() ? "/" : CONTEXT_PATH);
cookie.setSecure(req.isSecure());
res.addCookie(cookie);
}
@RequestMapping("/activation")
public ModelAndView activation(@RequestParam("key") String key, HttpServletResponse response) {
boolean success = accountService.activate(key);
if (success) {
//see AccountSession.dart#detectForceLogout();
Cookie cookie = new Cookie("force-logout", "true");
cookie.setPath("/");
cookie.setSecure(true);
response.addCookie(cookie);
}
return new ModelAndView("account/activation").addObject("success", success);
}
public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(secure);
cookie.setHttpOnly(true);
cookie.setMaxAge(maxAge);
cookie.setDomain(domain);
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
}
private AuthenticationStatus validateRequest(final InvocationContext invocationContext) throws Exception {
final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];
final RememberMe rememberMe = getRememberMe();
final Optional<Cookie> cookie = getCookie(httpMessageContext.getRequest(), rememberMe.cookieName());
if (cookie.isPresent()) {
final RememberMeCredential rememberMeCredential = new RememberMeCredential(cookie.get().getValue());
final CredentialValidationResult validate = rememberMeIdentityStore.get().validate(rememberMeCredential);
if (VALID.equals(validate.getStatus())) {
return httpMessageContext.notifyContainerAboutLogin(validate);
} else {
cookie.get().setMaxAge(0);
httpMessageContext.getResponse().addCookie(cookie.get());
}
}
final AuthenticationStatus status = (AuthenticationStatus) invocationContext.proceed();
if (SUCCESS.equals(status) && rememberMe.isRememberMe()) {
final CallerPrincipal principal = new CallerPrincipal(httpMessageContext.getCallerPrincipal().getName());
final Set<String> groups = httpMessageContext.getGroups();
final String loginToken = rememberMeIdentityStore.get().generateLoginToken(principal, groups);
final Cookie rememberMeCookie = new Cookie(rememberMe.cookieName(), loginToken);
rememberMeCookie.setMaxAge(rememberMe.cookieMaxAgeSeconds());
rememberMeCookie.setHttpOnly(rememberMe.cookieHttpOnly());
rememberMeCookie.setSecure(rememberMe.cookieSecureOnly());
httpMessageContext.getResponse().addCookie(rememberMeCookie);
}
return status;
}
@Test
public void cookies() {
Cookie cookie = new Cookie("foo", "bar");
cookie.setPath("/path");
cookie.setDomain("example.com");
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
response.addCookie(cookie);
assertEquals("foo=bar; Path=/path; Domain=example.com; " +
"Max-Age=0; Expires=Thu, 1 Jan 1970 00:00:00 GMT; " +
"Secure; HttpOnly", response.getHeader(HttpHeaders.SET_COOKIE));
}
public static Cookie setCookie(HttpServletRequest request, HttpServletResponse response, String name,
String value, int maxAge, String path) {
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge);
cookie.setPath(path);
cookie.setSecure(request.isSecure());
response.addCookie(cookie);
return cookie;
}
private void configCookie(HttpServletRequest request, Cookie sessionCookie){
sessionCookie.setSecure(request.isSecure());
String cookiePath = cookiePath(request);
sessionCookie.setPath(cookiePath);
String domain = cookieDomain(request);
if(StringUtils.isNotBlank(domain)){
sessionCookie.setDomain(domain);
}
}
public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(secure);
cookie.setHttpOnly(true);
cookie.setMaxAge(maxAge);
cookie.setDomain(domain);
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
}
void safeCookie3() {
boolean safe = true;
Cookie cookie = new Cookie("test1","1234");
cookie.setSecure(safe);
}
/**
* Perform single-sign-on support processing for this request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
request.removeNote(Constants.REQ_SSOID_NOTE);
// Has a valid user already been authenticated?
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.invoke", request.getRequestURI()));
}
if (request.getUserPrincipal() != null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.hasPrincipal",
request.getUserPrincipal().getName()));
}
getNext().invoke(request, response);
return;
}
// Check for the single sign on cookie
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.cookieCheck"));
}
Cookie cookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
cookie = cookies[i];
break;
}
}
}
if (cookie == null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.cookieNotFound"));
}
getNext().invoke(request, response);
return;
}
// Look up the cached Principal associated with this cookie value
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.principalCheck",
cookie.getValue()));
}
SingleSignOnEntry entry = cache.get(cookie.getValue());
if (entry != null) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.principalFound",
entry.getPrincipal() != null ? entry.getPrincipal().getName() : "",
entry.getAuthType()));
}
request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
// Only set security elements if reauthentication is not required
if (!getRequireReauthentication()) {
request.setAuthType(entry.getAuthType());
request.setUserPrincipal(entry.getPrincipal());
}
} else {
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.principalNotFound",
cookie.getValue()));
}
// No need to return a valid SSO session ID
cookie.setValue("REMOVE");
// Age of zero will trigger removal
cookie.setMaxAge(0);
// Domain and path have to match the original cookie to 'replace'
// the original cookie
cookie.setPath("/");
String domain = getCookieDomain();
if (domain != null) {
cookie.setDomain(domain);
}
// This is going to trigger a Set-Cookie header. While the value is
// not security sensitive, ensure that expectations for secure and
// httpOnly are met
cookie.setSecure(request.isSecure());
if (request.getServletContext().getSessionCookieConfig().isHttpOnly() ||
request.getContext().getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
response.addCookie(cookie);
}
// Invoke the next Valve in our pipeline
getNext().invoke(request, response);
}
/**
* 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
*/
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);
}
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 = "/";
}
}
cookie.setPath(contextPath);
return cookie;
}
private void executeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletConfig config = getServletConfig();
int servletMajorVersion = config.getServletContext().getMajorVersion();
int httpOnlyMinServletVersion = 3;
String secureString = "Secure";
String httpOnlyString = "HttpOnly";
String cookiePath = "/";
int cookieMaxAge = 86400; // 24 hours
Cookie testCookieDefault1 = new Cookie("TestCookieName1", "TestCookieValue1");
Cookie testCookieDefault2 = new Cookie("TestCookieName2", "TestCookieValue2");
Cookie testCookieSecure1 = new Cookie("TestCookieNameSecure1", "TestCookieValueSecure1");
Cookie testCookieSecure2 = new Cookie("TestCookieNameSecure2", "TestCookieValueSecure2");
Cookie testCookieHttpOnly1 = new Cookie("TestCookieNameHttpOnly1", "TestCookieValueHttpOnly1");
Cookie testCookieHttpOnly2 = new Cookie("TestCookieNameHttpOnly2", "TestCookieValueHttpOnly2");
Cookie testCookieSecureHttpOnly1 = new Cookie("TestCookieNameSecureHttpOnly1", "TestCookieValueSecureHttpOnly1");
Cookie testCookieSecureHttpOnly2 = new Cookie("TestCookieNameSecureHttpOnly2", "TestCookieValueSecureHttpOnly2");
Cookie[] cookies = {testCookieDefault1, testCookieDefault2, testCookieSecure1, testCookieSecure2,
testCookieHttpOnly1, testCookieHttpOnly2, testCookieSecureHttpOnly1,
testCookieSecureHttpOnly2};
for (int i = 0; i < cookies.length; i++) {
Cookie newCookie = cookies[i];
newCookie.setPath(cookiePath);
newCookie.setMaxAge(cookieMaxAge);
if(newCookie.getName().contains(secureString)){
newCookie.setSecure(true);
}
if(newCookie.getName().contains(httpOnlyString)){
if(servletMajorVersion >= httpOnlyMinServletVersion){
newCookie.setHttpOnly(true);
}
}
response.addCookie(newCookie);
}
}