Introduction
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.
Add the ktor-server-auth dependency for authentication:
dependencies: - $ktor.server.authBasic
The Basic authentication scheme is a part of the HTTP framework used for access control and authentication.
In this scheme, user credentials are transmitted as username/password pairs encoded using Base64.
Generally, it is not recommended if not used in combination with HTTPS.
The basic authentication flow looks as follows:
-
A client makes a request without the
Authorizationheader to a specific route in a server application. -
A server responds to a client with a
401(Unauthorized) response status and uses aWWW-Authenticateresponse header to provide information that the basic authentication scheme is used to protect a route.
Digest
Digest authentication in Ktor Server
The Digest authentication scheme is a part of the HTTP framework used for access control and authentication.
In this scheme, a hash function is applied to a username and password before sending them over the network.
The digest authentication provider exposes its settings via the DigestAuthenticationProvider.Config class.
In the example below, the following settings are specified:
-
The
realmproperty sets the realm to be passed in theWWW-Authenticate header. -
The
digestProviderfunction fetches the HA1 part of digest for a specified username. -
(Optional) The
validatefunction allows you to map the credentials to a custom principal.
authentication { digest("auth-digest") { realm = xtecRealm digestProvider { userName, realm -> userTable[userName] } validate { credentials -> if (credentials.userName.isNotEmpty()) { CustomPrincipal(credentials.userName, credentials.realm) } else { null } } }}Bearer
Bearer authentication in Ktor Server
The Digest authentication scheme is a part of the HTTP framework used for access control and authentication.
This scheme involves security tokens called bearer tokens. The Bearer authentication scheme is used as part of OAuth or JWT, but you can also provide custom logic for authorizing bearer tokens.
Form
Form-based authentication uses a web form to collect credential information and authenticate a user.
Session
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. For example, when a user logs in using a web form for the first time, you can save a username to a cookie session and authorize this user on later requests using the session provider.
To enable session authentication, you need to include the ktor-server-sessions artifact in the module.yaml file:
dependencies: - $ktor.server.sessionsThe authentication flow with sessions might vary and depends on how users are authenticated in your application.
Let’s see how it might look with the form-based authentication:
-
A client makes a request containing web form data (which includes the username and password) to a server.
-
A server validates credentials sent by a client, saves a username to a cookie session, and responds with the requested content and a cookie containing a username.
-
A client makes a later request with a cookie to the protected resource.
-
Based on received cookie data, Ktor checks that a cookie session exists for this user and, optionally, performs additional validations on received session data. In a case of successful validation, a server responds with the requested content.
JWT
JSON Web Token (JWT) is an open standard that defines a way for securely transmitting information between parties as a JSON object. This information can be verified and trusted since it is signed using a shared secret (with the HS256 algorithm) or a public/private key pair (for example, RS256).
To enable JWTauthentication, you need to include the ktor-server-auth-jwt artifact in the module configuration example:
dependencies: - $ktor.server.auth.jwtOAuth
Obtaining client credentials
To access Google APIs, you need to create authorization credentials in the Google Cloud Console.
-
Open the Credentials page in the Google Cloud Console.
-
Click CREATE CREDENTIALS and choose
OAuth client ID. -
Choose
Web applicationfrom the dropdown. -
Specify the following settings:
- Authorised JavaScript origins:
http://localhost:8080. - Authorised redirect URIs:
http://localhost:8080/callback.
Click CREATE.
- Authorised JavaScript origins: