Springfox swagger 2 not working with Spring Boot 1.5: HTTP 404 not found at /v2/api-docs - spring

I have a Spring Boot project with springfox-swagger-2 as dependency.
Versions used:
Spring Boot: 1.5.9.RELEASE
springfox-swagger-2: 2.7.0
This is the configuration:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
Docket api = new Docket(DocumentationType.SWAGGER_2);
api
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
api.apiInfo(apiInfo())
.globalOperationParameters(Lists.newArrayList(new ParameterBuilder()
.name("Example api info")
.description("description")
.modelRef(new ModelRef("string"))
.parameterType("parameter type example").build()))
;
return api;
}
#SuppressWarnings("rawtypes")
private ApiInfo apiInfo() {
Contact contact = new Contact("name", "url", "email");
Collection<VendorExtension> vendorExtensions = new ArrayList<>();
return new ApiInfo("title", "description", "version", "termsOfServiceUrl", contact, "license", "licenseUrl", vendorExtensions);
}
}
The application starts correctly, but the url /v2/api-docs gets an HTTP 404 Not Found
Even the /swagger-ui.html is not available adding the dependency for springfox-swagger-ui
The bootstrap log doesn't report any error.
I already tried to find the answer on other similar questions but any of them is working!
Any help would be appreciated.

SwaggerConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket apiDocket() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.."))
.paths(PathSelectors.any())
.build();
return docket;
}
}
SecurityConfig.java
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

try to add this to yourapplication.properties
spring.resources.add-mappings=true

Finally I have found the way to make it work.
The springfox-swagger-2 implementation has a #Controller within the class springfox.documentation.swagger2.web.Swagger2Controller.
This class implements the mapping for the url "/v2/api-docs" with this method:
#RequestMapping(
value = DEFAULT_URL,
method = RequestMethod.GET,
produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
#PropertySourcedMapping(
value = "${springfox.documentation.swagger.v2.path}",
propertyKey = "springfox.documentation.swagger.v2.path")
#ResponseBody
public ResponseEntity<Json> getDocumentation(
#RequestParam(value = "group", required = false) String swaggerGroup,
HttpServletRequest servletRequest) {
String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
Documentation documentation = documentationCache.documentationByGroup(groupName);
if (documentation == null) {
return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
}
Swagger swagger = mapper.mapDocumentation(documentation);
UriComponents uriComponents = componentsFrom(servletRequest, swagger.getBasePath());
swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
if (isNullOrEmpty(swagger.getHost())) {
swagger.host(hostName(uriComponents));
}
return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
}
As you can see, the RequestMapping expects a parameter named "group".
So, if you call the "/v2/api-docs" url without the "group" parameter, the documentation obtained is null because there are no documentations in the cache for the key "" (empty String).
I solved adding a custom Filter implemented in this way:
#Component
public class SwaggerFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String group = req.getParameter("group");
if (req.getServletPath().equals("/v2/api-docs") && group==null) {
res.sendRedirect("api-docs?group=default");
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
}
}
The mechanism is simple: without the "group" parameter, there is a redirect with the "default" group parameter.

I also stumbled upon an HTTP 404 Not Found for /v2/api-docs (but during a unit test) as part of migrating Spring Boot from version 2.0.4.RELEASE to version 2.1.6.RELEASE. The unit test passed before the "upgrade".
The unit test class had the following annotations:
#Category(UnitIntegrationTest.class)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ContextConfiguration(classes = {SecurityConfiguration.class})
#ActiveProfiles("test")
and the test configuration was defined as an inner class:
#Configuration
#EnableWebMvc
#EnableSwagger2
#Import(value = BeanValidatorPluginsConfiguration.class)
public static class TestSwaggerConfiguration {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("the.package.we.want"))
.paths(PathSelectors.any())
.build();
}
}
The fix was to specify the TestSwaggerConfiguration in the #ContextConfiguration, e.g.:
#Category(UnitIntegrationTest.class)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ContextConfiguration(classes = {SecurityConfiguration.class, GenerateDocumentationTest.TestSwaggerConfiguration.class})
#ActiveProfiles("test")
As a side note, before hitting the HTTP 404 I also had to specify
spring.main.allow-bean-definition-overriding=true
in the application-test.properties as per the Spring Boot 2.1 Release Notes.

In case the person stuck is a noob like me, make sure you have run the Maven Install command after adding the dependencies in the pom.xml file.

Related

Can not get user info with Spring Security SAML WITHOUT Spring Boot

I´m working on SAML integration in an older project but I can´t get the user information.
I've guided me with the response of this question:
https://stackoverflow.com/questions/70275050/spring-security-saml-identity-metadata-without-spring-boot
The project has these versions:
spring framework 5.3.24
spring security 5.6.10
opensaml 3.4.6
This is my code:
#Configuration
public class SAMLSecurityConfig {
private static final String URL_METADATA = "https://auth-dev.mycompany.com/app/id/sso/saml/metadata";
#Bean("samlRegistration")
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(URL_METADATA)
.registrationId("id")
.build();
return new InMemoryRelyingPartyRegistrationRepository(relyingPartyRegistration);
}
}
#EnableWebSecurity
public class WebSecurity {
#Configuration
#Order(2)
public static class SAMLSecurityFilter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.saml2Login(Customizer.withDefaults())
.antMatcher("/login/assertion")
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
}
#Controller("loginController")
public class BoCRLoginController {
#RequestMapping(value = "/login/assertion", method = {RequestMethod.POST},
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> assertLoginData(#AuthenticationPrincipal Saml2AuthenticatedPrincipal principal) {
System.out.println(principal); //here I get a null
return new ResponseEntity<>(HttpStatus.OK);
}
}
Once I did the login on okta the class: Saml2AuthenticatedPrincipal comes null value.
Could you help me to know why I received null value on the object Saml2AuthenticatedPrincipal where suppose have to receive the user information?

ServerHttpSecurity bean not found

I have a Security config class that has a SecurityWebFilterChain bean in it. This bean requires a ServerHttpSecuirty instance but spring says that it cannot find any beans of that type though there is one created in the external library (org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfiguration). I have seen this issue on a github page and they said try a different version but I am using spring boot 2.4.5 so it should work.
My Security Config class:
#Configuration
public class SecurityConfig {
#Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http,
JwtTokenProvider tokenProvider,
ReactiveAuthenticationManager reactiveAuthenticationManager) {
final String TAG_SERVICES = "/api/**";
return http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
.authorizeExchange(it -> it
.pathMatchers(HttpMethod.POST, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.PUT, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.GET, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(HttpMethod.DELETE, TAG_SERVICES).hasAnyRole("USER","ADMIN")
.pathMatchers(TAG_SERVICES).authenticated()
.anyExchange().permitAll()
)
.addFilterAt(new JwtTokenAuthenticationFilter(tokenProvider), SecurityWebFiltersOrder.HTTP_BASIC)
.build();
}
}
My application class
#ConfigurationPropertiesScan
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class TestPlatformBackendApplication {
public static void main(String[] args) {
SpringApplication.run(TestPlatformBackendApplication.class, args);
}
}
External Library Bean:
#Bean({"org.springframework.security.config.annotation.web.reactive.HttpSecurityConfiguration.httpSecurity"})
#Scope("prototype")
ServerHttpSecurity httpSecurity() {
ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity http = new ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity();
return http.authenticationManager(this.authenticationManager()).headers().and().logout().and();
}
As Toerktumlare recommended in the comments (1, 2) I added #EnableWebFluxSecurity to my security config:
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
But I also added the following to my exclude in the #SpringBootApplication annotation.
#ConfigurationPropertiesScan
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
public class TestPlatformBackendApplication {
public static void main(String[] args) {
SpringApplication.run(TestPlatformBackendApplication.class, args);
}
}

swagger 2.6.1 /swagger-resources/configuration/ui 404

