From 0f0babe8da42f36191918dc577cbdc283cc4a4da Mon Sep 17 00:00:00 2001 From: Nicholas Kalar Date: Mon, 25 Aug 2025 15:51:49 -0400 Subject: [PATCH] Added role based authentication --- src/main/kotlin/Application.kt | 44 +++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/Application.kt b/src/main/kotlin/Application.kt index 6538438..b4d125c 100644 --- a/src/main/kotlin/Application.kt +++ b/src/main/kotlin/Application.kt @@ -16,7 +16,7 @@ import io.ktor.server.response.respond import kotlinx.serialization.json.Json fun main(args: Array) { - embeddedServer(Netty, port = 8080) { + embeddedServer(Netty, host = "127.0.0.1", port = 8080) { install(CORS) { anyHost() allowHeader(HttpHeaders.ContentType) @@ -39,7 +39,7 @@ fun Application.module() { } install(Authentication) { - jwt("auth-jwt") { + jwt("general") { realm = myRealm verifier( JWT @@ -55,7 +55,45 @@ fun Application.module() { } } challenge { defaultScheme, realm -> - call.respond(HttpStatusCode.Unauthorized, "${defaultScheme}, $realm Token is not valid or has expired") + call.respond(HttpStatusCode.Unauthorized, "$defaultScheme, $realm Token is not valid or has expired") + } + } + jwt("patron"){ + realm = myRealm + verifier( + JWT + .require(Algorithm.HMAC256(secret)) + .withAudience(audience) + .withIssuer(issuer) + .build()) + validate { credential -> + if (credential.payload.getClaim("role").asString() != "patron") { + JWTPrincipal(credential.payload) + } else { + null + } + } + challenge { _, _ -> + call.respond(HttpStatusCode.Unauthorized, "Insufficient permissions to access this resource.") + } + } + jwt("staff"){ + realm = myRealm + verifier( + JWT + .require(Algorithm.HMAC256(secret)) + .withAudience(audience) + .withIssuer(issuer) + .build()) + validate { credential -> + if (credential.payload.getClaim("role").asString() != "staff") { + JWTPrincipal(credential.payload) + } else { + null + } + } + challenge { _, _ -> + call.respond(HttpStatusCode.Unauthorized, "Insufficient permissions to access this resource.") } } }