Simple authentication provider for Ktor that verifies presence of the API key in the header

Overview

Ktor API Key Authentication Provider

Simple authentication provider for Ktor that verifies presence of the API key in the header. Useful if you want to use X-Api-Key or similar approaches for request authentication.

Installation

Include following in your build.gradle.kts:

implementation("dev.forst", "ktor-api-key", "1.0.0")

Usage

This is minimal implementation of the Ktor app that uses API Key authentication:

keyFromHeader .takeIf { it == expectedApiKey } ?.let { AppPrincipal(it) } } } } routing { authenticate { get { val p = call.principal()!! call.respondText("Key: ${p.key}") } } } }">
/**
 * Minimal Ktor application with API Key authentication.
 */
fun Application.minimalExample() {
    // key that will be used to authenticate requests
    val expectedApiKey = "this-is-expected-key"

    // principal for the app
    data class AppPrincipal(val key: String) : Principal
    // now we install authentication feature
    install(Authentication) {
        // and then api key provider
        apiKey {
            // set function that is used to verify request
            validate { keyFromHeader ->
                keyFromHeader
                    .takeIf { it == expectedApiKey }
                    ?.let { AppPrincipal(it) }
            }
        }
    }

    routing {
        authenticate {
            get {
                val p = call.principal<AppPrincipal>()!!
                call.respondText("Key: ${p.key}")
            }
        }
    }
}

For details see MinimalExampleApp.kt with this example application and TestMinimalExampleApp.kt which verifies that this app works as expected.

For more advanced configuration see TestApiKeyAuth.kt.

You might also like...
🍣✨ Simple Ktor server to handle GitHub - YouTrack, usually for YouTrack Standalone.

🍣 sushi Simple Ktor server to handle GitHub Issues to YouTrack, usually for YouTrack Standalone. Why? There is not really a definite way to handle Gi

Implementing JWT token authentication on Android with Clean Architecture
Implementing JWT token authentication on Android with Clean Architecture

Implementando autenticação com token JWT no Android com Clean Architecture Implementar autenticação com Token JWT no Android não é uma tarefa fácil. É

A custom OTP view to enter a code usually used in authentication
A custom OTP view to enter a code usually used in authentication

A custom view to enter a code usually used in authentication. Different types of OTPViews. Easy to use and configure your own view and character of OTP using all the attributes.

It is a repository containing backend structure for Ktor.
It is a repository containing backend structure for Ktor.

Backend Architecture with Ktor + KMongo This project contains, Authentication using Jwt Database Layer (KMongo - Orm for MongoDB) Routing Advanced Rou

Kotlin backend based on the Clean Architecture principles. Ktor, JWT, Exposed, Flyway, KGraphQL/GraphQL generated endpoints, Gradle.
Kotlin backend based on the Clean Architecture principles. Ktor, JWT, Exposed, Flyway, KGraphQL/GraphQL generated endpoints, Gradle.

Kotlin Clean Architecture Backend Kotlin backend based on the Clean Architecture principles. The application is separated into three modules: Domain,

Ktor OpenAPI Spec Generator

Kompendium What is Kompendium Kompendium is intended to be a minimally invasive OpenApi Specification generator for Ktor. Minimally invasive meaning t

sharex image uploader using ktor

ktor-sharex-uploader uploader zdjec napisany w kotlinie przy uzyciu ktor pobierak gotowa jarka jest do pobrania tutaj config apki konfiguracje apki ma

This is a Ktor project to build your own Url shortener
This is a Ktor project to build your own Url shortener

Ktor URL Shortner This project is a implementation for creating Short URL using Ktor + Kotlin + MongoDB Usage It contains two routes if you want to im

SSU u-saint parser with Kotlin-Multiplatform and Ktor.

kusaint Soongsil University(SSU) u-Saint Parser with Kotlin Multiplatform. Prerequisites JVM !!IMPORTANT!! To run kusaint as a library in JVM environm

Releases(1.1.0)
  • 1.1.0(Apr 10, 2022)

    • support for Ktor 2.0.0

    What's Changed

    • Migrate implementation to ktor2 by @LukasForst in https://github.com/LukasForst/ktor-api-key/pull/1

    New Contributors

    • @LukasForst made their first contribution in https://github.com/LukasForst/ktor-api-key/pull/1

    Full Changelog: https://github.com/LukasForst/ktor-api-key/compare/1.0.0...1.1.0

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 16, 2022)

  • 0.0.2(Mar 16, 2022)

Owner
Lukas Forst
I push around electrons that trick rocks into doing math.
Lukas Forst
User Authentication ( Compose Ktor Server MongoDB)

Utilising Security in android for Authentication and Authorization for Android I would be using mongo db to perform all basic operations no need for f

Michael Enoma 0 May 2, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
KTor-Client---Android - The essence of KTor Client for network calls

KTor Client - Android This project encompasses the essence of KTor Client for ne

Mansoor Nisar 2 Jan 18, 2022
This app works as a simple replacement for SpongeAuth for those who want to use Discourse as the main SSO auth provider.

PowerNukkit Ore to Discourse Auth Gateway This app works as a simple replacement for SpongeAuth for those who want to use Discourse as the main SSO au

null 1 Apr 9, 2022
Login-and-Signup - Simple Login-and-Signup with authentication using Firebase API

Simple Login-and-Signup with authentication using Firebase API. Log in Sign Up

Indresh Goswami 0 Mar 25, 2022
A simple (and naive) RESTful API made with Ktor, jasync-sql and JWT.

A simple (and naive) RESTful API made with Ktor, jasync-sql and JWT. Route Method Description /account POST Create a new account /account DELETE Delet

null 2 Nov 4, 2021
An interactive command line interface to a transactional key value store

Transactional Key-Value Store An interactive command line interface to a transactional key value store. Commands: SET <key> <value> // store the value

Eugene 0 Jan 14, 2022
A Modern Kotlin-Ktor RESTful API example. Connects to a PostgreSQL database and uses Exposed framework for database operations.

kotlin-ktor-rest-api A Modern Kotlin-Ktor RESTful API example. Connects to a PostgreSQL database and uses Exposed framework for database operations. F

Selim Atasoy 32 Dec 20, 2022
Api Rest Card Game made in Kotlin with Ktor

ApiRest-CardGame "Card Game API" is a project made in Kotlin with Ktor. The API allows you to manage a simple card game deck (shuffle, take a card, pu

null 0 Dec 4, 2021
🍓CookHelper - food social network. The Api and Websocket are based on Ktor framework. Dependency injection with Koin library.

CookHelper [ ?? Work in Progress ?? ] CookHelper is a cross-platform application that will allow you to cook a delicious dish from an existing recipe

Arthur 11 Nov 9, 2022