我有一个登录过滤器,如下所示:
@WebFilter("*.xhtml")
public class LoginFiltre implements Filter {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) arg0;
HttpServletResponse res = (HttpServletResponse) arg1;
System.out.println(req.getRequestURI());
System.out.println(req.getContextPath());
Credentials credentials = (Credentials) req.getSession().getAttribute(
"credentials");
if (req.getRequestURI().contains("login")) {
System.out
.println("login olmak istiyor faces servlet e yönlendirilecek");
chain.doFilter(arg0, arg1);
} else if (credentials != null
&& credentials.getUsername().length() != 0
&& credentials.isIsloggedin()) {
System.out.println("login olmus faces servlet e yönlendiriliyor");
chain.doFilter(arg0, arg1);
} else {
System.out.println("login olmamis yönlendirilecek");
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
我希望此过滤器检查除登录页面之外的所有请求的身份验证如何将所有页面放在名为secure(login.xhtml除外)的文件夹中,并对此过滤器使用/ secure / *等前缀映射?
答案 0 :(得分:4)
此检查
if (req.getRequestURI().contains("login")) {
很弱。如果您有例如列出所有登录用户的logins.xhtml
?您允许每个 URL只包含字符“login”。您应该执行完全网址匹配。
String loginURL = req.getContextPath() + "/login.xhtml";
if (req.getRequestURI().equals(loginURL)) {
并在重定向网址中重复使用它:
res.sendRedirect(loginURL);
无关到具体问题,这个过滤器也阻塞了CSS / JS资源。因此,所有<h:outputStylesheet>
和<h:outputScript>
资源都停止运行。您也许也希望允许它们。此外,.xhtml
扩展名和您的问题历史记录表明您正在使用JSF。当会话过期或用户在另一个选项卡上注销时,此过滤器将失败,并且对JSF ajax请求没有反馈。您应该返回一个特殊的XML响应来触发JavaScript端的重定向。你可以在这个答案中找到另一个例子来涵盖这一切:Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same。
答案 1 :(得分:0)
我知道这不是你正在寻找的答案,但安全性是专业人士最好的事情之一。除非您有一组非常独特的要求,否则您应该尝试找到合适的开源库,例如Spring Security,Apache Shiro等。他们花了很多时间确保它们是实现的它们是安全的,并且它们被广泛部署,所以它们有很多眼睛。当您推出自己的安全性时,您可能会面临引入可能导致违规的错误的风险。