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?
Add this Configuration class. If you already have a WebMvcConfigurer, simply add the addCorsMappings
method. The cors configuration provided through CrossOrigin
annotation should then be read and the necessary header Access-Control-Allow-Origin
will get added into Response Header.
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.