How to disable endpoint based on environment in spring boot - spring

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);
}
}

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() {
}
}

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

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);
}
}
}

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())
...
}

Gzip filter with Spring async

I am using the new Servlet 3 feature DefferedResult in my Spring-MVC application. I had a GZIP filter which I had to remove as DefferedResult did not work with it.
Can someone tell me if there is a GZipFilter that will work with the Spring async(DefferedResult)?
Try using the filter introduced in servlet 3 - asyncSupported
#WebFilter(servletNames = { "servletAsynFilter" }, asyncSupported=true)
public class Filter1 implements Filter {
public void init(FilterConfig fConfig) throws ServletException {}
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponseWrapper respWrap = new HttpServletResponseWrapper((HttpServletResponse)response);
chain.doFilter(request, respWrap);
}
}

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