🐛 Changes basic auth to bearer auth

This commit is contained in:
2026-04-16 16:16:41 +02:00
parent 76df9c604a
commit bdc7b6b8cf
3 changed files with 11 additions and 5 deletions
+1
View File
@@ -12,6 +12,7 @@ fun Application.configureHTTP() {
allowMethod(HttpMethod.Put) allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Patch) allowMethod(HttpMethod.Patch)
allowMethod(HttpMethod.Delete) allowMethod(HttpMethod.Delete)
allowHeader(HttpHeaders.Authorization)
anyHost() // @TODO: Don't do this in production if possible. Try to limit it. anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
} }
install(Compression) install(Compression)
+7 -5
View File
@@ -8,11 +8,13 @@ fun Application.configureSecurity(dotenv: Dotenv) {
val apiKey = dotenv["API_KEY"] ?: throw Exception("API_KEY not found") val apiKey = dotenv["API_KEY"] ?: throw Exception("API_KEY not found")
authentication { authentication {
basic { bearer {
realm = "ktor" realm = "/"
validate { credentials -> authenticate { credential ->
if (credentials.name == "admin" && credentials.password == apiKey) { println("received: '${credential.token}'")
UserIdPrincipal(credentials.name) println("expected: '${apiKey}'")
if (credential.token == apiKey) {
UserIdPrincipal("admin")
} else { } else {
null null
} }
+3
View File
@@ -4,7 +4,9 @@ import dev.svitan.services.AuthService
import dev.svitan.services.NewAuthDTO import dev.svitan.services.NewAuthDTO
import io.ktor.http.HttpStatusCode import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application import io.ktor.server.application.Application
import io.ktor.server.auth.UserIdPrincipal
import io.ktor.server.auth.authentication import io.ktor.server.auth.authentication
import io.ktor.server.auth.principal
import io.ktor.server.plugins.BadRequestException import io.ktor.server.plugins.BadRequestException
import io.ktor.server.plugins.NotFoundException import io.ktor.server.plugins.NotFoundException
import io.ktor.server.request.receive import io.ktor.server.request.receive
@@ -16,6 +18,7 @@ fun Application.routeAuth() {
routing { routing {
authentication { authentication {
get("/auth") { get("/auth") {
println("Hello ${call.principal<UserIdPrincipal>()?.name}")
call.respond(AuthService.readAll()) call.respond(AuthService.readAll())
} }