I want to add Security Definition to my rest service using org.apache.cxf.jaxrs.swagger.Swagger2Feature. However I can not see any related method or any resource on how to do it. Below is the swagger doc which I want to generate using swagger2feature. How can I do it?
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: basic-auth-server.herokuapp.com
schemes:
- http
- https
securityDefinitions:
Bearer:
type: apiKey
name: Authorization
in: header
paths:
/:
get:
security:
- Bearer: []
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
I was facing the same problem and I couldn't find a suitable solution with CXF and its api. My solution is the following, create a class that extends the Swagger2Feature of CXF in order to override the addSwaggerResource method, to bound the security definition:
Then, as the Swagger instance has been modified after it has been loaded by the swagger api, you should "re-register" it in the context of the servlet (as I understand when I browsed the code of swagger). Have a look at io.swagger.jaxrs.config.SwaggerContextService. To do this, I had to create a new ServletContextInitializer in my servlet context:
Putting in the context the Swagger configuration previously modified with the security definition allows the swagger api to take it into account correctly. Without this, our extended Swagger2Feature would not work.
With this changes, I was able to get a swagger.yaml file as the one you are expecting, especially the following part:
I am using this solution in a Spring Boot application, here is my complete swagger configuration class, in case it helps someone:
I'm not using Spring Boot, but I copied @Naoj's approach. (Thanks!)
For those not on Spring Boot, you can accomplish this in a startup servlet that loads after the CXF servlet. You can also avoid extending the class if you just modify the Swagger instance when you grab it.
So in web.xml:
Then the servlet code: