spring-bootservlet-filtersspring-restservlet-listeners

Adding custom header to response in spring rest / spring boot


i am trying to send session id in response header in rest controller but excludepathpattern() seems not working

** the configuration class is not triggering **

i have tried changing the sevlet version but it didnt work

ContextListener

@Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        Map<String, HttpSession> map = new HashMap<>();
        context.setAttribute("activeUsers", map);

HttpSessionListener

ServletContext context = session.getServletContext();
        Map<String, HttpSession> activeUsers = (Map<String, HttpSession>) context.getAttribute("activeUsers");

        activeUsers.put(session.getId(), session);

HandlerInterceptor

ServletContext context = request.getServletContext();
        Map<String, HttpSession> activeUsers = (Map<String, HttpSession>) context.getAttribute("activeUsers");
        String sessionId = request.getHeader("sessionId");
        String requestUrl = request.getRequestURL().toString();
        if (requestUrl.contains("/getOtp") || requestUrl.contains("/validateOtp")) {
            return true;
        } else {
            if (activeUsers.containsKey(sessionId)) {
                return true;
            } else {
                response.setStatus(401);
                return false;
            }
        }

interceptorconfigurartion by extendig websecurityconfigure

@Configuration
@EnableAutoConfiguration
public class SessionInterceptorConfig implements WebMvcConfigurer  {
@Autowired
    private SessionHanlderInterceptor sessionHandlerIntercepto;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//      List<String> paths = new ArrayList<String>();
//      paths.add("/auth/*");
        registry.addInterceptor(sessionHandlerIntercepto).excludePathPatterns("/auth/**");
    }

    @Bean
    public ServletListenerRegistrationBean<CustomSessionListener> filterRegistrationBean() {
        ServletListenerRegistrationBean<CustomSessionListener> registrationBean = new ServletListenerRegistrationBean<CustomSessionListener>();
        CustomSessionListener customURLFilter = new CustomSessionListener();

        registrationBean.setListener(customURLFilter);
        registrationBean.setOrder(1); // set precedence
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean<CustomServletContextListener> filterContextRregistration() {
        ServletListenerRegistrationBean<CustomServletContextListener> registrationBean = new ServletListenerRegistrationBean<CustomServletContextListener>();
        CustomServletContextListener customURLFilter = new CustomServletContextListener();
        registrationBean.setListener(customURLFilter);
        registrationBean.setOrder(1); // set precedence
        return registrationBean;
    }

Sprinboot main class

@SpringBootApplication
public class CustomerApplication extends SpringBootServletInitializer  {

i expect to add the session id to header in response and to check for the sessionid in request


Solution

  • You can use spring web component "OncePerRequestFilter". You need to inject a bean which extends OncePerRequestFilter. Example:

    public class CustomHeaderFilter extends OncePerRequestFilter {
    
        @Override
        public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
                                     final FilterChain chain) throws IOException, ServletException {
               response.setHeader(customHeaderName, customHeaderValue);
            chain.doFilter(request, response);
        }
     }