アプリケーションのほとんどのページへのログイン ユーザーのみを許可する必要があります。JSF 2 を使用して Java エンタープライズ アプリケーションを開発しています。おそらく設定ファイルで?
ホームページにログイン コンポーネントがあり、ユーザーがページのいくつかの項目を除いて他の項目をクリックすると、ホームページにリダイレクトされるようにしたいと考えています。
それを行うにはさまざまな方法があります。まず、フィルターを使用してページアクセスを制御するか、jsfフェーズをリッスンするフェーズリスナーを使用できます。
それらの例を2つ挙げたいと思います;
public class SecurityFilter implements Filter{
FilterConfig fc;
public void init(FilterConfig filterConfig)throws ServletException {
fc = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession(true);
String pageRequested = req.getRequestURI().toString();
if(session.getAttribute("user") == null && !pageRequested.contains("login.xhtml")){
resp.sendRedirect("login.xhtml");
}else{
chain.doFilter(request, response);
}
}
public void destroy(){
}
}
そして、このフィルターをweb.xmlに追加する必要があります。
<filter>
<filter-name>SecurityFilter</filter-name>
<filter-class>com.webapp.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
フェーズリスナーの例;
public class SecurityFilter implements PhaseListener {
public void beforePhase(PhaseEvent event) {
}
public void afterPhase(PhaseEvent event) {
FacesContext fc = event.getFacesContext();
boolean loginPage =
fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true : false;
if (!loginPage && !isUserLogged()) {
navigate(event,"logout");
}
}
private boolean isUserLogged() {
//looks session for user
}
private void navigate(PhaseEvent event, String page) {
FacesContext fc = event.getFacesContext();
NavigationHandler nh = fc.getApplication().getNavigationHandler();
nh.handleNavigation(fc, null, page);
}
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}
したがって、リスナーを使用する場合は、これをfaces-config.xmlに追加する必要があります。注:「logout」は、faces-configで定義されているナビゲーションルールです。
<lifecycle>
<phase-listener>com.myapp.SecurityFilter</phase>
</lifecycle>
編集: ナビゲーションルール;
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>logout</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
このようなログイン方法でユーザーをセッションに参加させることができます;
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session =
(HttpSession)context.getExternalContext().getSession(true);
session.setAttribute("user", loggedUser);
それを達成する方法はたくさんあります。最も簡単でおそらく最も一般的な方法は、サーブレット フィルターを使用することです。このようなメカニズムの詳細については、「 JSF の基本セキュリティ」を参照してください。