Unable to generate Swagger json doc out of my spring code - spring

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.

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.

Spring boot 2 adding cache response headers without using Spring security

I am using Spring boot 2 and in application.properties file, I have specified the cache values as below :
spring.resources.cache.cachecontrol.max-age=0
spring.resources.cache.cachecontrol.no-cache=true
spring.resources.cache.cachecontrol.must-revalidate=true
spring.resources.cache.cachecontrol.no-store=true
Except for max-age, none of the headers is visible in the chrome developer tools network tab.
In my application I am making a Get request and getting ResponseEntity<Long> as response back.
Is there something else needs to be done to add these cache-headers in the response ?
I used filter for setting HttpHeader. It can give you fine grained control over setting value and validate your request before passing to controller.
public class CORSFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
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");
res.setHeader("Cache-Control","no-cache,no-store,must-revalidate,private,max-age=0");
res.setHeader("Pragma","no-cache");
res.setDateHeader("Expires",0);
if(!res.containsHeader("X-FRAME-OPTIONS"))
res.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}

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

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

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

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

Resources