springsession 使用

springsession 获取到session会话 可以通过2种方式,一个是把token放在header,一个是放在cookie里面。如果所有的子系统域名之间的cookie信息 可以共享,可以考虑使用 cookie。

开启redis 存储session会话,使用redis存储session 是为了seesion 会话共享,主要就是实现seesion接口 ,重写session

1. 放在header

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds =172800 ) // session 存储时间
public class HttpSessionConfig {

    @Bean
    // 放在heeader
    public HttpSessionIdResolver httpSessionStrategy() {
        return new WebHttpSessionIdResolver("token");
    }

}
public class WebHttpSessionIdResolver implements HttpSessionIdResolver {
    private static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token";
    private static final String HEADER_AUTHENTICATION_INFO = "Authentication-Info";
    private final String headerName ;

    public static HeaderHttpSessionIdResolver xAuthToken() {
        return new HeaderHttpSessionIdResolver("X-Auth-Token");
    }

    public static HeaderHttpSessionIdResolver authenticationInfo() {
        return new HeaderHttpSessionIdResolver("Authentication-Info");
    }

    public WebHttpSessionIdResolver(String headerName) {
        if (headerName == null) {
            throw new IllegalArgumentException("headerName cannot be null");
        } else {
            this.headerName = headerName;
        }
    }

    public List resolveSessionIds(HttpServletRequest request) {
        String headerValue = request.getHeader(this.headerName);
        return headerValue != null ? Collections.singletonList(headerValue) : Collections.emptyList();
    }

    public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
        response.setHeader(this.headerName, sessionId);
    }

    public void expireSession(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader(this.headerName, "");
    }
}

根据 需要是否 对类进行逻辑处理。

2 放在cookie里面

public class MyCookieSerializer implements CookieSerializer {
    private String cookieName = "SESSION";
    private Boolean useSecureCookie;
    private boolean useHttpOnlyCookie = this.isServlet3();
    private String cookiePath;
    private Integer cookieMaxAge;
    private String domainName;
    private Pattern domainNamePattern;
    private String jvmRoute;
    private boolean useBase64Encoding = true;
    private String rememberMeRequestAttribute;

    public MyCookieSerializer() {
    }

    public List readCookieValues(HttpServletRequest request) {
        String path = request.getRequestURI();
        if (path.startsWith("/api")){
            return new ArrayList<>();
        }
        Cookie[] cookies = request.getCookies();
        List matchingCookieValues = new ArrayList();
        if (cookies != null) {
            Cookie[] var4 = cookies;
            int var5 = cookies.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Cookie cookie = var4[var6];
                if (this.cookieName.equals(cookie.getName())) {
                    String sessionId = this.useBase64Encoding ? this.base64Decode(cookie.getValue()) : cookie.getValue();
                    if (sessionId != null) {
                        if (this.jvmRoute != null && sessionId.endsWith(this.jvmRoute)) {
                            sessionId = sessionId.substring(0, sessionId.length() - this.jvmRoute.length());
                        }

                        matchingCookieValues.add(sessionId);
                    }
                }
            }
        }

