How do I enable CORS headers in the Swagger /v2/api-docs offered by Springfox Swagger? - spring

I have the following file in my project:
#Configuration
#Order(Ordered.LOWEST_PRECEDENCE)
public class SwaggerConfig {
#Bean
public Docket apiSwagger2Documentation() { .... }
}
And in the Application.java there is:
#SpringBootApplication
#ComponentScan(basePackages = { ... })
#EnableSwagger2
public class Application {
...
}
The Swagger JSON is available under /v2/api-docs, that works fine.
What I would like to do, is to enable CORS headers for that endpoint.
For my own controllers, I have added #CrossOrigin to the controller classes, those APIs then have CORS headers, that works fine. But for the Swagger JSON URL I haven't written a controller myself, so I cannot use that annotation.
I have added the following method to the SwaggerConfig, as described in "Global CORS Configuration" in CORS support in Spring Framework.
#Bean
public WebMvcConfigurer corsConfigurer() {
System.out.println("*** corsConfigurer called");
return new WebMvcConfigurerAdapter() {
#Override public void addCorsMappings(CorsRegistry registry) {
System.out.println("*** addCorsMappings called");
registry.addMapping("/v2/api-docs");
}
};
}
Both print statements get printed, so the method is being called. But when I call the URL with curl:
curl -H "Origin: foo.com" \
-H "Access-Control-Request-Method: GET" \
-X OPTIONS \
--verbose \
http://localhost:9274/v2/api-docs
The CORS headers are not in the response. (In contrast to my own controller methods, annotated with #CrossOrigin, where the response does have the CORS headers.)
I am using springfox-swagger2 version 2.7.0, and spring-boot-starter-web 1.5.2.
What can I do to enable CORS headers on the Swagger JSON API endpoint?

I think you need a generic web filter as opposed to Web Mvc configuration.
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// Allow anyone and anything access. Probably ok for Swagger spec
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/v2/api-docs", config);
return new CorsFilter(source);
}

Thanks to #Barath for the answer. The solution was to ignore the Spring documentation, that code just seems to silently not work.
(It's a shame, the Spring stuff is quite advanced when it does work, for example, the "Access-Control-Allow-Headers" response header to the pre-flight request is set based on what headers the Java API method actually offers.)
Ignore Spring's implementation of CORS and do your own. I have put the code here that worked for me:
#Component
public class CorsFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Foo, Bar, Baz");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig filterConfig) {}
#Override
public void destroy() {}
}
Remember to add any #RequestHeader that you've used in any REST method to the Access-Control-Allow-Headers response header

Related

How to add CORS to outh2/resource server in Spring Boot 2.x?

I have an oauth server and a resource server that I have created with JWT.
I also created an angular front end with 2 buttons:
The first button calls the auth server and gets the JWT token and adds it to the input box.
The second button calls the rest server with the JWT token as a bearer Authorisation http header.
Calling the 2 services from PostMan works perfectly but I cannot get the CORS setup correctly configured for the back end services.
Both buttons are giving me the below error:
Access to XMLHttpRequest at 'http://localhost:8085/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
I added all 3 of these projects to my public github repo.
I have tried to add CORS with several ways:
The config on the resource rest service is smaller so I will outline that here
I tried adding the default .cors() on the HttpSecurity as well as setting it manually in the corsConfigurationSource() method.
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and().authorizeRequests().anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
//I tried manually configured the cors as well
/*http.csrf().disable()
.cors().configurationSource(corsConfigurationSource())
.and().authorizeRequests().anyRequest().authenticated();
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);*/
}
/* #Bean
CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
configuration.setAllowCredentials(true);
//the below three lines will add the relevant CORS response headers
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
*/
}
I also tried adding a servlet filter
#Component #Order(Ordered.HIGHEST_PRECEDENCE) public class
SimpleCorsFilter implements Filter {
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws
IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final HttpServletRequest request = (HttpServletRequest) servletRequest;
response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with, authorisation");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
#Override
public void destroy() {
} }
Just can't get it to work. Can anyone please give me some guidelines here?
Silly mistake on my end as in both my SimpleCorsFilter.java files I specified that authorisation header tags are allowed but it is not authorisation with an S but with a Z.
Changing both the files in my config server
response.setHeader("Access-Control-Allow-Headers", "content-type,
x-requested-with, Authorization");
Extends your class with withWebMvcConfigurer rather than WebSecurityConfigurerAdapter. The override the following method:
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE").allowedHeaders("*");
}
It should add the origin. You can play with '*' and make many combination. I have given you idean now it is your turn to play with this API.

