java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot 子域共享cookie

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

作者: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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文