Ktor - Authentication

  • 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:

    module.yaml
    dependencies:
    - $ktor.server.auth

    Basic

    Basic authentication

    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:

    1. A client makes a request without the Authorization header to a specific route in a server application.

    2. A server responds to a client with a 401 (Unauthorized) response status and uses a WWW-Authenticate response 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 realm property sets the realm to be passed in the WWW-Authenticate header.

    • The digestProvider function fetches the HA1 part of digest for a specified username.

    • (Optional) The validate function 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

    Form-based authentication uses a web form to collect credential information and authenticate a user.

    Session

    Session authentication

    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:

    module.yaml
    dependencies:
    - $ktor.server.sessions

    The 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:

    1. A client makes a request containing web form data (which includes the username and password) to a server.

    2. 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.

    3. A client makes a later request with a cookie to the protected resource.

    4. 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 Tokens

    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:

    module.yaml
    dependencies:
    - $ktor.server.auth.jwt

    OAuth

    Obtaining client credentials

    To access Google APIs, you need to create authorization credentials in the Google Cloud Console.

    1. Open the Credentials page in the Google Cloud Console.

    2. Click CREATE CREDENTIALS and choose OAuth client ID.

    3. Choose Web application from the dropdown.

    4. Specify the following settings:

      • Authorised JavaScript origins: http://localhost:8080.
      • Authorised redirect URIs: http://localhost:8080/callback.

      Click CREATE.

    Pending