Skip to content

Swagger with spring-security

When you work with web services it is good to have good documentation for the rest API. In this post, we add a swagger for application from previous posts. And configure it for working with spring security. All source code is available from GitHub – https://github.com/kazakovav/spring-security-jwt/tree/master/swagger.

Add required dependencies

First of all, adding dependencies to the build.gradle.kts:

val springfoxSwaggerVersion = "2.9.2"
val swaggerIoVersion = "1.5.22"

implementation("io.springfox:springfox-swagger2:$springfoxSwaggerVersion") {
    exclude(group = "io.swagger", module = "swagger-annotations")
    exclude(group = "io.swagger", module = "swagger-models")
}
implementation("io.springfox:springfox-swagger-ui:$springfoxSwaggerVersion")

implementation("io.swagger:swagger-annotations:$swaggerIoVersion")
implementation("io.swagger:swagger-models:$swaggerIoVersion")

Next, adding configuration for swagger docket:

@Configuration
class SwaggerConfiguration {

    @Bean
    fun docket(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
                .securityContexts(listOf(securityContext()))
                .securitySchemes(listOf(apiKey()))
                .useDefaultResponseMessages(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.akazakov.resource"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
    }

    private fun securityContext(): SecurityContext {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .build()
    }

    private fun apiKey(): ApiKey {
        return ApiKey("JWT", "Authorization", "header")
    }

    private fun defaultAuth(): List<SecurityReference> {
        return listOf(SecurityReference("JWT", arrayOf(
                AuthorizationScope("global", "accessEverything")
        )))
    }

    private fun apiInfo(): ApiInfo {
        return ApiInfoBuilder()
                .title("Resource service")
                .version("1.0")
                .build()
    }
}

And do not forget to add exclusions in spring security configuration:

override fun configure(web: WebSecurity) {
        web.ignoring().antMatchers("/actuator/**",
                "/csrf",
                "/error",
                "/favicon.ico",
                "/v2/api-docs**",
                "/configuration/ui",
                "/swagger-resources",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**",
                "/swagger-resources/configuration/ui",
                "/swagger-ui.html",
                "/swagger-resources/configuration/security")
    }

And of course, do not forget to add ‘@EnableSwagger2’ annotation to the application:

@SpringBootApplication
@EnableSwagger2
class ResourceServerApplication

fun main(args: Array<String>) {
	runApplication<ResourceServerApplication>(*args)
}

Test swagger

Run application and type “localhost:8080/swagger-ui.html” in the browser URL field, you will see the following window:

Let’s test the secured method. Authorize in keycloak:

POST <http://localhost:8484/auth/realms/spring-security-jwt/protocol/openid-connect/token>
Content-Type: application/x-www-form-urlencoded

client_id=spring-jwt-client&grant_type=password&scope=openid&username=test_user&password=test_user

and copy access_token to swagger. In authorization popup insert token with “Bearer ” prefix:

Execute user-info method:

And get results:

That’s all.

Happy coding!

Leave a Reply

Your email address will not be published.