Servlet Filter
SØAD allows you to define Servlet Filters that intercept incoming requests. Filters can be used to apply authentication checks, preprocess requests, or enforce headers.
How to Configure a Filter
To register a servlet filter, define it in your sufia.properties file:
authis the filter name (each filter must have a unique name).mappingdefines the URL pattern the filter applies to (e.g.,/*applies to all requests).filepoints to the Python file containing the filter logic.
You can define multiple filters by adding more entries with different names and mappings.
Filter File Example: auth_filter.py
The filter class must implement the Java jakarta.servlet.Filter interface through Jython. This allows the filter to be managed by the servlet container and invoked automatically for each matching request.
from jakarta.servlet import Filter
class Auth_filter(Filter):
def doFilter(self, request, response, chain):
session = request.getSession()
user_id = session.getAttribute("user_id")
# If url is for login, allow it to proceed without authentication
if request.getRequestURI().endswith("/t/auth/login"):
chain.doFilter(request, response)
return
# Check if user is authenticated
if user_id is None:
# If not authenticated, redirect to login page
response.sendRedirect(request.getContextPath() + "/t/auth/login")
return
# If authenticated, continue processing the request
chain.doFilter(request, response)
How It Works
- The
doFilter(request, response, chain)method is called automatically for each request that matches the configured mapping. - The filter has access to the HTTP request and response objects.
- If the request should not proceed (e.g. user not authenticated), it can redirect or block.
- To allow the request to continue to the next filter or target transaction, call
chain.doFilter(request, response).
Important Note
To avoid infinite loops, ensure your filter logic does not redirect to a URL that triggers the same filter repeatedly. For example, if your filter redirects to a login page, ensure that the login URL is excluded from the filter's mapping.
Filters give you full control to extend the request lifecycle without modifying each transaction manually. You can create multiple filters and map them to specific URL patterns, enabling clean separation of concerns in your application.