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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

Controller.java

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

}

Application.java

@SpringBootApplication
@ServletComponentScan
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

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

LoginHandleFilter.java

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

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
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");
    if(isAuthenticate(token)){
        chain.doFilter(request, response);
    }else{
        response.sendError(401);
    }
}

@Override
public void destroy() {
}

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

}

javascript

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

}
http.send();

Did I miss anything here?



Read more here: https://stackoverflow.com/questions/64416308/cors-origin-is-not-working-in-spring-boot-with-javax-servlet-webfilter

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: