Its weird, sometimes doFilter() is called once twice, once with ‘Authorization’ as null and then with actual ‘Authorization’ token. I am calling spring boot rest controller from a react fetch call.
react fetch call with headers:
const handleSubmit = (e) => {
if (validateForm()) {
const token = localStorage.getItem('token');
setIsLoading(true);
const headerList = {
'Authorization': 'Bearer ' + token
}
e.preventDefault();
const city = { cityName, cityDescription, stateId };
fetch(API_HOST_URL + "/cities/", {
method: "POST",
headers: headerList,
body: JSON.stringify(city)
}).then((res) => {
onSuccessfulSave();
resetForm();
}).catch((error) => {
onFailedSave();
});
}
else {
onFailedSave();
}
}
Here is the filter code:
@Component
public class RequestFilter implements Filter {
private final JwtService jwtService;
public RequestFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
System.out.println("Request path: " + req.getRequestURI());
System.out.println("Authorization: " + req.getHeader("Authorization"));
chain.doFilter(request, response);
}
}
Why sometimes only doFilter is called twice and why sometimes it pass ‘Authorization’ header and sometimes not?