Java Filter to redirect users who are not logged in to login page

后端 未结 4 2062
执念已碎
执念已碎 2020-12-17 05:05

I was trying to make a filter to stop users who are not logged in from accessing certain pages.For this i made a filter class with the following doFilter method

相关标签:
4条回答
  • 2020-12-17 05:36

    I think you have to change your web.xml... You have to put your restricted resources to appropriate folder. In this way Filter Servlet will restrict files which allocates in "restricted" folder.(http://www.developer.com/security/article.php/3467801/Securing-J2EE-Applications-with-a-Servlet-Filter.htm) (And I think the reason of using Filter Servlet is writing own Authorization system. - in this way you have not to define your Security Constraints in the web.xml, you have to define it in Data Base ;))) )

    <!--Servlet Filter that handles site authorization.-->
    <filter>
         <filter-name>AuthorizationFilter</filter-name>
         <filter-class>examples.AuthorizationFilter</filter-class>
         <description>This Filter authorizes user access to application
                      components based upon request URI.</description>
         <init-param>
            <param-name>error_page</param-name>
            <param-value>../../login.html</param-value>
         </init-param>
    </filter>
    
    <filter-mapping>
         <filter-name>AuthorizationFilter</filter-name>
         <url-pattern>/restricted/*</url-pattern>
    </filter-mapping>
    
    0 讨论(0)
  • 2020-12-17 05:50

    After response.sendRedirect("/login.jsp"); do return;.

    0 讨论(0)
  • 2020-12-17 05:50
    chain.doFilter(req, res);
    

    What other filters are running in your Application? You send the redirect, but continue with the filter chain. I guess another filter is modifying the response again. If you stay with your filter, just return after the redirect.

    Instead of the filter, in an Java WebApp you can define your Security Constraints in the web.xml. Have a look on Security Constraints.

    Short example:

    <security-constraint>
      <web-resource-collection>
         <web-resource-name>Restricted Area</web-resource-name>
         <url-pattern>*</url-pattern>
      </web-resource-collection>
      <auth-constraint>
         <role-name>Authorized</role-name>
      </auth-constraint>
    </security-constraint>
    
    0 讨论(0)
  • 2020-12-17 05:55

    I believe that you should either invoke sendRedirect OR doFilter. E.g.

    if (requiresLogin)
      response.sendRedirect("/login.jsp");
    else
      chain.doFilter(req,resp);
    
    0 讨论(0)
提交回复
热议问题