Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring security,在会话超时后创建会话而不登录_Java_Spring_Spring Mvc_Spring Security_Servlet Filters - Fatal编程技术网

Java Spring security,在会话超时后创建会话而不登录

Java Spring security,在会话超时后创建会话而不登录,java,spring,spring-mvc,spring-security,servlet-filters,Java,Spring,Spring Mvc,Spring Security,Servlet Filters,我已经创建了一个默认表单登录身份验证,下面是我的配置 <!-- Empty filter chain for the login page --> <http pattern="/rest/login" security="none" /> <http pattern="/install/license/**" security="none" /> <http pattern="/resources/**" security="none" />

我已经创建了一个默认表单登录身份验证,下面是我的配置

<!-- Empty filter chain for the login page -->
<http pattern="/rest/login" security="none" />
<http pattern="/install/license/**" security="none" />
<http pattern="/resources/**" security="none" />

<http auto-config="true" use-expressions="true">
    <request-cache ref="authenticationRequestCache" />
    <access-denied-handler error-page="/rest/login?error=denied" />
    <form-login login-page="/rest/login"    
        authentication-success-handler-ref="successHandler"
        authentication-failure-url="/rest/login?error" />
    <intercept-url pattern="/rest/devices" access="denyAll" />
    <intercept-url pattern="/rest/devices/**" access="denyAll" />
    <intercept-url pattern="/rest/super/**" access="hasRole('ROLE_SUPER')" />
    <intercept-url pattern="/rest/**" access="isAuthenticated()" />
    <intercept-url pattern="/cavirinRest/*" />
    <session-management invalid-session-url="/rest/login?error=sessionExpired" 
        session-authentication-strategy-ref="sas" />
    <logout invalidate-session="true" logout-success-url="/rest/login" delete-cookies="JSESSIONID"/>
</http>

我知道我并没有在超时后停止轮询服务器,所以它会一次又一次地轮询,但1)在不登录应用程序的情况下如何创建会话

另外,2)我没有收到会话超时错误消息,因为它会一次又一次地重定向到此页面,并转到登录页面。在用户再次登录之前,我无法保留此错误消息


有什么建议吗

在阅读了大量有关spring security及其相关内容后,我开始意识到这一点 1) 会话是默认创建的(http配置,如果需要),一旦会话超时,它将自动重定向到无效会话url的会话管理上的给定url,并创建另一个会话。我在spring安全调试日志中观察到了这种行为,其中指出,会话无效,如果需要,将创建另一个会话。
2) 一旦超时会话无效,它将重定向到无效会话url;但是我的ajax会从同一个页面进行轮询,创建另一个会话并寻找身份验证以访问我的安全网页,因此会对我的登录页面进行重定向,但这次没有会话超时错误。

您正确理解了

让我解释一下

会话在默认情况下是创建的,它被称为ROLE_ANONYMOUS

默认情况下,如果没有会话(没有JSSessionID的cookie),它将创建一个Role=Role\u匿名的会话,如果已经通过身份验证,它将不会创建新会话

因此,ROLE_ANONYMOUS是一个未经身份验证的用户

permitAll还包括匿名用户。将允许匿名用户访问该资源

试试这个。像这样向匿名用户授权管理资源

.antMatchers("/app/admin/*").hasRole("ANONYMOUS")
那么管理员资源只能在没有登录的情况下访问。如果使用管理员凭据登录并尝试访问,您将收到403错误(禁止)

未经身份验证的用户是匿名用户,他还将获得一个会话来识别他,因此他的会话在超时后也会失效,因此会重定向到会话管理中配置的页面expiredUrl


他是唯一一个无法访问AuthenticationSuccessHandler的用户

是否可以阻止spring security在会话失效时创建另一个会话?要使其仅重定向到无效会话url的会话管理上的给定url。。。
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    HttpSession session = request.getSession(false);

    if (session != null) {
        logger.trace("doFilterInternal(): session object is not null.");

        session.setMaxInactiveInterval(120); //2 mins for testing //set max inactive interval to 30 mins

        // if requestURI is not null
        if (request.getRequestURI() != null) {

            logger.trace("doFilterInternal(): request.getRequestURI() : {} ", request.getRequestURI());

            String ajaxHeader = request.getHeader("X-Requested-With");
            logger.trace("doFilterInternal(): ajaxHeader : {} ", ajaxHeader);

            //if it is an AJAX call
            if ("XMLHttpRequest".equals(ajaxHeader)) {
                logger.trace("doFilterInternal(): An AJAX call, set the last access time, if not already set.");
                Long lastAccess = (Long) session.getAttribute(AJAX_DATA_LAST_ACCESS_TIME);

                if (lastAccess == null) {
                    logger.trace("doFilterInternal(): Last access time is null, set current time as lastAccess time.");
                    lastAccess = System.currentTimeMillis();
                    session.setAttribute(AJAX_DATA_LAST_ACCESS_TIME, lastAccess);
                } else {
                    logger.trace("doFilterInternal(): max interval: {} -- lastAccess: {} -- currentTimeMillis: {} ",
                        + session.getMaxInactiveInterval(), lastAccess, System.currentTimeMillis());
                    if (((session.getMaxInactiveInterval() * 1000) - (System.currentTimeMillis() - lastAccess)) < 0) {
                        logger.debug("doFilterInternal(): session should be invalidated as inative time execeeded.");
                        session.invalidate();
                    }
                }
            } else {
                logger.trace("doFilterInternal(): Not an AJAX call.");
                session.removeAttribute(AJAX_DATA_LAST_ACCESS_TIME);
            }
        }
    }

    filterChain.doFilter(request, response);
}
RequestMapping(method = RequestMethod.GET)
public ModelAndView showLogin(Model model,
                              @RequestParam(value = "error", required = false) String errorStr,
                              HttpServletRequest request) {
    logger.trace("Returning login page view.");

    String pageToBeLoaded = "rest/login" ;

    System.out.println("showLogin(): errorStr: " + errorStr);

    if (errorStr != null) {

        if (errorStr.equalsIgnoreCase("sessionExpired")) {
            logger.debug("showLogin(): error: sessionExpired ");
            System.out.println("showLogin(): error: sessionExpired");
            model.addAttribute("error", "Session expired. Please log in again.");
        } else if (errorStr.equalsIgnoreCase("denied")) {
            logger.debug("showLogin(): error: denied ");
            System.out.println("showLogin(): error: denied");
            model.addAttribute("error", "Access is denined. This page is for SUPER user only.");
        } else {
            model.addAttribute("error", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
            System.out.println("showLogin(): error: " + getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
        }
    } 
    return new ModelAndView(pageToBeLoaded);
}
.antMatchers("/app/admin/*").hasRole("ANONYMOUS")