I am using spring 4.1.6 release version on was 8.5 for jackson jersery rest service. This has no web.xml. it is done thro WebApplicationInitializer class.Now i would like to implement swagger UI, I googled and didnt find any examples that fit my exact scenario. everyone is providing examples that is for rest controller thro spring mvc. i would like to know how to do it thro jackson jersey in spring4. please advise
#Bean
public SwaggerConfig swaggerConfig(){
return new SwaggerConfig();
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
}
using this swagger-ui is enabled with spring MVC
Related
We are facing one issue in loading swagger ui. Out project is built on spring web flux and integrated with springdoc-openapi-webflux-ui. Whenever we try to load the swagger url, spring web flux returns partial js and css response(swagger-ui.css, swagger-ui-bundle.js).
Please let us know what should be the reason for this partial response from spring web flux
Which version of swagger are you using?
You also might check this doc:
https://github.com/springfox/springfox#migrating-from-earlier-snapshot
For me, it worked with the following code
#Configuration
#EnableWebFlux
public class SwaggerConfig implements WebFluxConfigurer {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes( Mono.class, Flux.class, Publisher.class)
.select()
.paths( PathSelectors.any())
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.build();
}
}
I have an apache wicket web application. In that, I want to integrate swagger UI. Is there any integration with the apache wicket. If anyone works on apache wicket and if you go through with swagger UI then please share your thoughts.
In my case all the api manage through the mountResource(name, staticResourceRefernce) method.
I am trying to add a Docket object in WebMarkupContainer.
public class SwaggerUiPage extends WebPage {
public static final SwaggerUiPageResource PAGE_RESOURCE = new SwaggerUiPageResource();
private IModel<Docket> model;
#Override
protected void onInitialize() {
super.onInitialize();
model.setObject(postsApi());
add(new WebMarkupContainer("swagger",model));
}
#Bean
public Docket postsApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
.select()
.apis(RequestHandlerSelectors.basePackage("com.app"))
.paths(PathSelectors.ant("/api/*"))
.build();
return docket;
}
}
This is the swagger-ui.html page
Thank you
back in 2017 I've tried to provide an integration with rest-annotations module and Swagger. I never had the chance to finish this work so I just came to a partial implementation using a SwaggerResource to expose API information and a SwaggerUtils class to extract rest endpoints information. If you want you can take a look at the code here:
https://github.com/bitstorm/core/commits/swagger-integration
I use spring security in spring cloud gateway. cloud version is Finchely.SR2 and spring boot version is 2.0.x
Then i set two role in one matcher like this:
.pathMatchers("/apis/**").hasRole("TEST1")
.pathMatchers("/apis/**").hasRole("TEST2")
but, when i startup application and do test, just TEST1 role can access. TEST2 role get FORBIDDEN 403 response.
I know in spring-boot-starter-web with spring-security, it has any method like
.antMatchers("/apis/**").hasAnyRole("TEST1", "TEST2")
Does webflux spring security has any API like hasAnyRole(String...roles) to use?
There isn't one available in the base APIs from Spring Security, however I've been using the following for anyAuthority,
public class HasAnyAuthority<T> implements ReactiveAuthorizationManager<T> {
private final Collection<String> allowedAuthorities;
public HasAnyAuthority(Collection<String> allowedAuthorities) {
this.allowedAuthorities = allowedAuthorities;
}
#Override
public Mono<AuthorizationDecision> check(final Mono<Authentication> authentication,
T object) {
return authentication.filter(Authentication::isAuthenticated)
.flatMapIterable(Authentication::getAuthorities)
.map(GrantedAuthority::getAuthority).any(allowedAuthorities::contains)
.map(AuthorizationDecision::new)
.defaultIfEmpty(new AuthorizationDecision(false));
}
with usage like,
.access(new HasAnyAuthority<>(allowedAuth.getAuthorities())
hasAnyRole and hasAnyAuthority will be available in WebFlux in Spring Security 5.2.0.
You can try them out now in 5.2.0.M3.
The syntax is the same
.pathMatchers("/apis/**").hasAnyRole("TEST1", "TEST2")
If it helps anyone
.pathMatchers("/apis/**")
.access((mono, context) -> mono.map(auth -> auth.getAuthorities().stream()
.filter(e -> (e.getAuthority().contains(TEST1) || e.getAuthority().contains(TEST2)))
.count() > 0)
.map(AuthorizationDecision::new))
I am trying to build a web service using WebFlux. When I tried to configure Spring Security with Spring WebFlux, the requests are not intercepted by Spring Security. My Spring Security config is:
#EnableWebFlux
#EnableWebFluxSecurity
#Configuration
public class WebConfig {
#Bean
public MapUserDetailsRepository userDetailsRepository() {
UserDetails cust =
User.withUsername("user1").password("password")
.roles("USER").build();
UserDetails admin =
User.withUsername("admin1").password("password")
.roles("ADMIN").build();
return new MapUserDetailsRepository(cust, admin);
}
#Bean
public SecurityWebFilterChain springWebFilterChain(
HttpSecurity httpSecurity) {
return httpSecurity.authorizeExchange().anyExchange().
authenticated().and().build();
}
}
One way is to use method security. You need to add #EnableReactiveMethodSecurity to your configuration class and then secure handler component methods with annotations, such as #PreAuthorize("isAuthenticated()")
This is how I managed to get this working with Spring Boot 2.0.0.M4, but again this may depend on what kind of request handling you are doing.
This is an issue when using Spring Security with WebFlux. The workaround is posted here: https://jira.spring.io/browse/SPR-16144
Is it possible to use swagger as a documentation/testing tool for APIs that use OAuth2? I don't see anything on the swagger site (or anywhere else for that matter). Every usage I've seen uses either an API key, HTTP basic, or cookies.
I have been working along the same lines. Swagger will accept any header or URL defined api key or token. Adding a validation helper to the api and app is a standard approach.
Oauth does require a HTML review and or login to start the handshake aouth process. This means that a swagger api will need to support a web interface for a standard login and scope acceptance. Rolling oauth into swagger results in a few logic loops, which long term are not easy to support.
A different approach we are exploring is the option to let the api handle and store access tokens for a number of different oauth providers; GitHub, twitter and Facebook. This might result in login loops as well.
late to the party here but oAuth support is now in 1.3.0-RC1 of swagger-core. The javascript library which can support oAuth was released yesterday in swagger-js. Finally, the swagger-ui is in develop phase, and will soon have a oAuth implicit and server flow.
the blog´s post http://developers-blog.helloreverb.com/enabling-oauth-with-swagger/ cited by #fehguy shows an example of java code to include the authorization data in json generated by swagger, however my question was where it should be included with app with Spring, JAXRS and CXF. I didn´t find it in CXF + JAXRS Sample :https://github.com/swagger-api/swagger-core/tree/master/samples/java-jaxrs-cxf
However, looking for a bit more and gotcha !
https://github.com/swagger-api/swagger-core/blob/master/samples/java-jersey-spring/src/main/resources/beans-asset-ws.xml
Is necessary include a Bean with a class called Bootstrap (extends HttpServlet) and a static block !
Opinion: Maybe it would be more “spring-friendly” loaded from annotations by SwaggerConfig Scanner in Rest class instead a static block in a servlet.
#Configuration
public class SwaggerConfiguration {
#Bean
#DependsOn("jaxRsServer") //org.apache.cxf.endpoint.Server bean
public ServletContextInitializer initializer() {
return new ServletContextInitializer() {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
BeanConfig scanner = (BeanConfig) ScannerFactory.getScanner();
Swagger swagger = scanner.getSwagger();
servletContext.setAttribute("swagger", swagger);
}
};
}
#Bean
public Feature swaggerFeature() {
XSwagger2Feature feature = new XSwagger2Feature();
return feature;
}
#Bean
public FilterRegistrationBean swaggerApiFilter() {
ApiOriginFilter filter = new ApiOriginFilter();
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registrationBean;
}
public static class XSwagger2Feature extends Swagger2Feature {
#Override
protected void addSwaggerResource(Server server) {
super.addSwaggerResource(server);
BeanConfig scanner = (BeanConfig) ScannerFactory.getScanner();
Swagger swagger = scanner.getSwagger();
swagger.securityDefinition("api_key", new ApiKeyAuthDefinition("api_key", In.HEADER));
swagger.securityDefinition("petstore_auth",
new OAuth2Definition()
.implicit("http://petstore.swagger.io/api/oauth/dialog")
.scope("read:pets", "read your pets")
.scope("write:pets", "modify pets in your account"));
}
}
}
IOdocs from mashery seems to support OAuth, but it's quite different from swagger (redis, node, etc.). It's available on github.