防止在未登录 Jsf2 的情况下访问受限页面 [英] Prevent accessing restricted page without login in Jsf2

查看:20
本文介绍了防止在未登录 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,那么您可以使用 filter 来完成这项工作.在 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.
    }
}

将此过滤器映射到覆盖受限制页面的 URL 模式.

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天全站免登陆