Cors filter not working for spring boot

I am working on spring boot filters. I have registered the CORS bean as
#Bean
public FilterRegistrationBean simpleCORSFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
SimpleCORSFilter filter = new SimpleCORSFilter();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.applyPermitDefaultValues();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Integer.MAX_VALUE);
bean.setFilter(filter);
return bean;
}
I have written a filter class for the same.
Though the class is getting instantiated but the request from UI is failing here.
#Component
public class SimpleCORSFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCORSFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
LOGGER.info("start");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,auth-token");
if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
response.setStatus(HttpStatus.NO_CONTENT.value());
}else{
AuthenticationRequestWrapper requestAuth = new AuthenticationRequestWrapper((HttpServletRequest) request);
filterChain.doFilter(requestAuth, response);
}
LOGGER.info("end");
}
}
But still I am getting the following error
cors header ‘access-control-allow-origin’ missing
I don't think that you need bean for that. Also adding #Order(Ordered.HIGHEST_PRECEDENCE) just after #Component maybe will solve your problem. This will tell spring that this configuration should be with highest precedence. And in order to be consistent use HttpServletResponse.SC_OK instead HttpStatus.NO_CONTENT.value()
According to offcial Spring Boot documentation :
Enabling Cross Origin Requests for a RESTful Web Service
Here's an example of how to configure CORS with annotations and filters :
Enabling CORS
Controller method CORS configuration
So that the RESTful web service will include CORS access control headers in its response, you just have to add a #CrossOrigin annotation to the handler method:
src/main/java/hello/GreetingController.java
#CrossOrigin(origins = "http://localhost:9000")
#GetMapping("/greeting")
public Greeting greeting(#RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
Global CORS configuration
As an alternative to fine-grained annotation-based configuration, you can also define some global CORS configuration as well. This is similar to using a Filter based solution, but can be declared within Spring MVC and combined with fine-grained #CrossOrigin configuration. By default all origins and GET, HEAD and POST methods are allowed.
src/main/java/hello/GreetingController.java
#GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(#RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
src/main/java/hello/Application.java
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
I suggest to try using this one https://gist.github.com/keesun/2245179
Works for me, then add it to WebMvcConfigurer
public class Interceptors implements WebMvcConfigurer {
private final CorsInterceptor corsInterceptor;
#Autowired
public Interceptors(CorsInterceptor corsInterceptor) {
this.corsInterceptor = corsInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.corsInterceptor).addPathPatterns("/**");
}
}
I also added #Configuration to the CorsInterceptor class
I had the same issue. I thought that my spring cors configuration was wrong, but what I realized was that the request must fulfill some requirements:
the method must be OPTIONS
the presence of the Origin header
the presence of the Access-Control-Allow-Methods header
I found that here
Try this:
1-Just add the #CrossOrigin annotation to your controller
2-Send your request with this 2 headers using OPTIONS method:
Access-Control-Request-Method:GET
Origin:*
You should get your Access-Control-Allow-Origin:*
Juani

Spring security, cors error when enable Oauth2

