Added role based authentication
This commit is contained in:
@@ -16,7 +16,7 @@ import io.ktor.server.response.respond
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
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.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user