SpringBoot实现多个子域共享cookie的示例

 更新时间:2023年04月10日 09:12:22   作者:modelmd  
本文主要介绍了SpringBoot实现多个子域共享cookie的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

项目信息

使用SpringBoot web框架,版本号 2.7.10

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

cookie 共享

需求

现在有两个域名 dev.scd.com.cn,test.scd.com.cn 的服务,登录验证之后,服务器写入 cookie 到响应头,用户只需要登录一次,访问任意一个域都携带cookie 信息

如何实现

后端服务写入cookie 指定domain为二级域名 .scd.com.cn
cookie基础知识

环境配置

配置域

本地模拟多个域的环境,需要在host 上配置域名,增加如下配置

127.0.0.1 dev.scd.com.cn
127.0.0.1 test.scd.com.cn

SpringBoot 配置 https 访问

application.properties 文件增加如下配置

# https
server.ssl.key-store=F:/keytool/https.p12
server.ssl.key-alias=tomcathttps
server.ssl.key-store-password=shootercheng

执行jdk 自带的命令行工具 keytool 生成证书

keytool -genkey -alias tomcathttps -keyalg RSA -keysize 4096 -keystore https.p12 -validity 365

参考地址

SpringBoot Https配置

后端代码

在 httpResponse 响应中增加 cookie

package com.scd.cookie.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author James
 * @date 2023/4/8
 */
@RestController
@RequestMapping(value = "/cookie")
public class CookieController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CookieController.class);

    private static final String COOKIE_DOMAIN = ".scd.com.cn";

    private static final int COOKIE_MAX_AGE_DAY = 7;

    private static final String COOKIE_KEY = "test_key";

    @GetMapping("/set")
    public String cookieSet(HttpServletResponse response) {
        Cookie cookie = new Cookie(COOKIE_KEY, "scd");
        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setSecure(true);
        cookie.setMaxAge((int) Duration.ofDays(COOKIE_MAX_AGE_DAY).getSeconds());
        response.addCookie(cookie);
        return "OK";
    }

    @GetMapping("/get")
    public String cookieGet(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (COOKIE_KEY.equals(cookie.getName())) {
                LOGGER.info("cookie name {} value {}", COOKIE_KEY, cookie.getValue());
            }
            return cookie.getValue();
        }
        return "OK";
    }
}

启动服务,访问 https://dev.scd.com.cn:8080/cookie/set

后端服务报错信息如下 An invalid domain [.scd.com.cn] was specified for this cookie

java.lang.IllegalArgumentException: An invalid domain [.scd.com.cn] was specified for this cookie
	at org.apache.tomcat.util.http.Rfc6265CookieProcessor.validateDomain(Rfc6265CookieProcessor.java:218) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.http.Rfc6265CookieProcessor.generateHeader(Rfc6265CookieProcessor.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.connector.Response.generateCookieString(Response.java:970) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.connector.Response.addCookie(Response.java:923) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.connector.ResponseFacade.addCookie(ResponseFacade.java:314) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at javax.servlet.http.HttpServletResponseWrapper.addCookie(HttpServletResponseWrapper.java:57) ~[tomcat-embed-core-9.0.73.jar:4.0.FR]
	at com.scd.cookie.controller.CookieController.cookieSet(CookieController.java:39) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_77]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_77]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.26.jar:5.3.26]
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1072) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:965) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:502) ~[tomcat-embed-core-9.0.73.jar:4.0.FR]
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.26.jar:5.3.26]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:596) ~[tomcat-embed-core-9.0.73.jar:4.0.FR]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:209) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.26.jar:5.3.26]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.26.jar:5.3.26]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.26.jar:5.3.26]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.26.jar:5.3.26]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:142) ~[spring-session-core-2.7.1.jar:2.7.1]
	at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:82) ~[spring-session-core-2.7.1.jar:2.7.1]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.26.jar:5.3.26]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.26.jar:5.3.26]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:130) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:389) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:926) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1791) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.73.jar:9.0.73]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.73.jar:9.0.73]

根据堆栈信息,发现报错的方法在校验域名时候产生的org.apache.tomcat.util.http.Rfc6265CookieProcessor#generateHeader(javax.servlet.http.Cookie, javax.servlet.http.HttpServletRequest)
org.apache.tomcat.util.http.Rfc6265CookieProcessor#validateDomain

	private void validateDomain(String domain) {
        int i = 0;
        int prev = true;
        int cur = -1;

        for(char[] chars = domain.toCharArray(); i < chars.length; ++i) {
            int prev = cur;
            cur = chars[i];
            if (!domainValid.get(cur)) {
                throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", new Object[]{domain}));
            }

            if ((prev == 46 || prev == -1) && (cur == 46 || cur == 45)) {
                throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", new Object[]{domain}));
            }

            if (prev == 45 && cur == 46) {
                throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", new Object[]{domain}));
            }
        }

如何绕过校验了,跟踪代码发现最终添加 cookie 的代码方法为
org.apache.catalina.connector.Response#addCookie

org.apache.catalina.connector.Response#addHeader(java.lang.String, java.lang.String, java.nio.charset.Charset)

最终是转换为字符串设置到 “Set-Cookie” 字符串的,可以使用如下方法直接设置

ResponseCookie cookie = ResponseCookie.from(COOKIE_KEY, "scd")
                .httpOnly(true)
                .secure(true)
                .domain(COOKIE_DOMAIN)
                .path("/")
                .sameSite("Lax")
                .maxAge(Duration.ofDays(COOKIE_MAX_AGE_DAY))
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());