I am trying to add Swagger to the Spring Framework, but I get a 404 error.
My project setting
Spring 4.2.5 + Spring Security 4.2.3
pom.xml
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!-- Swagger-UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
SwaggerConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
#Bean public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.useDefaultResponseMessages(false);
}
/** API Info */
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("Swagger Sample", "APIs Sample", "Sample Doc 0.1v", "", "Author Name", "This sentence will be display.", "/");
return apiInfo;
}
/** Swagger UI 를 Resource Handler 에 등록 */
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
context-security.xml
<intercept-url pattern="/swagger-ui.html" />
<intercept-url pattern="/swagger-resources" />
<intercept-url pattern="/webjars/** " />
<intercept-url pattern="/v2/api-docs" />
Please help me.
I hope this can help you. I use Spring Mvc, swagger2 and don´t use spring security.
Separate the configuration into 2 parts
#Configuration
#EnableSwagger2
#ComponentScan("com.demo.controller")
public class SwaggerConfig{
#Bean
public Docket apiSwagger(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Next, I create another class of configuration
#Configuration
#EnableWebMvc
#Import(SwaggerConfig.class)
public class AppSwaggerConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//enabling swagger-ui part for visual documentation
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Finally, in my WebAppInitializer class, add the AppSwaggerConfig class in the Dispatcher
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SwaggerConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
try {
loadProperties(rootContext);
} catch (IOException e) {
throw new ServletException("Properties could not be loaded", e);
}
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(AppSwaggerConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher",
new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
I seem, new Docket requires also defining few parameters. In my old project:
#Bean
public Docket configSwaggerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(new ApiInfo(environment.getProperty("api.title"), environment.getProperty("api.description"), environment.getProperty("api.version"),
environment.getProperty("api.terms"), new Contact(environment.getProperty("api.contact.name"), environment.getProperty("api.contact.url"),
environment.getProperty("api.contact.mail")), environment.getProperty("api.license"), environment.getProperty("api.license.url")))
.host(environment.getProperty("platform.url"))
.pathMapping(environment.getProperty("server.context-path"))
.protocols(newHashSet("http", "https"))
.produces(Arrays.stream(new String[] {"application/json"}).collect(Collectors.toSet()))
.tags(new Tag("public", "public tools"), new Tag("user","user tools"));
}
If you use Spring Security, don't forget to provide non-secured access to swagger:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/favicon.ico", "/swagger*", "/swagger.json", "/swagger-resources/**", "/swagger-*/**", "/webjars/**");
}
Default path /v2/api-docs does not require any interceptors and configurations. If you want to change it, add to application.properties new parameter springfox.documentation.swagger.v2.path=/new/path.
Resource handlers are used if you don't use Spring Boot.
If these advices won't help you, I can describe fully workable version with oauth security access.

swagger not detected when i remove #configuration

i try to integrate swagger into my spring boot project but i receive always an error :
"Error creating bean with name 'modelMapperImpl': Failed to introspect bean class [springfox.documentation.swagger2.mappers.ModelMapperImpl] " but when i remove #configuration from swaggerConfig swagger will not be detected ,here is my code :
WebConfig:
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE",
"PATCH");
}
}
SwaggerConfig
#EnableSwagger2
#Configuration
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
Try this approach.
#Configuration
#ConfigurationProperties(prefix = "mycompany.cors")
public class CorsSettings {
final private Logger log = LoggerFactory.getLogger(CorsSettings.class);
private List<String> origins = new ArrayList<>();
public CorsSettings() {
log.debug("construct CorsSettings");
}
public List<String> getOrigins() {
return this.origins;
}
#Bean
public WebMvcConfigurer corsConfigurer() {
if (origins != null) {
log.debug("corsOrgins=" + origins);
} else {
log.error("corsOrgins=null");
}
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins(origins.toArray(new String[origins.size()]));
}
};
}
}
Next in Config
#Configuration
public class SwaggerConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My Swagger API").description("This is a my swagger server")
.license("").licenseUrl("https://opensource.org/licenses/MIT").termsOfServiceUrl("").version("1.0.0")
.contact(new Contact("My name", "://www.mycompany.com", "myemail#mycompany.com"))
.build();
}
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.mycompany.path")).build()
.apiInfo(apiInfo());
}
}
Then in application.yml
mycompany:
cors:
origins:
- ${origin1:http://localhost:8080}
- ${origin2:http://localhost:8080}
- ${origin3:http://localhost:8080}
- ${origin4:http://localhost:8080}

Not able to get Swagger UI with spring boot

I am following the article at http://raibledesigns.com/rd/entry/documenting_your_spring_api_with.
Everything works fine but not able to integrate Swagger UI.
http://localhost:8080/docs/index.html
results in /error redirection.
I know this is an old question but maybe this will help someone with the similar problem in the future.
I followed similar tutorial to the one you mentioned and I made it work without a problem. I put my own document on how to setup a Swagger with UI in a Spring boot project couple of weeks ago. Maybe it will help you out since it is shorter and more up-to-date.
Add Maven dependencies
Stick these in your pom.xml:
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
<type>jar</type>
</dependency>
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your webapp directory and rename dist to swagger (or any name you like).
Open the index.html file inside the copied directory and change the url in the first javascript function so it points to the /api-docs endpoint:
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "/project-name/api-docs";
}
Configure Swagger
Create a SwaggerConfig.java class and configure swagger there:
#Configuration
#EnableSwagger
#EnableAutoConfiguration
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
// Root level documentation
.apiInfo(new ApiInfo("Swagger-demo JSON API", "This service provides a JSON representation the service API", null, null, null, null))
.useDefaultResponseMessages(false)
// Map the specific URL patterns into Swagger
.includePatterns("/greeting.*");
}
}
Your swagger should be up and running now. Try accessing /project-name/swagger/index.html.
I'm answering this with swagger2 configuration inside a gradle based spring boot application. Following are the configuration required for Swagger2.
Add Gradle Configuartion
Add Gradle dependencies inside build.gradle file
dependencies {
compile("io.springfox:springfox-swagger2:2.0.2")
compile("io.springfox:springfox-swagger-ui:2.0.2")
}
Swagger2 Confugration Class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build().pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder().code(500).message("500 message")
.responseModel(new ModelRef("Error")).build()))
.securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()))
.apiInfo(apiInfo());
}
#Autowired
private TypeResolver typeResolver;
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*")).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("mykey", authorizationScopes));
}
#Bean
SecurityConfiguration security() {
return new SecurityConfiguration("123456", "test-app-realm", "clientapp", "apiKey");
}
#Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("DSM API", "API for DSM", "1.0.0", "termsOfServiceUrl",
"nijo#ndimensionz.com", null, null);
return apiInfo;
}
}
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your src/main/resources/static directory and rename dist to swagger
HomeController.class
#Api(basePath = "/", value = "/", description = "Home Controller")
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "redirect:swagger-ui.html";
}
}
MyApplication.class
#SpringBootApplication
#ComponentScan(basePackageClasses = SwaggerConfig.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Configure your spring boot application with dependencies and run to see the API.
the url will be http://localhost:8080/v2/swagger-ui.html
you can also customize this as above answer.
I too face same problem. I was able to see json but not swagger ui after adding dest folder aslo. In initialize class which extends SpringBootServletInitializer I added below method then it was working perfect
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebStaticApplication.class);
}
please refer link
Here is my working configuration incase it helps anyone else
#Configuration
#EnableSwagger2
#Profile({"!production"})
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {
#Autowired
private ServletContext servletContext;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost")
.directModelSubstitute(LocalDate.class, Date.class)
.pathProvider(new RelativePathProvider(servletContext) {
#Override
public String getApplicationBasePath() {
return "/docs";
}
})
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Since I am also using Spring security, I also had to add the following to my whitelist:
private String[] swaggerWhiteList = {"/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/swagger.json", "/webjars/**"};
Then I could access it using the following url:
http://localhost:8080/docs/swagger-ui.html

Resources