除了能夠使用類似於基於角色的安全性的組件rendered
之外,核心JSF中沒有固有的身份驗證功能。
默認情況下,JSF應用程序依賴與包含它的Web組件相同的容器管理安全機制(JEE5 tutorial)。像Seam這樣的第三方框架可以提供替代方案。
如果您想添加自己的應用程序安全性,servlet filter是更簡單的機制之一。
<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>
過濾器類實現:
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;
}
}
的登錄豆在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;
}
}
此過濾器作爲web.xml
定義的restricted
目錄下的保護資源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>
(被選定爲簡便起見,而不是任何形式的最佳實踐的重定向URL /機制;請參閱Servlet API以獲取更多選項。)
相關:http://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0/2207147#2207147或者如果你打開到Shiro等第三方庫,然後http://balusc.blogspot.com/2013/01/apache-shiro-is-it-ready-for-java-ee-6.html – BalusC