WebFilter基于用户角色 [英] WebFilter base on user role

查看:89
本文介绍了WebFilter基于用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的登录过滤器类:

Here is my login filter class:

@WebFilter(urlPatterns = {"/backend/*", "/frontend/manager/*", "/frontend/faculty/*"})
public class AuthorizationFilter extends HttpFilter {

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response,
            HttpSession session, FilterChain chain) throws ServletException, IOException {
        UserManagedBean user = session != null ? (UserManagedBean) session.getAttribute("userManagedBean") : null;
        if (user != null && user.isLoggedIn()) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/frontend/login.xhtml?faces-redirect=true");
        }
    }
}

反正有没有办法让过滤器类自动将用户过滤到我根据其角色配置的urlPatterns上?

Is there anyway to let the filter class auto filter user to the urlPatterns I configured base on their roles?

例如,如果我是管理员,则过滤器将允许我访问/backend/*.如果我是经理,则筛选器将允许我访问/frontend/manager/*,而不允许其他人(后端,教师)使用.

For example, if I am an admin so the filter will allow me to access to /backend/*. If I am manager, then the filter will allow me to access to /frontend/manager/* and disallow me the other ones (backend, faculty).

推荐答案

不,过滤器不支持基于角色的URL匹配.为此,您应该通过<security-constraint>条目使用Java EE内置容器管理的安全性,而不是使用servlet过滤器的自制安全性.在这些<security-constraint>条目内,您可以通过<web-resource-collection><url-pattern>声明URL模式,并通过<auth-constraint><role-name>声明角色.

Nope, filters doesn't support role-based URL matching. For that, you should be using Java EE builtin container managed security by <security-constraint> entries instead of homebrewed security using a servlet filter. Inside those <security-constraint> entries you can declare URL patterns by <web-resource-collection><url-pattern> and roles by <auth-constraint><role-name>.

在过滤器中,最好的办法是手动检查HttpServletRequest#isUserInRole().

Inside a filter, best what you can do is manually checking HttpServletRequest#isUserInRole().

  • How to handle authentication/authorization with users in a database?
  • Java EE 6 tutorial - securing web applications

这篇关于WebFilter基于用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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