CORS origin is not working in Spring boot with Javax servlet Webfilter

I created a Rest API with java and spring boot.

Using javax.servlet.annotation.WebFilter to check the authentication. It was working fine but facing

Access to XMLHttpRequest at 'http://localhost:8080/api/' from origin 'null' has been blocked by CORS policy

issue So I use @CrossOrigin(origins = "*") in my @RestController class

when I tried to access my rest api from my frontend application it shows CROS policy error in browser console and shows 401 error in server console.

When I remove @WebFilter annotation CROS origin is working fine.

How can I fix this issue.

My Code

Spring boot version


@CrossOrigin(origins = "*")
@RequestMapping(value = "api")
public class Controller  {


public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {, args);

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);

@WebFilter(description = "Login and encoding filter", urlPatterns = {"/api/*"}) public class LoginHandleFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String token = request.getHeader("Authorization");
        chain.doFilter(request, response);

public void destroy() {

private boolean isAuthenticate(String token){
    return token.equals("Mytoken");



var http = new XMLHttpRequest():"GET", "http://localhost:8080/api/", true);
http.setRequestHeader("Authorization", "TOKEN");
http.onreadystatechange = function(){


Did I miss anything here?

Read more here:

Content Attribution

This content was originally published by Naveen at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: