Spring 会话过期后重定向到登录页面

Redirecting to login page after Session Expired in Spring

1 我遇到了问题。我在我的项目用户、管理员、专家中有 3 个角色。 2 3 不同的用户登录页面。 3 我想要的是会话何时过期,之后如果用户执行任何事件,页面应根据那里的角色定向。 例如,用户应该重定向到用户登录和管理员以管理登录。

我读过很多关于 it.Some 的文档,它们给出了添加过​​滤器并检查过滤器中的会话的想法。 但问题是我没有得到过滤器中的角色。 所以 SpringSecurityHolder 将在 Filter 内部工作。

我也读过关于接受事件的ApplicationListerner。 我有 return 代码,但我不知道如何从监听器内部进行引导 class

import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.session.HttpSessionDestroyedEvent;

public class SessionTimeoutHandler  implements ApplicationListener<HttpSessionDestroyedEvent>{

    @Override
    public void onApplicationEvent(HttpSessionDestroyedEvent event) {

        List<SecurityContext> lstSecurityContext = event
                .getSecurityContexts();

        for (SecurityContext securityContext : lstSecurityContext)
        {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            List<GrantedAuthority> authList = (List<GrantedAuthority>) authentication
                    .getAuthorities();
            String userRole = authList.get(0).getAuthority();

            if(userRole.equals("ROLE_ADMIN")){


            }else if(userRole.equals("ROLE_EXPERT")){

            }else{

            }

        }

    }

}

请帮帮我,我怎样才能重定向页面。

感谢您的帮助

一旦 HTTP 会话过期,确实没有确定用户所处角色的好方法,因为一旦过期,用户信息就会消失。

您不能从 ApplicationListener 进行重定向,因为当用户浏览器未发出请求时会话可能会过期(除非有打开的连接,否则我们无法将信息推送到浏览器)。

我能给你的最好的解决方案是设置一个 cookie 来指示用户所处的角色。cookie 将比会话更有效,然后你可以根据 cookie 执行重定向到适当的登录页面。

当然,如果多个不同类型的用户使用同一台计算机,因为他们共享相同的 cookie,这当然会失败。