Spring Boot: Swagger2 configuration

Swagger2 is a visual interactive document for your api’s. When swagger is configured on your system, it automatically grabs all of your api’s and displays you in a interactive web page.

1. Dependency

Add two dependencies for swagger.

<!--SWAGGER-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

2. Configuration

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${app.client.id}")
    private String clientId;
    @Value("${app.client.secret}")
    private String clientSecret;

    @Value("${applicationName}")
    private String applicationName;

    @Value("${baseUrl}")
    private String appUrl;

    @Value("${contactEmail}")
    private String contactEmail;

    @Value("${host.full.dns.auth.link}")
    private String authLink;


    @Bean
    public Docket api() {

        List<ResponseMessage> list = new java.util.ArrayList<>();
        list.add(new ResponseMessageBuilder().code(500).message("500 message")
                .responseModel(new ModelRef("Result")).build());
        list.add(new ResponseMessageBuilder().code(401).message("Unauthorized")
                .responseModel(new ModelRef("Result")).build());
        list.add(new ResponseMessageBuilder().code(406).message("Not Acceptable")
                .responseModel(new ModelRef("Result")).build());

        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build().securitySchemes(Collections.singletonList(securitySchema()))
                .securityContexts(Collections.singletonList(securityContext())).pathMapping("/")
                .useDefaultResponseMessages(false).apiInfo(apiInfo()).globalResponseMessage(RequestMethod.GET, list)
                .globalResponseMessage(RequestMethod.POST, list);



    }



    private OAuth securitySchema() {

        List<AuthorizationScope> authorizationScopeList = newArrayList();
        authorizationScopeList.add(new AuthorizationScope("read", "read all"));
        authorizationScopeList.add(new AuthorizationScope("trust", "trust all"));
        authorizationScopeList.add(new AuthorizationScope("write", "access all"));

        List<GrantType> grantTypes = newArrayList();
        GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(authLink + "oauth/token?client_id=" + this.clientId + "&client_secret=" + this.clientSecret);

        grantTypes.add(creGrant);

        return new OAuth("oauth2schema", authorizationScopeList, grantTypes);

    }

    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant("/user/**"))
                .build();
    }

    private List<SecurityReference> defaultAuth() {

        final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3];
        authorizationScopes[0] = new AuthorizationScope("read", "read all");
        authorizationScopes[1] = new AuthorizationScope("trust", "trust all");
        authorizationScopes[2] = new AuthorizationScope("write", "write all");

        return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));
    }

    @Bean
    public SecurityConfiguration securityInfo() {
        return new SecurityConfiguration(clientId, clientSecret, "", "", "", ApiKeyVehicle.HEADER, "", " ");
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(this.applicationName + " Api").description("")
                .termsOfServiceUrl(this.appUrl + "/terms")
                .contact(new Contact(this.applicationName + " Admin", this.appUrl, this.contactEmail))
                .license("MIT").licenseUrl(this.appUrl + "/license").version("1.0.0").build();
    }
}

 

To make this configuration work, add some properties on application.properties file to bind fields that we declared in this configuration class.

Like

app.client.id=76rehuwiy8736r54w739yh
app.client.secret=jkhfdeuiry847yr3our98
applicationName=MyApplication
baseUrl=https://www.example.com
[email protected]
host.full.dns.auth.link=

3. Security

Now you have to exclude/configure access to swagger endpoint. Open your class that extends WebSecurityConfigurerAdapter and configure access to this endpoint according to your requirement on configure(HttpSecurity http) block. Here I’m just excluding swagger endpoint from security.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-ui.html"
                )
                .permitAll();
   
}

4. Verification

Run your app and open browser. Then go to /swagger-ui.html to access the api’s.

http://localhost:8080/swagger-ui.html

Leave a Reply

Your email address will not be published. Required fields are marked *