-2

I'm just wondering if it's possible if its possible to run one function on every incoming request to my endpoints, expect ones that the user doesn't need to be authenticated for i.e. /registerUser . I just want to check if their firebase token is correct, and this is sent in the header of the request.

I found this SO post on the topc : How to process incoming Http request in a filter to do authentication? How ever it had no answers.

Jamie
  • 23
  • 10

2 Answers2

2

You are not allowed to ask for tutorials on stack overflow, and your question is a simple yes or no answer.

So the answer to your question is yes, it can be done. But you have not provided any code, any information of exactly what you want to do, the purpose or a code example so thats the answer to your question.

Yes you can run a function on each request using a filter. I'll link the spring security jwt documentation for good measure.

Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
  • I wasn't looking for a tutorial, probably should've made that clearer, just a point in the right direction as what I was googling wasn't returning anything useful. Many thanks for the help. – Jamie Feb 28 '21 at 22:09
0

I would do something like this:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class MyFilter implements Filter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        
        String header = httpServletRequest.getHeader("YourHeader");
        // do more stuff with it
       
        filterChain.doFilter(httpServletRequest, servletResponse);        
    }

    @Bean
    public FilterRegistrationBean<MyFilter> myFilterRegistration(){
        FilterRegistrationBean<MyFilter> registrationBean
                = new FilterRegistrationBean<>();

        registrationBean.setFilter(new MyFilter());
        registrationBean.addUrlPatterns("/registerUser/*");

        return registrationBean;
    }
}

MyFilter is a filter that does whatever is needed with the request and its headers. It needs to be typecasted to HttpServletRequest because a base ServletRequest doesn't know nothing about headers. So depending on the application you may need to do type check.

Then I define a bean of type FilterRegistrationBean that registers MyFilter and uses an url pattern to apply it only in some cases, like it seems you need.

gere
  • 1,600
  • 1
  • 12
  • 19