OncePerRequestFilter is not called when user tries to log in with wrong credentials - spring

in my App I have the following OncePerRequestFilter but its not called when user tries to login with wrong credentials.
With correct credentials the filter is called.
Does someone know why it's not called?
#Component
public class LoginFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
if (httpServletRequest.getRequestURI().contains("/sign-in")) {
String username = httpServletRequest.getUserPrincipal().getName();
//do things here
} else {
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
}

Related

How to allow swagger ui in Spring Custom Filter along with validation

I have written the following code where I have created a Custom Filter in SpringBoot which is always passed as Request Header. Request header name licenseKey and some value. I have implemented and also allowed Swagger-UI to work. Please suggest me to follow better approach, my seniors say that it is not a good approach. I provide below the code. The task is to receive licenseKey while calling Rest end point and also we need to allow Swagger-UI without licenseKey that will be provided later as part of authorization in Swagger. Currently the code is working fine. I request for better approach. I provide below the code. I removed all import statements.
#Component
public class CustomURLFilter implements Filter {
#Autowired
private CustomUserDetailsService userDetailsService;
private static final Logger LOGGER = LoggerFactory.getLogger(CustomURLFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("########## Initiating CustomURLFilter filter ##########");
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String path = request.getRequestURI();
System.out.println("Path: "+path);
if(path.startsWith("/app-name-service/swagger-ui") || path.startsWith("/app-name-service/v3/api-docs")) {
filterChain.doFilter(request, response);
return;
} else {
String licenseKey = userDetailsService.getLicenseKey(request);
System.out.println("User License Key: "+licenseKey);
}
LOGGER.info("This Filter is only called when request is mapped for /customer resource");
//call next filter in the filter chain
filterChain.doFilter(request, response);
}
#Override
public void destroy() {
}
}

How to disable endpoint based on environment in spring boot

I have a controller comprising of a bunch of swagger endpoints. For one of the endpoint I want it to be disabled / hidden for PROD env, and the rest of them to be active for all envs. How could i get that done ?
You can use a Filter.
public class MyFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (request.getRequestURI().contains("secret") && env.getProperty("environment").equals("Production"))
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized!");
else
filterChain.doFilter(request, response);
}
}

Set cookie in every request - SPRING

Im now developing simple spring boot web app..
Is there something in spring(filter) that check every request(headers)..
I want to check if there is cookie..
If there is cookie- nothing happend..
But if there is not it would create cookie...
Do i have to do this manually, so i put this in every function?
Or can i do something like global function, that got executed with every other request?
Thanks for help.
yes you have to use filters
you can try doing something like this
public class MyCookieFilter extends GenericFilterBean {
public static final String MY_COOKIE_NAME = "your-cookie-name";
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
checkCookie(httpServletRequest, httpServletResponse);
filterChain.doFilter(servletRequest, servletResponse);
}
private void checkCookie(HttpServletRequest request, HttpServletResponse servletResponse) {
boolean cookieExists = Arrays.stream(request.getCookies()).anyMatch(cookie -> cookie.getName().equalsIgnoreCase(MY_COOKIE_NAME));
if (!cookieExists) {
String cookieValue = "your-cookie-value";
Cookie newCookie = new Cookie(MY_COOKIE_NAME, cookieValue);
servletResponse.addCookie(newCookie);
}
}
}
then add it in your security config
#Override
public void configure(HttpSecurity http) throws Exception {
http
...
.addFilter(new MyCookieFilter())
...
}

return after call doFilter() of GenericFilterBean on Spring Boot

I am using GenericFilterBean as filter on my Spring boot project.
In some case, I want to pass next filter on my filter logic.
My filter looks like below;
public class MyFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (anyCondition){
chain.doFilter();
return;
}
if (anyCondition){
chain.doFilter();
return;
}
if (anyCondition){
chain.doFilter();
return;
}
chain.doFilter();
}
}
it calls other chain.doFilter() if I don’t return, that’s way I return.
İt will caused any problem to return after call chain.doFilter() ?
Is it right way to handle this situations?
Your code will always call chain.doFilter (not doChain)
for example
public class MyFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//this gets executed before other filters
some code here
//now we execute other filters
chain.doFilter(request, response);
//this code gets executed after the 'next' filters are done
some code here
}
}
But your code always executes the next filter and then is complete.
Your code is fine, but you can do it with an if then else statement instead
public class MyFilter extends GenericFilterBean {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (condition1){
//do something for condition1
} else if (condition2) {
//do something for condition2
} else if (condition3) {
//do something for condition3
}
chain.doChain();
}
}

Spring MVC / Security - "Store is closed" Security Filter

I have a Spring MVC webapp that uses Spring Security. I want to add "Store is closed" functionality - i.e. if I set the store to be closed, regardless of where the user tries to navigate on my site they will end up on the page saying "Store is closed".
I have implemented a Security Filter as follows (and can wire it in fine):
public class ClosedFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
if(storeIsClosed()) {
//do something useful here
}else {
chain.doFilter(req, response);
}
}
}
But am unsure what to put in the "//do something useful here" bit. I have tried:
throw new StoreIsClosedException(); //extends RuntimeException
but I can't then map my exception to my view. I also tried
response.redirect("myClosedView");
with no luck. What I want is something conceptually like:
return new ModelAndView("closed");
Thanks.
I ended up with a solution, I changed my filter to:
public class ClosedFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
if (isClosed()) {
final String path = req.getContextPath()+"/closed.do";
if(!path.equals(req.getRequestURI())) {
response.sendRedirect(path);
return;
}
}
chain.doFilter(req, response);
}
}
and then added this to my security.xml
<intercept-url pattern="/closed.do*" access="permitAll"/>

Resources