        return matchingCookieValues;
    }

    public void writeCookieValue(CookieSerializer.CookieValue cookieValue) {
        HttpServletRequest request = cookieValue.getRequest();
        HttpServletResponse response = cookieValue.getResponse();
        String requestedCookieValue = cookieValue.getCookieValue();
        String actualCookieValue = this.jvmRoute == null ? requestedCookieValue : requestedCookieValue + this.jvmRoute;
        Cookie sessionCookie = new Cookie(this.cookieName, this.useBase64Encoding ? this.base64Encode(actualCookieValue) : actualCookieValue);
        sessionCookie.setSecure(this.isSecureCookie(request));
        sessionCookie.setPath(this.getCookiePath(request));
        String path = request.getRequestURI();
        if (!path.equals("/") && !path.equals("/login") && !path.equals("/logout")){
            return;
        }

        String domainName = this.getDomainName(request);
        if (domainName != null) {
            sessionCookie.setDomain(domainName);
        }

        if (this.useHttpOnlyCookie) {
            sessionCookie.setHttpOnly(true);
        }

        if (cookieValue.getCookieMaxAge() < 0) {
            if (this.rememberMeRequestAttribute != null && request.getAttribute(this.rememberMeRequestAttribute) != null) {
                cookieValue.setCookieMaxAge(2147483647);
            } else if (this.cookieMaxAge != null) {
                cookieValue.setCookieMaxAge(this.cookieMaxAge);
            }
        }

        sessionCookie.setMaxAge(cookieValue.getCookieMaxAge());
        response.addCookie(sessionCookie);
    }

    private String base64Decode(String base64Value) {
        try {
            byte[] decodedCookieBytes = Base64.getDecoder().decode(base64Value);
            return new String(decodedCookieBytes);
        } catch (Exception var3) {
            return null;
        }
    }

    private String base64Encode(String value) {
        byte[] encodedCookieBytes = Base64.getEncoder().encode(value.getBytes());
        return new String(encodedCookieBytes);
    }

    public void setUseSecureCookie(boolean useSecureCookie) {
        this.useSecureCookie = useSecureCookie;
    }

    public void setUseHttpOnlyCookie(boolean useHttpOnlyCookie) {
        if (useHttpOnlyCookie && !this.isServlet3()) {
            throw new IllegalArgumentException("You cannot set useHttpOnlyCookie to true in pre Servlet 3 environment");
        } else {
            this.useHttpOnlyCookie = useHttpOnlyCookie;
        }
    }

    private boolean isSecureCookie(HttpServletRequest request) {
        return this.useSecureCookie == null ? request.isSecure() : this.useSecureCookie;
    }

    public void setCookiePath(String cookiePath) {
        this.cookiePath = cookiePath;
    }

    public void setCookieName(String cookieName) {
        if (cookieName == null) {
            throw new IllegalArgumentException("cookieName cannot be null");
        } else {
            this.cookieName = cookieName;
        }
    }

    public void setCookieMaxAge(int cookieMaxAge) {
        this.cookieMaxAge = cookieMaxAge;
    }

    public void setDomainName(String domainName) {
        if (this.domainNamePattern != null) {
            throw new IllegalStateException("Cannot set both domainName and domainNamePattern");
        } else {
            this.domainName = domainName;
        }
    }

    public void setDomainNamePattern(String domainNamePattern) {
        if (this.domainName != null) {
            throw new IllegalStateException("Cannot set both domainName and domainNamePattern");
        } else {
            this.domainNamePattern = Pattern.compile(domainNamePattern, 2);
        }
    }

    public void setJvmRoute(String jvmRoute) {
        this.jvmRoute = "." + jvmRoute;
    }

    public void setUseBase64Encoding(boolean useBase64Encoding) {
        this.useBase64Encoding = useBase64Encoding;
    }

    public void setRememberMeRequestAttribute(String rememberMeRequestAttribute) {
        if (rememberMeRequestAttribute == null) {
            throw new IllegalArgumentException("rememberMeRequestAttribute cannot be null");
        } else {
            this.rememberMeRequestAttribute = rememberMeRequestAttribute;
        }
    }

    private String getDomainName(HttpServletRequest request) {
        if (this.domainName != null) {
            return this.domainName;
        } else {
            if (this.domainNamePattern != null) {
                Matcher matcher = this.domainNamePattern.matcher(request.getServerName());
                if (matcher.matches()) {
                    return matcher.group(1);
                }
            }

            return null;
        }
    }

    private String getCookiePath(HttpServletRequest request) {
        return  "/"+request.getServerPort() + "";
    }

    private boolean isServlet3() {
        try {
            ServletRequest.class.getMethod("startAsync");
            return true;
        } catch (NoSuchMethodException var2) {
            return false;
        }
    }

使用cookie。

3. 一起使用 ,如果需要一起使用,最好用能区分什么接口 从header获取,什么接口 从cookie 获取。

你可能感兴趣的:(java)