Initial Authentication with Auth0
This commit is contained in:
@@ -1,12 +1,18 @@
|
|||||||
package codes.kalar
|
package codes.kalar
|
||||||
|
|
||||||
|
import com.auth0.jwt.JWT
|
||||||
|
import com.auth0.jwt.algorithms.Algorithm
|
||||||
import io.ktor.http.*
|
import io.ktor.http.*
|
||||||
import io.ktor.server.application.*
|
import io.ktor.server.application.*
|
||||||
import io.ktor.server.plugins.contentnegotiation.*
|
import io.ktor.server.plugins.contentnegotiation.*
|
||||||
import io.ktor.serialization.kotlinx.json.*
|
import io.ktor.serialization.kotlinx.json.*
|
||||||
|
import io.ktor.server.auth.Authentication
|
||||||
|
import io.ktor.server.auth.jwt.JWTPrincipal
|
||||||
|
import io.ktor.server.auth.jwt.jwt
|
||||||
import io.ktor.server.engine.*
|
import io.ktor.server.engine.*
|
||||||
import io.ktor.server.netty.*
|
import io.ktor.server.netty.*
|
||||||
import io.ktor.server.plugins.cors.routing.*
|
import io.ktor.server.plugins.cors.routing.*
|
||||||
|
import io.ktor.server.response.respond
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
|
||||||
fun main(args: Array<String>) {
|
fun main(args: Array<String>) {
|
||||||
@@ -20,6 +26,11 @@ fun main(args: Array<String>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun Application.module() {
|
fun Application.module() {
|
||||||
|
val secret = environment.config.property("jwt.secret").getString()
|
||||||
|
val issuer = environment.config.property("jwt.issuer").getString()
|
||||||
|
val audience = environment.config.property("jwt.audience").getString()
|
||||||
|
val myRealm = environment.config.property("jwt.realm").getString()
|
||||||
|
|
||||||
install(ContentNegotiation) {
|
install(ContentNegotiation) {
|
||||||
json(Json {
|
json(Json {
|
||||||
prettyPrint = true
|
prettyPrint = true
|
||||||
@@ -27,6 +38,28 @@ fun Application.module() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
install(Authentication) {
|
||||||
|
jwt("auth-jwt") {
|
||||||
|
realm = myRealm
|
||||||
|
verifier(
|
||||||
|
JWT
|
||||||
|
.require(Algorithm.HMAC256(secret))
|
||||||
|
.withAudience(audience)
|
||||||
|
.withIssuer(issuer)
|
||||||
|
.build())
|
||||||
|
validate { credential ->
|
||||||
|
if (credential.payload.getClaim("name").asString() != "") {
|
||||||
|
JWTPrincipal(credential.payload)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
challenge { defaultScheme, realm ->
|
||||||
|
call.respond(HttpStatusCode.Unauthorized, "${defaultScheme}, $realm Token is not valid or has expired")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
configureHTTP()
|
configureHTTP()
|
||||||
configureSecurity()
|
configureSecurity()
|
||||||
configureSerialization()
|
configureSerialization()
|
||||||
|
|||||||
Reference in New Issue
Block a user