Skip to content

V2 Authentication

Lukas Ruegner edited this page Jun 2, 2024 · 1 revision

A working example can be found here.

Configuring a OpenAPI Security Scheme

install(SwaggerUI) {
    securityScheme("MyBasicAuth") {
        type = AuthType.HTTP
        scheme = AuthScheme.BASIC
    }
    securityScheme("MyJwtAuth") {
        type = AuthType.HTTP
        scheme = AuthScheme.BEARER
        bearerFormat = "jwt"
    }
    swagger {
        defaultSecuritySchemeName = "MyBasicAuth"
    }
}

Configures two security mechanisms "MyBasicAuth" and "MyJwtAuth", that can be used across the api. By default "MyBasicAuth" will automatically be used for all protected routes - if not specified otherwise.

Multiple default security mechanisms can be specified with defaultSecuritySchemeNames = setOf(...)

See the official OpenAPI Specification for further information.

Flows

Example for an implicit OAuth2 flow

install(SwaggerUI) {
    securityScheme("MyAuth") {
        type = AuthType.OAUTH2
        flows {
            implicit {
                authorizationUrl = "https://example.com/api/oauth/dialog"
                scopes = mapOf(
                    "write:pets" to "modify pets in your account",
                    "read:pets" to "read your pets"
                )
            }
        }
    }
    //...
}

Assigning a Security Scheme to a Route

Using the default security scheme:

routing {
    authenticate {
        get("hello") {
            // handle call...
        }
    }
}

Using another security scheme:

routing {
    authenticate {
        get("hello", {
            securitySchemeName = "MyJwtAuth"
        }) {
            // handle call...
        }
    }
}

Using multiple security schemes (any given one can be used)

routing {
    authenticate {
        get("hello", {
            securitySchemeNames = setOf("MyJwtAuth", "MyBasicAuth")
        }) {
            // handle call...
        }
    }
}

Default "Unauthorized"-Response

A default response can be added to the OpenAPI-Spec of each protected route via the defaultUnauthorizedResponse-field in the plugin configuration.

install(SwaggerUI) {
    swagger {
        defaultUnauthorizedResponse = {
            description = "Username or password is invalid."
            // ...
        }
    }
}
Clone this wiki locally