代码之家  ›  专栏  ›  技术社区  ›  ngeek

使用j_安全检查在JavaEE/JSF中执行用户身份验证

  •  155
  • ngeek  · 技术社区  · 15 年前

    我想知道,对于使用JSF2.0(如果有组件存在的话)和JavaEE6核心机制(登录/检查权限/注销)并将用户信息保存在JPA实体中的web应用程序,当前的方法是什么。OracleJavaEE教程在这方面的内容有点少(只处理servlet)。

    这是 没有 使用一个完整的其他框架,如SpringSecurity(acegi)或Seam,但如果可能的话,尝试使用新的JavaEE6平台(web概要文件)。

    4 回复  |  直到 11 年前
        1
  •  85
  •   Vítor E. Silva Souza    11 年前

    在搜索了Web并尝试了许多不同的方法之后,下面是我对Java EE 6身份验证的建议:

    设置安全域:

    http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

    注意:本文讨论了数据库中的用户和组表。我有一个用户类,其UserType enum属性通过javax.persistence注释映射到数据库。我为用户和组配置了相同的表,使用userType列作为组列,效果很好。

    使用表单身份验证:

    仍然遵循上面的博文,配置web.xml和sun-web.xml,但不要使用基本身份验证,而是使用表单(实际上,使用哪一个并不重要,但我最终使用了表单)。使用标准HTML,而不是JSF。

    然后使用上面BalusC关于从数据库初始化用户信息的提示。他建议在托管bean中这样做,从faces上下文中获取校长。相反,我使用了一个有状态会话bean来存储每个用户的会话信息,因此我注入了会话上下文:

     @Resource
     private SessionContext sessionContext;
    

    SessionInformation EJB。

    我还四处寻找注销的最佳方式。我发现最好的方法是使用Servlet:

     @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
     public class LogoutServlet extends HttpServlet {
      @Override
      protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       HttpSession session = request.getSession(false);
    
       // Destroys the session for this user.
       if (session != null)
            session.invalidate();
    
       // Redirects back to the initial page.
       response.sendRedirect(request.getContextPath());
      }
     }
    

    虽然考虑到问题的日期,我的回答真的很晚,但我希望这能帮助其他从谷歌来到这里的人,就像我一样。

    苏扎河畔

        2
  •  153
  •   SilverNak jach    8 年前

    form based authentication 使用 deployment descriptors j_security_check

    您也可以在JSF中通过使用相同的预定义字段名来实现这一点 j_username j_password 如本教程所示。

    <form action="j_security_check" method="post">
        <h:outputLabel for="j_username" value="Username" />
        <h:inputText id="j_username" />
        <br />
        <h:outputLabel for="j_password" value="Password" />
        <h:inputSecret id="j_password" />
        <br />
        <h:commandButton value="Login" />
    </form>
    

    您可以在 User getter来检查 使用者 Principal 请求中存在,如果存在,则获取 与…有关 j_用户名 .

    package com.stackoverflow.q2206911;
    
    import java.io.IOException;
    import java.security.Principal;
    
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.faces.context.FacesContext;
    
    @ManagedBean
    @SessionScoped
    public class Auth {
    
        private User user; // The JPA entity.
    
        @EJB
        private UserService userService;
    
        public User getUser() {
            if (user == null) {
                Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
                if (principal != null) {
                    user = userService.find(principal.getName()); // Find User by j_username.
                }
            }
            return user;
        }
    
    }
    

    使用者 在JSF EL中显然可以通过 #{auth.user} .

    HttpServletRequest#logout() (并设置 使用者 HttpServletRequest 在JSF中 ExternalContext#getRequest() . 您也可以完全使会话无效。

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "login?faces-redirect=true";
    }
    

    对于剩余部分(在部署描述符和领域中定义用户、角色和约束),只需按照通常的方式遵循JavaEE6教程和servletcontainer文档。


    更新 HttpServletRequest#login() 执行编程登录而不是使用 j_安全检查 在某些ServletContainer中,调度器本身可能无法访问。在这种情况下,您可以使用一个完整的JSF表单和一个带有 username password 属性和 login

    <h:form>
        <h:outputLabel for="username" value="Username" />
        <h:inputText id="username" value="#{auth.username}" required="true" />
        <h:message for="username" />
        <br />
        <h:outputLabel for="password" value="Password" />
        <h:inputSecret id="password" value="#{auth.password}" required="true" />
        <h:message for="password" />
        <br />
        <h:commandButton value="Login" action="#{auth.login}" />
        <h:messages globalOnly="true" />
    </h:form>
    

    此视图范围为托管bean,它还记得最初请求的页面:

    @ManagedBean
    @ViewScoped
    public class Auth {
    
        private String username;
        private String password;
        private String originalURL;
    
        @PostConstruct
        public void init() {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
    
            if (originalURL == null) {
                originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
            } else {
                String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
    
                if (originalQuery != null) {
                    originalURL += "?" + originalQuery;
                }
            }
        }
    
        @EJB
        private UserService userService;
    
        public void login() throws IOException {
            FacesContext context = FacesContext.getCurrentInstance();
            ExternalContext externalContext = context.getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    
            try {
                request.login(username, password);
                User user = userService.find(username, password);
                externalContext.getSessionMap().put("user", user);
                externalContext.redirect(originalURL);
            } catch (ServletException e) {
                // Handle unknown username/password in request.login().
                context.addMessage(null, new FacesMessage("Unknown login"));
            }
        }
    
        public void logout() throws IOException {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            externalContext.invalidateSession();
            externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
        }
    
        // Getters/setters for username and password.
    }
    

    使用者 在JSF EL中可以通过 #{user}

        3
  •  7
  •   Matthias Ronge    13 年前

    应该提到的是,这是一个将身份验证问题完全留给前端控制器(例如Apache Web服务器)的选项,并对HttpServletRequest.getRemoteUser()求值,后者是REMOTE_用户环境变量的JAVA表示形式。这也允许复杂的登录设计,如Shibboleth身份验证。通过web服务器过滤对servlet容器的请求对于生产环境来说是一种很好的设计,通常使用mod_jk来实现。

        4
  •  4
  •   alfonx    8 年前

    问题 HttpServletRequest.login does not set authentication state in session 已在3.0.1中修复。将glassfish更新至最新版本,即可完成。

    更新非常简单:

    glassfishv3/bin/pkg set-authority -P dev.glassfish.org
    glassfishv3/bin/pkg image-update