Không có chức năng xác thực vốn có trong JSF lõi ngoài việc có thể sử dụng những thứ như thành phần rendered
thuộc tính hướng tới bảo mật dựa trên vai trò.
Theo mặc định, một ứng dụng JSF dựa trên cùng một cơ chế bảo mật do container quản lý như thành phần web có chứa nó (JEE5 tutorial). Khung bên thứ ba như Seam có thể cung cấp các lựa chọn thay thế.
Nếu bạn muốn thêm bảo mật ứng dụng của riêng mình, servlet filter là một trong những cơ chế đơn giản hơn.
lọc này bảo vệ các nguồn tài nguyên dưới restricted
thư mục theo quy định tại 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>
Việc thực hiện lớp lọc:
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;
}
}
Một bean đăng nhập quy định tại 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;
}
}
Biểu mẫu đăng nhập JSF trong th e restricted_login.jsp
page:
<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 redirect/cơ chế đã được lựa chọn cho ngắn gọn hơn bất kỳ loại thực hành tốt nhất; xem Servlet API để biết thêm các tùy chọn.)
Related: http://stackoverflow.com/questions/2206911/best-way-for-user-authentication-on-javaee-6-using-jsf-2-0/2207147#2207147 Hoặc nếu bạn đang mở cho các thư viện của bên thứ ba như Shiro, sau đó http://balusc.blogspot.com/2013/01/apache-shiro-is-it-ready-for-java-ee-6.html – BalusC