CORS in Spring Boot with Spring Security + React - java

After deploy I got problem with CORS. I can access data directly from my API but when trying fetch it from React app I got problem as in an image:
I tried to add filters to add to every header Access-Control-Allow-Origin and it now return data from API and I can see it in browsers console but react cant get it
WebSecurity.java
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();
http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and();
http.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
#Bean
public FilterRegistrationBean crosFilterRegistration(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new MyCorsFilter());
registrationBean.setName("CORS Filter");
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("https://*************"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Access-Control-Allow-Origin",
"Access-Control-Request-Method", "Access-Control-Request-Headers", "Origin",
"Cache-Control", "Content-Type"));
configuration.setAllowCredentials(true);
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
MyCorseFiltre.java
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "https://**************");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig config) throws ServletException {
}
}
Application.java
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("https://*************");
}
};
}

This row
response.setHeader("Access-Control-Allow-Origin", "https://**************");
adds the duplicated header. So does this row:
configuration.setAllowedOrigins(Collections.singletonList("https://*************"));
One of them is enough. Preferably the latter. The same goes for most of the CORS config you have.

Related

Why I don't get authorization header?

I use the Spring framework. If I send a request using postman, I get the authorization header, but if I use Axois I don't get it. What is the problem?
Axois send:
axios({
method: 'get',
url: 'http://localhost:8081/api/posts',
headers: { 'Authorization': 'Bearer_' + localStorage.getItem("username")} // Cookies.get('Token')
})
Cors in spring
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.exposedHeaders("Authorization", "authorization")
.allowedOrigins("*")
.allowedMethods("*")
.allowCredentials(false).maxAge(3600);;
}
Spring security config:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(LOGIN_ENDPOINT, REGISTRATION_ENDPOINT).permitAll()
.antMatchers(ADMIN_ENDPOINT).hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.apply(new JwtConfigurer(jwtTokenProvider));
}
Get the headers here:
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) req;
Map<String, List<String>> headersMap = Collections.list(httpRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(
Function.identity(),
h -> Collections.list(httpRequest.getHeaders(h))
));
Postman request
Headers with postman
Headers with Axios
I added Bean:
#Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config.applyPermitDefaultValues());
return source;
}

How do I handle CORS in Spring Boot Oauth2 Resource Server with password grant

Details:
I am using spring boot oauth2 resource server which is giving me CORS even after trying different approaches to filter this off.
How do my code look ?
Its a simple resource server with spring boot with spring-cloud-starter-oauth2 and spring-cloud-starter-security as two major dependencies.
I have used java annotations to make this a resource server :
#CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = "*")
#RestController
#RequestMapping("/api/v1")
#EnableResourceServer
Here is how I tried to resolve this :
I tried to add a custom filter which skips further filter calls with code below. After this I got "Authorization Header not allowed in preflight request on browser". After adding CORS everyehere extension to my browser my requests succeeded.
#EnableWebSecurity(debug = true)
#Order(Ordered.HIGHEST_PRECEDENCE)
public class WebSecurityConfig implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Expose-Headers", "Location");
System.out.println(request.getMethod());
System.out.println("-----------------");
if(!request.getMethod().equals("OPTIONS")) {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {}
#Override
public void destroy() {}
}
I had the same problem and
that was the resolution.
public class ResourceServerCustom extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().disable().authorizeRequests().antMatchers("/oauth/token/**").permitAll()
.anyRequest().authenticated().and().exceptionHandling()
.authenticationEntryPoint(new AuthExceptionEntryPoint());
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}
}
And others configs.
public class WebSecurityCustom extends WebSecurityConfigurerAdapter {
public TokenStore tokenStore;
#Bean
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**",
"/configuration/security", "/swagger-ui.html", "/webjars/**");
web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
}
public class CorsFilterCustom extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
}
public class AuthorizationServerCustom implements AuthorizationServerConfigurer {
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
}
}
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
throws ServletException, IOException {
final Map<String, Object> mapBodyException = new HashMap<>();
mapBodyException.put("error", "Error from AuthenticationEntryPoint");
mapBodyException.put("message", "Message from AuthenticationEntryPoint");
mapBodyException.put("exception", "My stack trace exception");
mapBodyException.put("path", request.getServletPath());
mapBodyException.put("timestamp", (new Date()).getTime());
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), mapBodyException);
}
}
You could configure cors by adding a configuration class with different variations like this
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedMethods(Collections.singletonList("*"));
http.cors().configurationSource(request -> config);
}
}
or just disable like this
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable();
}
}

