下面列出了javax.servlet.http.Cookie#setPath() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Spring put the CSRF token in session attribute "_csrf"
CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");
// Send the cookie only if the token has changed
String actualToken = request.getHeader("X-CSRF-TOKEN");
if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
// Session cookie that will be used by AngularJS
String pCookieName = "CSRF-TOKEN";
Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
cookie.setMaxAge(-1);
cookie.setHttpOnly(false);
cookie.setPath("/");
response.addCookie(cookie);
}
filterChain.doFilter(request, response);
}
@BeforeTest
public void onInit() throws InterruptedException, IOException {
ApplicationConfigCache.loadConfigCache();
Map<String, String> cookiesMap = null;
try {
httpRequest.addHeader("Authorization", GrafanaAuthenticationTestData.authorization);
cookiesMap = PlatformServiceUtil.getGrafanaCookies(httpRequest);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
cookiesString = cookiesMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(";"));
log.debug(" cookiesString " + cookiesString);
for (Map.Entry<String, String> entry : cookiesMap.entrySet()) {
Cookie cookie = new Cookie(entry.getKey(), entry.getValue());
cookie.setHttpOnly(true);
cookie.setMaxAge(60 * 30);
cookie.setPath("/");
httpRequest.setCookies(cookie);
}
}
/**
* Create the session.
*
* @param webApplication the web application.
* @param request the request.
* @return the session.
*/
@Override
public synchronized HttpSession createSession(WebApplication webApplication, HttpServletRequest request) {
String sessionId = UUID.randomUUID().toString();
DefaultHttpSession session = new DefaultHttpSession(webApplication, sessionId, true);
session.setSessionManager(this);
sessions.put(sessionId, session);
HttpServletResponse response = (HttpServletResponse) webApplication.getResponse(request);
Cookie cookie = new Cookie(name, sessionId);
if (path != null) {
cookie.setPath(path);
} else {
cookie.setPath("".equals(webApplication.getContextPath())? "/" : webApplication.getContextPath());
}
response.addCookie(cookie);
sessionListeners.stream().forEach((sessionListener) -> {
sessionListener.sessionCreated(new HttpSessionEvent(session));
});
return session;
}
/**
* 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);
}
private void addCookie(Cookie cookie) {
checkCommitted();
if (StringUtils.isNullOrEmpty(cookie.getPath())) {
cookie.setPath(StringUtils.addStart(contextPath, "/"));
}
getCookieMap().put(cookie.getName(), cookie);
}
private Cookie cloneCokie(Cookie sourceCookie, String newValue, int maxAge) {
Cookie resultCookie = new Cookie(sourceCookie.getName(), newValue);
resultCookie.setPath("/");
resultCookie.setMaxAge(maxAge);
resultCookie.setVersion(1);
resultCookie.setSecure(true);
return resultCookie;
}
/**
* accessToken生存时间设置为30min
*
* refreshToken生存时间设置为1天
*
* @param response
* @param path
* @param time
* @param accessToken
*/
public static void setCookieValue(HttpServletResponse response, String path, Integer time,
AccessTokenModel accessToken) {
/*
* P3P解决跨域
*/
response.addHeader("P3P", "CP=CAO PSA OUR");
// response.setHeader("P3P","CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa
// PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM
// CNT PRE LOC\"");
// accessToken及账号
Map<String, String> map1 = new HashMap<String, String>();
map1.put("accessToken", accessToken.getAccessToken());
map1.put("account", accessToken.getAccount());
Cookie cookie1 = new Cookie("accessToken", JsonTools.mapToJson(map1).toString());
cookie1.setPath(path);
cookie1.setMaxAge(time);
response.addCookie(cookie1);
// refreshToken及账号
Map<String, String> map2 = new HashMap<String, String>();
map2.put("refreshToken", accessToken.getRefreshToken());
map2.put("account", accessToken.getAccount());
Cookie cookie2 = new Cookie("refreshToken", JsonTools.mapToJson(map2).toString());
cookie2.setPath(path);
cookie2.setMaxAge(86400);// refreshToken默认一天
response.addCookie(cookie2);
}
/**
* 销毁cookie
*
* @param response
* @param tokenName
* @return
*/
public static boolean delCookieValue(HttpServletResponse response, String tokenName) {
try {
Cookie cookie = new Cookie(tokenName, "");
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public void onLoginSuccess(Map requestParams, HttpServletRequest request, HttpServletResponse response, SSOToken token) throws AuthenticationException {
log(token.getTokenID());
for (Object key : requestParams.keySet()) {
log(key + " -> " + requestParams.get(key));
}
String sessionId = token.getTokenID().toString();
response.setContentType("text/html");
response.addHeader("X-sli-session", sessionId);
response.setHeader("X-sli-session", sessionId);
Cookie c = new Cookie("sliSessionId", sessionId);
c.setPath("/");
c.setDomain(".slidev.org");
c.setMaxAge(5 * 60);
response.addCookie(c);
Cookie c2 = new Cookie("sliSessionId", sessionId);
c2.setPath("/");
c2.setDomain(".dk.com");
c2.setMaxAge(5 * 60);
response.addCookie(c2);
Cookie c3 = new Cookie("fversion", "1:51");
c.setPath("/");
c.setDomain(".slidev.org");
c.setMaxAge(5 * 60);
response.addCookie(c3);
}
@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 removeSessionCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = new Cookie("JSESSIONID", "");
cookie.setMaxAge(0); // 立即删除型
cookie.setPath("/"); // 项目所有目录均有效,这句很关键,否则不敢保证删除
cookie.setDomain(request.getHeader("host"));
response.addCookie(cookie); // 重新写入,将覆盖之前的%>
}
private Cookie setCookie(String token,User user){
CacheUtils.putUser(token, user);
Cookie cookie = new Cookie(Constants.TOKEN_COOKIE_NAME,token);
cookie.setPath("/");
cookie.setMaxAge(ConfigUtils.getTokenExpires());
return cookie;
}
void addCookie(HttpServletRequest req, HttpServletResponse resp, String cookieName,
String cookieValue) {
if (!"added".equals(req.getAttribute(cookieName))) {
final Cookie cookie = new Cookie(cookieName, cookieValue);
// cookie persistant, valide pendant 30 jours
cookie.setMaxAge(30 * 24 * 60 * 60);
// inutile d'envoyer ce cookie aux autres URLs que le monitoring
cookie.setPath(req.getRequestURI());
resp.addCookie(cookie);
req.setAttribute(cookieName, "added");
}
}
private void removeOidcRequestCookie(final HttpServletResponse httpServletResponse) {
final Cookie cookie = new Cookie(OIDC_REQUEST_IDENTIFIER, null);
cookie.setPath("/");
cookie.setHttpOnly(true);
cookie.setMaxAge(0);
cookie.setSecure(true);
httpServletResponse.addCookie(cookie);
}
/**
* 设置search记录到cookie中,操作步骤:
* 检查加入的记录是否已经存在cookie中,如果存在,则更新列表次序;如果不存在,则插入到最前面
* @param context
* @param value
*/
private void setSearchHistroy(Map<String, Object> context, String value) {
//分析已有的cookie
String separatorsB = "\\.\\.\\.\\.\\.\\.";
String newCookiev = value;
Cookie[] cookies = request.getCookies();
for(Cookie c:cookies){
if(c.getName().equals("HISTORY")){
String cookiev = c.getValue();
String[] values = cookiev.split(separatorsB);
int count = 1;
for(String v : values){
if(count<=10){
if(!value.equals(v)){
newCookiev = newCookiev + separatorsB + v;
}
}
count ++;
}
break;
}
}
Cookie _cookie=new Cookie("HISTORY", newCookiev);
_cookie.setMaxAge(60*60*24*7); // 设置Cookie的存活时间为30分钟
_cookie.setPath("/");
response.addCookie(_cookie); // 写入客户端硬盘
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
String redirectUrl = "";
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null && StringUtils.isNotEmpty(savedRequest.getRedirectUrl())) {
redirectUrl = savedRequest.getRedirectUrl();
}
// 根据需要设置 cookie,js携带token直接访问api接口等
if (authentication instanceof OAuth2AuthenticationToken) {
OAuth2AuthorizedClient client = authorizedClientService
.loadAuthorizedClient(
((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(),
authentication.getName());
String token = client.getAccessToken().getTokenValue();
Cookie tokenCookie = new Cookie("access_token", token);
tokenCookie.setHttpOnly(true);
tokenCookie.setDomain(cookieDomain);
tokenCookie.setPath("/");
response.addCookie(tokenCookie);
}
//设置回调成功的页面,
if (StringUtils.isNotEmpty(redirectUrl)) {
super.onAuthenticationSuccess(request, response, authentication);
} else {
response.sendRedirect("/");
}
}
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
if ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) &&
!request.isRequestedSessionIdValid()) {
if (containerLog.isDebugEnabled()) {
containerLog.debug("Load-balancer is in DISABLED state; draining this node");
}
boolean ignoreRebalance = false;
Cookie sessionCookie = null;
final Cookie[] cookies = request.getCookies();
final String sessionCookieName = SessionConfig.getSessionCookieName(request.getContext());
if (null != cookies) {
for (Cookie cookie : cookies) {
final String cookieName = cookie.getName();
if (containerLog.isTraceEnabled()) {
containerLog.trace("Checking cookie " + cookieName + "=" + cookie.getValue());
}
if (sessionCookieName.equals(cookieName) &&
request.getRequestedSessionId().equals(cookie.getValue())) {
sessionCookie = cookie;
} else if (null != _ignoreCookieName &&
_ignoreCookieName.equals(cookieName) &&
null != _ignoreCookieValue &&
_ignoreCookieValue.equals(cookie.getValue())) {
// The client presenting a valid ignore-cookie value?
ignoreRebalance = true;
}
}
}
if (ignoreRebalance) {
if (containerLog.isDebugEnabled()) {
containerLog.debug("Client is presenting a valid " + _ignoreCookieName +
" cookie, re-balancing is being skipped");
}
getNext().invoke(request, response);
return;
}
// Kill any session cookie that was found
// TODO: Consider implications of SSO cookies
if (null != sessionCookie) {
sessionCookie.setPath(SessionConfig.getSessionCookiePath(request.getContext()));
sessionCookie.setMaxAge(0); // Delete
sessionCookie.setValue(""); // Purge the cookie's value
response.addCookie(sessionCookie);
}
// Re-write the URI if it contains a ;jsessionid parameter
String uri = request.getRequestURI();
String sessionURIParamName = SessionConfig.getSessionUriParamName(request.getContext());
if (uri.contains(";" + sessionURIParamName + "=")) {
uri = uri.replaceFirst(";" + sessionURIParamName + "=[^&?]*", "");
}
String queryString = request.getQueryString();
if (null != queryString) {
uri = uri + "?" + queryString;
}
// NOTE: Do not call response.encodeRedirectURL or the bad
// sessionid will be restored
response.setHeader("Location", uri);
response.setStatus(_redirectStatusCode);
} else {
getNext().invoke(request, response);
}
}
private void killCookie(HttpServletResponse response, String name) {
Cookie c = new Cookie(name,"false");
c.setMaxAge( 0 ); // An age of 0 is defined to mean "delete cookie"
c.setPath( "/" ); // for all subdirs
response.addCookie( c );
}
/**
* Actual login method
* @param id
* @param pw
* @return
*/
private java.lang.String login(java.lang.String id, java.lang.String pw) {
Message message = PhaseInterceptorChain.getCurrentMessage();
HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
String ipAddress = request.getRemoteAddr();
boolean allowLogin = serverConfigurationService.getBoolean("webservices.allowlogin", false);
if (!allowLogin) {
throw new RuntimeException("Web Services Login Disabled");
}
try {
if ("GET".equals(request.getMethod())) {
log.info("This endpoint {} should use POST instead of GET, GET will be deprecated in a future release", request.getRequestURI());
}
Evidence e = new IdPwEvidence(id, pw, ipAddress);
Authentication a = authenticationManager.authenticate(e);
Session s = sessionManager.startSession();
sessionManager.setCurrentSession(s);
if (s == null) {
log.warn("Web Services Login failed to establish session for id=" + id + " ip=" + ipAddress);
throw new RuntimeException("Unable to establish session");
} else {
// We do not care too much on the off-chance that this fails - folks simply won't show up in presense
// and events won't be trackable back to people / IP Addresses - but if it fails - there is nothing
// we can do anyways.
usageSessionService.login(a.getUid(), id, ipAddress, "SakaiLogin", UsageSessionService.EVENT_LOGIN_WS);
log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());
// retrieve the configured cookie name, if any
if (System.getProperty(RequestFilter.SAKAI_COOKIE_PROP) != null) {
cookieName = System.getProperty(RequestFilter.SAKAI_COOKIE_PROP);
}
// retrieve the configured cookie domain, if any
// compute the session cookie suffix, based on this configured server id
String suffix = System.getProperty(RequestFilter.SAKAI_SERVERID);
if (StringUtils.isEmpty(suffix)) {
if (m_displayModJkWarning) {
log.warn("no sakai.serverId system property set - mod_jk load balancing will not function properly");
}
m_displayModJkWarning = false;
suffix = "sakai";
}
Cookie c = new Cookie(cookieName, s.getId() + "." + suffix);
c.setPath("/");
c.setMaxAge(-1);
if (System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN) != null) {
c.setDomain(System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN));
}
if (request.isSecure() == true) {
c.setSecure(true);
}
HttpServletResponse res = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP_RESPONSE);
if (res != null) {
res.addCookie(c);
}
log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());
return s.getId();
}
} catch (AuthenticationException ex) {
log.warn("Failed Web Services Login id=" + id + " ip=" + ipAddress + ": " + ex.getMessage());
}
throw new RuntimeException("Unable to login");
}
/**
* 设置cookie
*
* @param response HttpServletResponse
* @param name cookie name
* @param value cookie value
* @param maxAgeInSeconds maxage
*/
public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAgeInSeconds);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}