Prevent accessing restricted page without login in Jsf2

后端 未结 2 1148
一整个雨季
一整个雨季 2020-12-03 02:26

I have a problem. I want to prevent a user from accessing a page without login in jsf2. When a user directly write restricted page url into browser, s/he should not see the

2条回答
  •  有刺的猬
    2020-12-03 02:44

    That depends on how you have programmed the login. You seem to be using homegrown authentication wherein you set the logged-in user as a property of a session scoped managed bean. Because with Java EE provided container managed login, preventing access to restricted pages is already taken into account.

    Assuming that you've all restricted pages on a certain URL pattern, like /app/*, /secured/* etc and that your session scoped bean has the managed bean name user, then you could use a filter for the job. Implement the following in doFilter() method:

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        User user = (session != null) ? (User) session.getAttribute("user") : null;
    
        if (user == null || !user.isLoggedIn()) {
            response.sendRedirect("/login.xhtml"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }
    

    Map this filter on an URL pattern covering the restricted pages.

    Further, you need to ensure that you've disabled the browser cache on those pages, otherwise the enduser will still be able to see them from browser cache after logout. You can also use a filter for this. You could even do it in the same filter. See also Browser back button doesn't clear old backing bean values.

提交回复
热议问题