I'm getting an error while querying my oauth/token endpoint.
I've configured cors enable for my resource / also tried to allow all resources but nothing worked.
XMLHttpRequest cannot load http://localhost:8080/oauth/token. Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:1111' is therefore not allowed
access. The response had HTTP status code 401.
vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at CatchSubscriber.selector (app.js:7000)
at CatchSubscriber.error (vendor.js:36672)
at MapSubscriber.Subscriber._error (vendor.js:282)
at MapSubscriber.Subscriber.error (vendor.js:256)
at XMLHttpRequest.onError (vendor.js:25571)
at ZoneDelegate.invokeTask (polyfills.js:15307)
at Object.onInvokeTask (vendor.js:4893)
at ZoneDelegate.invokeTask (polyfills.js:15306)
at Zone.runTask (polyfills.js:15074)
defaultErrorLogger # vendor.js:1837
ErrorHandler.handleError # vendor.js:1897
next # vendor.js:5531
schedulerFn # vendor.js:4604
SafeSubscriber.__tryOrUnsub # vendor.js:392
SafeSubscriber.next # vendor.js:339
Subscriber._next # vendor.js:279
Subscriber.next # vendor.js:243
Subject.next # vendor.js:14989
EventEmitter.emit # vendor.js:4590
NgZone.triggerError # vendor.js:4962
onHandleError # vendor.js:4923
ZoneDelegate.handleError # polyfills.js:15278
Zone.runTask # polyfills.js:15077
ZoneTask.invoke # polyfills.js:15369
With Postman everything works perfect.
My cors security configuration:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.allowCredentials(true);
}
}
also tried to add http://localhost:1111 in allowed origins
Code in Postman:
require 'uri'
require 'net/http'
url = URI("http://localhost:8080/oauth/token")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"
response = http.request(request)
puts response.read_body
After a lot of struggling i've overrided method configure(WebSecurity web) of class WebSecurityConfigurerAdapter because Authorization server configures this by itself and i just haven't found another solution. Also you need to permitAll "/oauth/token" Http.Options method. My method:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}
After this we need to add cors filter to set Http status to OK. And we can now intecept Http.Options method.
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
#WebFilter("/*")
public class CorsFilter implements Filter {
public CorsFilter() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
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 {
}
}
I found a way to fix the 401 error on Spring Security 5 and Spring Security OAuth 2.3.5 without turning off security for all OPTIONS requests on the token endpoint.
I realized that you can add a security filter to the token endpoint via the AuthorizationServerSecurityConfigurer. I tried adding a CorsFilter and it worked. The only problem I have with this method is I couldn't leverage Spring MVC's CorsRegistry. If anyone can figure out how to use the CorsRegistry, let me know.
I've copied a sample configuration for my solution below:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
#Configuration
#EnableAuthorizationServer
public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
//... other config
#Override
public void configure(AuthorizationServerSecurityConfigurer security) {
//... other config
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.applyPermitDefaultValues();
// Maybe there's a way to use config from AuthorizationServerEndpointsConfigurer endpoints?
source.registerCorsConfiguration("/oauth/token", config);
CorsFilter filter = new CorsFilter(source);
security.addTokenEndpointAuthenticationFilter(filter);
}
}
This worked for me
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
{
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.applyPermitDefaultValues();
// add allow-origin to the headers
config.addAllowedHeader("access-control-allow-origin");
source.registerCorsConfiguration("/oauth/token", config);
CorsFilter filter = new CorsFilter(source);
security.addTokenEndpointAuthenticationFilter(filter);
}
}
You could extend the AuthorizationServerSecurityConfiguration and override the void configure(HttpSecurity http) method to implement a custom cors configuration while leaving the rest untouched.
Here's an example:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration;
import org.springframework.web.cors.CorsConfiguration;
public class MyAuthorizationServerSecurityConfiguration extends AuthorizationServerSecurityConfiguration {
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(request -> {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedMethod("POST");
configuration.addAllowedHeader("Content-Type");
return configuration;
}));
}
}
And then, instead of using the default annotation #EnableAuthorizationServer which pulls in the default configuration class you can import the relevant classes on your own:
#Import({AuthorizationServerEndpointsConfiguration.class, MyAuthorizationServerSecurityConfiguration.class})
No need to alter any security configuration related to OPTIONS method and/or specific oauth paths.
I had CORS errors using XMLHttpRequest to send POST /logout requests (Keycloak and Spring Cloud OidcClientInitiatedServerLogoutSuccessHandler), so I used HTML form instead:
<form action="/logout" method="post">
<button>Logout</button>
</form>
it works without any issues and no CORS config is needed.

