Servlet Filter - Do Not Apply Filter to a Specific

I have a web application with a login screen backed by an authentication filter.

I have the following in my web.xml

<filter> <filter-name>AuthenticationFilter</filter-name> <display-name>AuthenticationFilter</display-name> <filter-class>com.mycompany.secutity.AuthenticationFilter</filter-class> </filter> 

And I have the following mapping -

 <filter-mapping> <filter-name>AuthenticationFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

But now I want to add an exception where for a specific servlet /web/MyNewServlet I want to bypass the authentication filter. How can we do this?

+6
source share
2 answers

There are two ways to do this:

  • Cancel the /* template to another template, for example /subdir/* , and thus avoid using the authentication filter from /web/MyNewServlet . This is a cumbersome process, as you may have multiple URLs in your web application that you now need to reassign. I would suggest doing this at an early stage of development or when you have too many URLs to reassign.
  • Include an exclusion rule in the software implementation of the filter. You will need to use HttpServletRequest.getServletPath and similar methods to check if the fragment contains the URL /web/MyNewServlet and then binds the filter to the next filter or servlet, instead of executing the filter body.
+5
source

By adding the idea of ​​Vineet a bit, you can add another filter, called something like DoNotNeedAuthenticationFilter, which runs before the AuthenticationFilter, and simply sets the DOES_NOT_NEED_AUTHENTICATION attribute for the request. Then AuthenticationFilter can check this attribute and pass any of its requests. You can then use the normal filter matching mechanism to apply the DoNotNeedAuthenticationFilter file to the corresponding URLs or servlets.

+4
source

Source: https://habr.com/ru/post/895634/


All Articles