在Jsf2中无需登录即可防止访问受限页面 [英] Prevent accessing restricted page without login in Jsf2

查看:80
本文介绍了在Jsf2中无需登录即可防止访问受限页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我想阻止用户在没有登录jsf2的情况下访问页面。当用户直接将受限制的页面URL写入浏览器时,他/她不应该看到该页面。就像上面的情况一样,他/她必须被重定向到登录页面。我该如何以编程方式执行此操作?

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 page. Thats like above circumstance come about, s/he has to be redirected to login page. How can I do this programmatically ?

推荐答案

这取决于您如何编程登录。您似乎正在使用自行开发的身份验证,其中您将登录用户设置为会话作用域托管bean的属性。因为Java EE提供了容器管理登录,所以已经考虑阻止访问受限制的页面。

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.

假设您在某个URL模式上有所有受限制的页面,例如 / app / * / secured / * 等,并且您的会话范围bean具有托管bean名称 user ,然后您可以使用过滤来完成工作。在 doFilter()方法中实现以下内容:

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.

此外,您需要确保已在这些页面上禁用了浏览器缓存,否则最终用户仍然可以在注销后从浏览器缓存中看到它们。您也可以使用过滤器。您甚至可以在同一个过滤器中执行此操作。另请参见浏览器后退按钮不会清除旧的支持bean值

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.

这篇关于在Jsf2中无需登录即可防止访问受限页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