How do I allow cross origin request

I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(request, response);
}
But still he gets the error.What may be the cause.Any help is appreciated
OPTIONS https:my.domain/url 401 (Unauthorized)
when it is a POST request.
Controller code:
#RestController
public class RegistrationController {
#Autowired
#Qualifier("restTemplateUserRegitration")
private RestTemplate restTemplateUserRegitration;
#RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
public ResponseEntity<?> registerUser(#RequestBody Model ModelRequest){
Map<String, Object> Status=new HashMap<String, Object>();
FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
return ResponseEntity.ok(Status);
}
}
I also had a similar experience. We have solved the problem as follows.
This code added in securityConfiguration.
The browser will send the OPTIONS request first before sending the POST request. Therefore, when the request is sent, the authorization header value is not included in the request header, so the JWT filter judges that the user is unauthenticated.
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS);
}
Try this first, this should allow all origins, but it is security risk.
response.setHeader("Access-Control-Allow-Origin", "*");
This is one option. Not sure if its an elegant one
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
Put this in any spring bean.
You can create your own CorsConfiguration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
#Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:63342");
corsConfiguration.addAllowedHeader("Authorization");
corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
};
And add it to configuration.
.and().cors().configurationSource(corsConfigurationSource);
And try using this annotation
#CrossOrigin
You should implement a filter like this:
public class CORSFilter extends OncePerRequestFilter {
private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
LOG.info("Adding CORS Headers ........................");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
Found this from the post Cross Origin Request Blocked Spring MVC Restful Angularjs
Hope this help!

Spring API REST and Cors and AngularJS

I have probem with Spring Boot and Cors
After some searches I was able to find solutions (Spring Data Rest and Cors and How to configure CORS in a Spring Boot + Spring Security application?) which I tried but which does not solve my problem.
My code for the Authentication with JWT
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter
{
private final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);
private final String tokenHeader = "Authorization";
private final TokenUtils tokenUtils = new TokenUtils();
public AuthenticationFilter()
{
super("/api/v1/**");
tokenUtils.expiration = 86400;
tokenUtils.secret = "papipapo123popo";
}
#Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException
{
String header = httpServletRequest.getHeader(tokenHeader);
if(header == null || !header.startsWith("Bearer "))
{
log.error("Not found JWT token in request headers","Not found header Authorization");
throw new JwtTokenMissingException("No JWT token found in request headers");
}
String token = header.substring(7);
JwtAuthentication jwtAuthentication = new JwtAuthentication(token);
boolean isValid = tokenUtils.validateToken(token);
if(!isValid)
{
log.error("JWT token is expired",token);
throw new JwtTokenExpired("JWT token is expired");
}
return this.getAuthenticationManager().authenticate(jwtAuthentication);
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException
{
super.successfulAuthentication(request, response, chain, authResult);
String token = ((JwtAuthentication)authResult).getToken();
log.info("Token is authenticated : ",token);
chain.doFilter(request, response);
}
#Override
protected AuthenticationManager getAuthenticationManager()
{
return authentication -> (JwtAuthentication) authentication;
}
}
My code for Configuration security
#Configuration
#EnableWebSecurity
#EnableAutoConfiguration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
#Inject
private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
#Inject
private JwtAuthenticationProvider jwtAuthenticationProvider;
#Bean
#Override
public AuthenticationManager authenticationManager() throws Exception
{
return new ProviderManager(Arrays.asList(jwtAuthenticationProvider));
}
#Bean
public AuthenticationFilter authenticationFilter() throws Exception
{
AuthenticationFilter authenticationFilter = new AuthenticationFilter();
authenticationFilter.setAuthenticationManager(authenticationManager());
authenticationFilter.setAuthenticationSuccessHandler(new EntryPointSuccessHandler());
return authenticationFilter;
}
#Bean
public FilterRegistrationBean corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
source.registerCorsConfiguration("/**",config);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
filterRegistrationBean.setOrder(0);
return filterRegistrationBean;
}
#Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(entryPointUnauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST,"/api/auth").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationFilter(),UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
}
I always receive an error 401 refused accesse.
I am a beginner in Spring-Boot.
You can help me.
I solved my problem by adding a Class which implements Filter.
#Component
public class CorsConfig implements Filter
{
#Override
public void init(FilterConfig filterConfig) throws ServletException
{}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
String method = request.getMethod();
if(method.equals("OPTIONS") || method.equals("options"))
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
response.setStatus(200);
filterChain.doFilter(servletRequest, servletResponse);
}
else
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
filterChain.doFilter(servletRequest, servletResponse);
}
}
#Override
public void destroy()
{}
}
First class:
#Configuration
public class MyConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
Second class:
#EnableWebSecurity
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
}
}
And be happy my friend
1: Create a class WebMvcConfig extends WebMvcConfiguration and override addCorsMappings method.
2: Don't forget to make it #Configuration annotation
#Configuration
public class WebMvcCofig implements WebMvcConfigurer{
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}