How to handle CORS URLs on Prod/Dev environments?

In our Spring Boot app, we made the first deployment on our Quality environment and now we want to make it simple defining URLs to accept petitions from our FrontEnd application.
We build our application with maven and then we execute it with the command
java -Dspring.profiles.active=prod -jar myapp-0.0.1-SNAPSHOT.jar
We thought we could set the URL on the application.properties/application-prod.properties file, but this does not work as in execution time it is null. Another workaround would be somehow to get the parameter -Dspring.profiles.active=prod we pass when running the application and then take one URL or another but this seems to be a little dirty...
So what do you guys would do? I was impressed not finding anything on google, apparently people have different workarounds or I am searching in the wrong way.
Edit
Cross Origin info:
This is how we implemented it at first.
#CrossOrigin(origins = BasicConfiguration.CLIENT_URL)
And this is how we want to do it now with a filter with Spring Security
public class CorsFilter implements Filter, ApplicationContextAware {
#Value("${urlServer}")
private String urlServer;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", urlServer);
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");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig filterConfig) {}
#Override
public void destroy() {}
}
Of course urlServer is defined in application.properties with its corresponding metadata.
EDIT 2
How I initialize the filter:
#Bean
public FilterRegistrationBean corsFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CorsFilter());
registration.addUrlPatterns("/sessionLogin");
return registration;
}
The problem is that you CorsFilter is not a spring bean. You can eather define it like a bean, or do something like this:
#Bean
public FilterRegistrationBean corsFilter(#Value("${app.cors.url.server}") String urlServer) {
FilterRegistrationBean registration = new FilterRegistrationBean();
CorsFilter corsFilter = new CorsFilter();
corsFilter.setUrlServer(urlServer);
registration.setFilter(corsFilter);
registration.addUrlPatterns("/sessionLogin");
return registration;
}
Of course, you will need to define setter in your CorsFilter for urlServer field

Unable to generate Swagger json doc out of my spring code

I installed Swagger-UI as a standlone which being served by nginx server.
We have couple of microservices and I am trying to implement swagger json out of our spring-boot app.
So if I understand it right I need to point at swagger-ui the url to my swagger endpoint of my app in order to receive that json info.
How I did it?
on gradle:
dependencies {
compile("com.mangofactory:swagger-springmvc:0.8.8")
}
Added new configuration to my app:
#Configuration
#EnableSwagger
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
// Don't forget the #Bean annotation
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(
apiInfo()).includePatterns("/saurzcode/.*");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("SaurzCode API", "API for Saurzcode",
"Saurzcode API terms of service", "mail2saurzcode#gmail.com",
"Saurzcode API Licence Type", "Saurzcode API License URL");
return apiInfo;
}
}
and added to one of my controllers this:
#ApiOperation(httpMethod = "GET", value = "Say Hello To World using Swagger")
#RequestMapping(method = RequestMethod.GET)
String get() {
...
}
Now when I invoke my app with the following url:
http://localhost:8080/api-docs
I get:
{"apiVersion":"1.0","swaggerVersion":"1.2","info":{"title":"SaurzCode API","description":"API for Saurzcode","termsOfServiceUrl":"Saurzcode API terms of service","contact":"mail2saurzcode#gmail.com","license":"Saurzcode API Licence Type","licenseUrl":"Saurzcode API License URL"}}
How from this point i am generating the right json file and actually having my swagger ui to point at it:
As soon as I enter any url into the swagger ui I get:
Can't read from server. It may not have the appropriate access-control-origin settings.
I added this in my spring client to enable cors:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
It solved but:
if I restart my spring app my browser showing again this error.
If I use incognito-mode it works again.. something with local cache.. any idea?
Thank you.
ray.

Resources