Skip to content

Commit

Permalink
store security-schemas in components as configured
Browse files Browse the repository at this point in the history
  • Loading branch information
SMILEY4 committed Nov 17, 2024
1 parent 78eee6e commit 02c91b0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ private fun Application.myModule() {

// Install and configure the "SwaggerUI"-Plugin
install(SwaggerUI) {
schemas { }
security {
// configure a basic-auth security scheme
securityScheme("MySecurityScheme") {
Expand All @@ -53,6 +54,7 @@ private fun Application.myModule() {
// if no other response is documented for "401 Unauthorized", this information is used instead
defaultUnauthorizedResponse {
description = "Username or password is invalid"
body<AuthRequired>()
}
}
}
Expand All @@ -74,6 +76,12 @@ private fun Application.myModule() {
}) {
call.respondText("Hello World!")
}

get("protected2", {
// response for "401 Unauthorized" is automatically added if configured in the plugin-config and not specified otherwise
}) {
call.respondText("Hello World!")
}
}

// route is not in an "authenticate"-block but "protected"-flag is set (e.g. because is it protected by an external reverse-proxy
Expand All @@ -96,3 +104,6 @@ private fun Application.myModule() {
}

}


class AuthRequired(val message: String)
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,21 @@ class SchemaContextImpl(private val schemaConfig: SchemaConfigData) : SchemaCont

fun addGlobal(config: SchemaConfigData) {
config.securitySchemas.forEach { typeDescriptor ->
val schema = collapseRootRef(generateSchema(typeDescriptor))
val schema = generateSchema(typeDescriptor)
rootSchemas[typeDescriptor] = schema.swagger
schema.componentSchemas.forEach { (k, v) ->
componentSchemas[k] = v
}
}
config.schemas.forEach { (schemaId, typeDescriptor) ->
val schema = collapseRootRef(generateSchema(typeDescriptor))
val schema = generateSchema(typeDescriptor)
componentSchemas[schemaId] = schema.swagger
schema.componentSchemas.forEach { (k, v) ->
componentSchemas[k] = v
}
}
}

private fun collapseRootRef(schema: CompiledSwaggerSchema): CompiledSwaggerSchema {
if (schema.swagger.`$ref` == null) {
return schema
} else {
val referencedSchemaId = schema.swagger.`$ref`!!.replace("#/components/schemas/", "")
val referencedSchema = schema.componentSchemas[referencedSchemaId]!!
return CompiledSwaggerSchema(
typeData = schema.typeData,
swagger = referencedSchema,
componentSchemas = schema.componentSchemas.toMutableMap().also {
it.remove(referencedSchemaId)
}
)
}
}

fun add(routes: Collection<RouteMeta>) {
collectTypeDescriptor(routes).forEach { typeDescriptor ->
val schema = generateSchema(typeDescriptor)
Expand Down

0 comments on commit 02c91b0

Please sign in to comment.