Required dependencies: io.ktor:%artifact_name%
Ktor provides the Authentication plugin to handle authentication and authorization. Typical usage scenarios include logging in users, granting access to specific resources, and securely transmitting information between parties. You can also use Authentication
with Sessions to keep a user's information between requests.
Ktor supports the following authentications and authorization schemes:
HTTP provides a general framework for access control and authentication. In Ktor, you can use the following HTTP authentication schemes:
- Basic - uses
Base64
encoding to provide a username and password. Generally is not recommended if not used in combination with HTTPS. - Digest - an authentication method that communicates user credentials in an encrypted form by applying a hash function to the username and password.
Bearer
- an authentication scheme that involves security tokens called bearer tokens. You can use JSON Web Tokens as bearer tokens and use thejwt
authentication in Ktor to validate and authorize a request.
Form-based authentication uses a web form to collect credential information and authenticate a user.
JSON Web Token is an open standard for securely transmitting information between parties as a JSON object. You can use JSON Web Tokens for authorization: when the user is logged in, each request will include a token, allowing the user to access resources that are permitted with that token. In Ktor, you can verify a token and validate the claims contained within it using the jwt
authentication.
LDAP is an open and cross-platform protocol used for directory services authentication. Ktor provides the ldapAuthenticate function to authenticate user credentials against a specified LDAP server.
OAuth is an open standard for securing access to APIs. The oauth
provider in Ktor allows you to implement authentication using external providers such as Google, Facebook, Twitter, and so on.
Sessions provide a mechanism to persist data between different HTTP requests. Typical use cases include storing a logged-in user's ID, the contents of a shopping basket, or keeping user preferences on the client. In Ktor, a user that already has an associated session can be authenticated using the session
provider. Learn how to do this from .
Note that some authentication providers, such as JWT and LDAP, require additional artifacts.
After installing Authentication, you can configure and use Authentication
as follows:
To use a specific authentication provider (basic, digest, form, and so on), you need to call the corresponding function inside the install
block. For example, to use the basic
authentication, call the basic function:
install(Authentication) {
basic {
// [[[Configure basic authentication|basic.md]]]
}
}
Inside this function, you can configure settings specific to this provider.
A function for using a specific provider optionally allows you to specify a provider name. A code sample below installs the basic and form providers with the auth-basic and auth-form names, respectively:
install(Authentication) {
basic("auth-basic") {
// [[[Configure basic authentication|basic.md]]]
}
form("auth-form") {
// [[[Configure form authentication|form.md]]]
}
// ...
}
{disable-links="false"}
These names can be used later to authenticate different routes using different providers.
Note that a provider name should be unique, and you can define only one provider without a name.
Each provider type has its own configuration. For instance, the BasicAuthenticationProvider.Config class contains options passed to the basic function. The most important function exposed by this class is validate that validates a username and password. A code sample below shows how it can look:
{src="snippets/auth-basic/src/main/kotlin/com/example/Application.kt" lines="9-20"}
To understand how the validate
function works, we need to introduce two terms:
- A principal is an entity that can be authenticated: a user, a computer, a service, etc. In Ktor, various authentication providers might use different principals. For example, the
basic
andform
providers authenticate UserIdPrincipal while thejwt
provider verifies JWTPrincipal.If you use session authentication, a principal might be a data class that stores session data.
- A credential is a set of properties for a server to authenticate a principal: a user/password pair, an API key, and so on. For instance, the
basic
andform
providers use UserPasswordCredential to validate a username and password whilejwt
validates JWTCredential.
So, the validate
function checks a specified Credential and returns a Principal in a case of successful authentication or null
if authentication fails.
To skip authentication based on a specific criteria, use skipWhen. For example, you can skip
basic
authentication if a session already exists:basic { skipWhen { call -> call.sessions.get<UserSession>() != null } }
The final step is to define the authorization for the different resources in our application. You can do this by using the
authenticate function. This function can accept a name of a provider used to authenticate nested routes. The code snippet below uses a provider with the auth-basic name to protect the /login
and /orders
routes:
routing {
authenticate("auth-basic") {
get("/login") {
// ...
}
get("/orders") {
// ...
}
}
get("/") {
// ...
}
}
Note that you can omit a provider name to use an unnamed provider.
In a case of successful authentication, you can retrieve an authenticated Principal inside a route handler using the call.principal
function. This function accepts a specific principal type returned by the configured authentication provider. In a code sample below, call.principal
is used to obtain UserIdPrincipal
and get a name of an authenticated user.
{src="snippets/auth-basic/src/main/kotlin/com/example/Application.kt" lines="21-27"}
If you use session authentication, a principal might be a data class that stores session data. So, you need to pass this data class to call.principal
:
{src="snippets/auth-form-session/src/main/kotlin/com/example/Application.kt" lines="75-77,80-81"}