Spring Security CORS filter not working

I'm using spring security with OAuth2 (version: 4.0.4.RELEASE) and spring (verison: 4.3.1.RELEASE).
I'm developing frontend in Angular and I'm using grunt connect:dev (http://127.0.0.1:9000). When I trying to login by localhost address everything working fine but from other I'm getting error:
"XMLHttpRequest cannot load http://localhost:8084/oauth/token?client_id=MY_CLIENT_ID. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:9000' is therefore not allowed access. The response had HTTP status code 401."
I have configured mapping (Overrided public void addCorsMappings(CorsRegistry registry)) in WebMvcConfigurerAdapter (like below) but it still not working for http://127.0.0.1:9000.
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:9000")
.allowedMethods("POST", "OPTIONS", "GET", "DELETE", "PUT")
.allowedHeaders("X-Requested-With,Origin,Content-Type,Accept,Authorization")
.allowCredentials(true).maxAge(3600);
Configuration based on: https://spring.io/guides/gs/rest-service-cors/
Please, point me the right directon to resolve this issue.
Hopefully, you found an answer long ago, but if not (and if anyone else finds this question searching as I was):
The issue is that Spring Security operates using filters and those filters generally have precedence over user defined filters, #CrossOrigin and similar annotations, etc.
What worked for me was to define the CORS filter as a bean with highest precedence, as suggested here.
#Configuration
public class MyConfiguration {
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://127.0.0.1:9000");
config.setAllowedMethods(Arrays.asList("POST", "OPTIONS", "GET", "DELETE", "PUT"));
config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
Sorry for long time response. I resolved the issue by configuring my CORS filter like below:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger(CORSFilter.class.getName());
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final String origin = ((HttpServletRequest) req).getHeader("Origin");
if (ofNullable(origin).isPresent() && origin.equals("http://127.0.0.1:9000")) {
LOGGER.info("CORSFilter run");
response.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:9000");
response.addHeader("Access-Control-Allow-Credentials", "true");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept,Authorization");
response.setStatus(200);
}
}
chain.doFilter(addNessesaryHeaders(request), response);
}
private MutableHttpServletRequest addNessesaryHeaders(final HttpServletRequest request) {
final MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
mutableRequest.putHeader("Accept", "application/json");
mutableRequest.putHeader("Authorization", "Basic" + " bXVzaWNzY2hvb2w6");
return mutableRequest;
}
#Override
public void destroy() {
}
}
You can try something like that
#Configuration
public class CorsConfig {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods(HttpMethod.OPTIONS.name(),
HttpMethod.PATCH.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name(),
HttpMethod.GET.name(),
HttpMethod.POST.name())
.maxAge(360);
}
};
}
}
Note: Spring version should be 4.2 or later
below worked for me.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}

Categories

Resources