An invalid domain [.test.com] was specified for this cookie 原因分析

java.lang.IllegalArgumentException: An invalid domain [.test.com] was specified for this cookie
以上博客说明了解决办法以及可能的原因,现在就根据log查看tomcat源码看看是异常的原因以及在tomcat8.5上cookie name的规则。
Rfc6265CookieProcessor源码的167-197行代码如下

 private void validateDomain(String domain) {
        int i = 0;
        int prev = -1;
        int cur = -1;
        char[] chars = domain.toCharArray();
        while (i < chars.length) {
            prev = cur;
            cur = chars[i];
            if (!domainValid.get(cur)) {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            // labels must start with a letter or number
            if ((prev == '.' || prev == -1) && (cur == '.' || cur == '-')) {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            // labels must end with a letter or number
            if (prev == '-' && cur == '.') {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidDomain", domain));
            }
            i++;
        }
        // domain must end with a label
        if (cur == '.' || cur == '-') {
            throw new IllegalArgumentException(sm.getString(
                    "rfc6265CookieProcessor.invalidDomain", domain));
        }
    }

domain规则如下
1、必须是1-9、a-z、A-Z、. 、- (注意是-不是_)这几个字符组成
2、必须是数字或字母开头

上篇文章使用.test.com报错就是因为使用”.”开头

3、必须是数字或字母结尾

path的规则源码及规则

 private void validatePath(String path) {
        char[] chars = path.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (ch < 0x20 || ch > 0x7E || ch == ';') {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidPath", path));
            }
        }
    }

1、字符必须是在 0x20-0x7E之间,并且不能出现”;”号

cookie value 源码及规则

private void validateCookieValue(String value) {
        int start = 0;
        int end = value.length();

        if (end > 1 && value.charAt(0) == '"' && value.charAt(end - 1) == '"') {
            start = 1;
            end--;
        }

        char[] chars = value.toCharArray();
        for (int i = start; i < end; i++) {
            char c = chars[i];
            if (c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c || c == 0x7f) {
                throw new IllegalArgumentException(sm.getString(
                        "rfc6265CookieProcessor.invalidCharInValue", Integer.toString(c)));
            }
        }
    }

1、会自动去除开头和结尾的引号”
2、如果包含以下规则字符则校验失败:
c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c || c == 0x7f

posted @ 2016-08-06 11:47  小小架构师  阅读(2283)  评论(0编辑  收藏  举报