In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to dynamically modify the max-age of cookie in spring-session, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Dynamically modify the max-age of cookie when using spring-session
Whether you use spring-session provided by spring or http session implemented using a servle container. The principle is to store session-id in the client in the form of cookie. Bring cookie with each request. The server finds the session through session-id.
The use of spring-session
Https://springboot.io/t/topic/864
A problem caused by "remember me"
When users log in, they usually need a [remember me] selection box to indicate whether they want to keep the session for a long time.
[remember me] × generally sets the max-age of cookie to-1, which means that cookie is automatically deleted when the browser is closed. For the client to close the browser is to lose the session and need to log in to the system again. Especially after logging on to some systems in public places, they forgot to perform the 'exit' operation and closed the browser directly. Later, people who use the computer open the browser and must log in before they can access the system. This ensures security to a certain extent.
[remember me] √ usually chooses on his own personal computer in order to avoid repeated login operations. If you log in successfully, you will generally set the value of max-age to long, even if you close the browser. Reopen it, and you don't need to log in again.
Spring-session configures the max-age property of cookie
When using spring-session, you can set the properties of max-age in the form of yml configuration or code configuration. But the problem is that all session creations use the same properties. There will be some problems in [remember me] this function
Fixed setting: max-age=-1, then even if [remember me] is checked, the session will be lost because the browser closes and deletes the cookie. Next time you open the browser, you still need to log in again.
Fixed setting: max-age=604800 (7 days), then the user closes the browser without checking [remember me]. Cookie will not be deleted immediately, and anyone will turn on the system again. You don't need to log in to run the operating system directly.
In general, the fixed max-age attribute will cause the [remember me] function to fail.
Solution when using spring-session
Spring-session completes the read and write operation to the client cookie through the interface CookieSerializer. And provides a default implementation class: DefaultCookieSerializer. We want to modify the max-age property of cookie dynamically, the core method is.
@ Overridepublic void writeCookieValue (CookieValue cookieValue) {... StringBuilder sb = new StringBuilder (); sb.append (this.cookieName) .append ('='); Int maxAge = getMaxAge (cookieValue); / / read the maxAge attribute if (maxAge >-1) {sb.append ("; Max-Age=") .append (cookieValue.getCookieMaxAge ()); ZonedDateTime expires = (maxAge! = 0)? ZonedDateTime.now (this.clock) .plusSeconds (maxAge): Instant.EPOCH.atZone (ZoneOffset.UTC); sb.append ("; Expires=") .append (expires.format (DateTimeFormatter.RFC_1123_DATE_TIME));}...} private int getMaxAge (CookieValue cookieValue) {int maxAge = cookieValue.getCookieMaxAge (); if (maxAge)
< 0) { if (this.rememberMeRequestAttribute != null && cookieValue.getRequest().getAttribute(this.rememberMeRequestAttribute) != null) { cookieValue.setCookieMaxAge(Integer.MAX_VALUE); } else if (this.cookieMaxAge != null) { cookieValue.setCookieMaxAge(this.cookieMaxAge); // 如果 DefaultCookieSerializer 设置了maxAge属性,则该属性优先 } } return cookieValue.getCookieMaxAge(); // cookieValue 默认的maxAge属性 = -1} 可以看出,spring-session并没使用servlet提供的cookie api来响应cookie。而是自己构造Cookie头。而且还提供了Servlet还未实现的,Cookie的新属性:sameSite,可以用来防止csrf攻击。 覆写 DefaultCookieSerializerimport javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.session.web.http.DefaultCookieSerializer;// @Componentpublic class DynamicCookieMaxAgeCookieSerializer extends DefaultCookieSerializer { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicCookieMaxAgeCookieSerializer.class); public static final String COOKIE_MAX_AGE = "cookie.max-age"; @Value("${server.servlet.session.cookie.max-age}") private Integer cookieMaxAge; @Override public void writeCookieValue(CookieValue cookieValue) { HttpServletRequest request = cookieValue.getRequest(); // 从request域读取到cookie的maxAge属性 Object attribute = request.getAttribute(COOKIE_MAX_AGE); if (attribute != null) { cookieValue.setCookieMaxAge((int) attribute); } else { // 如果未设置,就使用默认cookie的生命周期 cookieValue.setCookieMaxAge(this.cookieMaxAge); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("动态设置cooke.max-age={}", cookieValue.getCookieMaxAge()); } super.writeCookieValue(cookieValue); }} 原理就是,把cookie的maxAge属性存储到request域。在响应客户端之前,动态的设置。 添加到IOCimport org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.session.web.http.CookieSerializer;import com.video.manager.spring.session.DynamicCookieMaxAgeCookieSerializer;@Configurationpublic class SpringSessionConfiguration { @Value("${server.servlet.session.cookie.name}") private String cookieName; @Value("${server.servlet.session.cookie.secure}") private Boolean cookieSecure; // @Value("${server.servlet.session.cookie.max-age}")// private Integer cookieMaxAge; @Value("${server.servlet.session.cookie.http-only}") private Boolean cookieHttpOnly; @Value("${server.servlet.session.cookie.same-site}") private String cookieSameSite; @Bean public CookieSerializer cookieSerializer() { DynamicCookieMaxAgeCookieSerializer serializer = new DynamicCookieMaxAgeCookieSerializer(); serializer.setCookieName(this.cookieName); // serializer.setCookieMaxAge(this.cookieMaxAge); serializer.setSameSite(this.cookieSameSite); serializer.setUseHttpOnlyCookie(this.cookieHttpOnly); serializer.setUseSecureCookie(this.cookieSecure); return serializer; }} 使用 @Value,读取yml配置中的Cookie属性。 测试接口import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;import com.video.manager.spring.session.DynamicCookieMaxAgeCookieSerializer;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;@Controller@RequestMapping("/test")public class TestController { static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @GetMapping("/session") public ModelAndView session(HttpServletRequest request, @RequestParam("remember")Boolean remember) { HttpSession httpSession = request.getSession(); LOGGER.debug("httpSession={}", httpSession); if (!remember) { // 不记住我 // 设置cookie的生命周期为 -1 request.setAttribute(DynamicCookieMaxAgeCookieSerializer.COOKIE_MAX_AGE, -1); // 设置session仅缓存30分钟 httpSession.setMaxInactiveInterval(60 * 30); } ModelAndView modelAndView = new ModelAndView("test/test"); return modelAndView; }}【记住我】√ http://localhost/test/session?remember=true 响应Cookie,存储时间是 7 天Redis's session storage, caching time is 7 days
[remember me] ×
Http://localhost/test/session?remember=false
In response to Cookie, the storage time is:-1. The temporary session is set successfully, and the browser closes Cookie deletion.
Session storage of redis. Cache time is 30 minutes. If it is inactive for more than 30 minutes, it will be deleted automatically.
The max-age about how to dynamically modify cookie in spring-session is shared here. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.