这样就绕过校验了。调整之后的代码如下:

package com.scd.cookie.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author James
 * @date 2023/4/8
 */
@RestController
@RequestMapping(value = "/cookie")
public class CookieController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CookieController.class);

    private static final String COOKIE_DOMAIN = ".scd.com.cn";

    private static final int COOKIE_MAX_AGE_DAY = 7;

    private static final String COOKIE_KEY = "test_key";

    @GetMapping("/set")
    public String cookieSet(HttpServletResponse response) {
//        Cookie cookie = new Cookie(COOKIE_KEY, "scd");
//        cookie.setDomain(COOKIE_DOMAIN);
//        cookie.setHttpOnly(true);
//        cookie.setPath("/");
//        cookie.setSecure(true);
//        cookie.setMaxAge((int) Duration.ofDays(COOKIE_MAX_AGE_DAY).getSeconds());
//        response.addCookie(cookie);
        ResponseCookie cookie = ResponseCookie.from(COOKIE_KEY, "scd")
                .httpOnly(true)
                .secure(true)
                .domain(COOKIE_DOMAIN)
                .path("/")
                .sameSite("Lax")
                .maxAge(Duration.ofDays(COOKIE_MAX_AGE_DAY))
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        return "OK";
    }

    @GetMapping("/get")
    public String cookieGet(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (COOKIE_KEY.equals(cookie.getName())) {
                LOGGER.info("cookie name {} value {}", COOKIE_KEY, cookie.getValue());
            }
            return cookie.getValue();
        }
        return "OK";
    }
}

验证

重启服务,之后访问 https://dev.scd.com.cn:8080/cookie/set,发现响应头设置cookie 成功

再次请求这个地址,请求头也携带了 cookie

访问 https://test.scd.com.cn:8080/cookie/set, 请求头也会携带cookie

验证后端解析 cookie 使用无痕模式,先访问 https://dev.scd.com.cn:8080/cookie/set再访问地址 https://test.scd.com.cn:8080/cookie/get

可以看到 cookie 在多个子域的请求都可以携带

到此这篇关于SpringBoot实现多个子域共享cookie的示例的文章就介绍到这了,更多相关SpringBoot 子域共享cookie内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现接口的枚举类示例

    Java实现接口的枚举类示例

    这篇文章主要介绍了Java实现接口的枚举类,结合实例形式分析了java接口的枚举类相关原理与使用技巧,需要的朋友可以参考下
    2019-08-08
  • java使用for循环输出杨辉三角

    java使用for循环输出杨辉三角

    杨辉三角形由数字排列,可以把它看做一个数字表,其基本特性是两侧数值均为1,其他位置的数值是其正上方的数字与左上角数值之和,下面是java使用for循环输出包括10行在内的杨辉三角形
    2014-02-02
  • Java求10到100000之间的水仙花数算法示例

    Java求10到100000之间的水仙花数算法示例

    这篇文章主要介绍了Java求10到100000之间的水仙花数算法,结合实例形式分析了水仙花数的概念及相应的java算法实现技巧,需要的朋友可以参考下
    2017-10-10
  • Spring Boot 整合 Fisco Bcos部署、调用区块链合约的案例

    Spring Boot 整合 Fisco Bcos部署、调用区块链合约的案例

    本篇文章介绍 Spring Boot 整合 Fisco Bcos 的相关技术,最最重要的技术点,部署、调用区块链合约的工程案例,本文通过流程分析给大家介绍的非常详细,需要的朋友参考下吧
    2022-01-01
  • 利用Spring AOP记录方法的执行时间

    利用Spring AOP记录方法的执行时间

    这篇文章给大家介绍的是spring的aop来实现方法级的执行时间的记录监控,以此来评估方法的性能以及针对性的对已存在的方法进行优化。对于监控,我们比较关注监控的可靠性和性能,准确,高效,这才能在不影响整体性能的情况下对我们的系统性能有个较准确的认识。
    2016-09-09
  • 通过实例深入了解java序列化

    通过实例深入了解java序列化

    这篇文章主要介绍了通过实例深入了解java序列化,
    2019-06-06
  • mybatisplus开启sql打印的三种方式汇总

    mybatisplus开启sql打印的三种方式汇总

    这篇文章主要介绍了mybatisplus开启sql打印的三种方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-01-01
  • Eclipse新建web项目流程图解

    Eclipse新建web项目流程图解

    这篇文章主要介绍了Eclipse新建web项目流程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Java使用ArrayList实现扑克牌的示例代码

    Java使用ArrayList实现扑克牌的示例代码

    学习了关于集合类的知识,我们可以做一个小项目来加深对集合类知识的学习!本文就来利用ArrayList实现扑克牌发牌洗牌效果,需要的可以参考一下
    2022-10-10
  • 往DAO类中注入@PersistenceContext和@Resource的区别详解

    往DAO类中注入@PersistenceContext和@Resource的区别详解

    这篇文章主要介绍了往DAO类中注入@PersistenceContext和@Resource的区别详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02

最新评论