JSF中的基本安全性

Fil*_*erg 36 jsf login

我想看到一个简单的登录应用程序,而不是简单的虽然.

我想要实现的是对JSF如何工作的理解,我已经开发了很多ASP.NET,你可以在其中找到代码,在那里你可以检查是否在登录时创建了会话.

JSF中的类似解决方案会很棒.

这基本上就是我想要实现的目标:

  • 登录页面
  • 如果好的话
    • 创建会话并返回"成功"
  • 如果失败
    • 返回"失败"

("成功"和失败被映射到faces-config.xml)

在成功页面我希望确定用户已登录,因此如果您没有正确的会话,则应该无法导航到"success.jspx".

McD*_*ell 46

除了能够使用rendered基于角色的安全性的组件属性之外,核心JSF中没有固有的身份验证功能.

默认情况下,JSF应用程序依赖于与包含它的Web组件相同的容器管理安全机制(JEE5教程).像Seam这样的第三方框架可以提供替代方案.

如果要添加自己的应用程序安全性,servlet过滤器是更简单的机制之一.

此过滤器保护restricted目录中的资源,web.xml如下所示:

  <filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>restricted.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/restricted/*</url-pattern>
  </filter-mapping>
Run Code Online (Sandbox Code Playgroud)

过滤器类实现:

public class AuthenticationFilter implements Filter {
  private FilterConfig config;

  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
    if (((HttpServletRequest) req).getSession().getAttribute(
        AuthenticationBean.AUTH_KEY) == null) {
      ((HttpServletResponse) resp).sendRedirect("../restricted_login.faces");
    } else {
      chain.doFilter(req, resp);
    }
  }

  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }

  public void destroy() {
    config = null;
  }
}
Run Code Online (Sandbox Code Playgroud)

登录bean定义于faces-config.xml:

public class AuthenticationBean {
  public static final String AUTH_KEY = "app.user.name";

  private String name;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }

  public boolean isLoggedIn() {
    return FacesContext.getCurrentInstance().getExternalContext()
        .getSessionMap().get(AUTH_KEY) != null;
  }

  public String login() {
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
        AUTH_KEY, name);
    return "secret";
  }

  public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
        .remove(AUTH_KEY);
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)

页面中的JSF登录表单restricted_login.jsp:

  <f:view>
    <p><a href="restricted/secret.faces">try to go to secret
    page</a></p>
    <h:form>
    Username:
    <h:panelGroup rendered="#{not authenticationBean.loggedIn}">
        <h:inputText value="#{authenticationBean.name}" />
        <h:commandButton value="login"
          action="#{authenticationBean.login}" />
      </h:panelGroup>
      <h:commandButton value="logout"
        action="#{authenticationBean.logout}"
        rendered="#{authenticationBean.loggedIn}" />
    </h:form>
  </f:view>
Run Code Online (Sandbox Code Playgroud)

(选择重定向URL /机制是为了简洁而不是任何类型的最佳实践; 有关更多选项,请参阅Servlet API.)