Required dependencies: io.ktor:%artifact_name%
Code examples: auth-form-html-dsl, auth-form-session
Form-based authentication uses a web form to collect credential information and authenticate a user.
Given that username and password are passed as clear text when using form-based authentication, you need to use HTTPS/TLS to protect sensitive information.
To enable form
authentication, you need to include the %artifact_name%
artifact in the build script:
The form-based authentication flow might look as follows:
-
An unauthenticated client makes a request to a specific route in a server application.
-
A server returns an HTML page that consists at least from an HTML-based web form, which prompts a user for a username and password.
Ktor allows you to build a form using Kotlin DSL, or you can choose between various JVM template engines, such as FreeMarker, Velocity, and so on.
-
When a user submits a username and password, a client makes a request containing web form data (which includes the username and password) to a server.
{src="snippets/auth-form-html-dsl/post.http"}
In Ktor, you need to specify parameter names used to fetch a username and password.
-
A server validates credentials sent by a client and responds with the requested content.
To install the form
authentication provider, call the form function inside the install
block:
install(Authentication) {
form {
// Configure form authentication
}
}
You can optionally specify a provider name that can be used to authenticate a specified route.
The form
authentication provider exposes its settings via the FormAuthenticationProvider.Config class. In the example below, the following settings are specified:
- The
userParamName
andpasswordParamName
properties specify parameter names used to fetch a username and password. - The
validate
function validates a username and password.
{src="snippets/auth-form-html-dsl/src/main/kotlin/com/example/Application.kt" lines="11-23"}
The validate
function checks UserPasswordCredential
and returns a UserIdPrincipal
in a case of successful authentication or null
if authentication fails.
As for the
basic
authentication, you can also use UserHashedTableAuth to validate users stored in an in-memory table that keeps usernames and password hashes.
After configuring the form
provider, you can define the authorization for the different resources in our application using the authenticate
function. In a case of successful authentication, you can retrieve an authenticated UserIdPrincipal inside a route handler using the call.principal
function and get a name of an authenticated user.
{src="snippets/auth-form-html-dsl/src/main/kotlin/com/example/Application.kt" lines="25-30,51"}