GithubHelp home page GithubHelp logo

omkar-tenkale / ktor-role-based-auth Goto Github PK

View Code? Open in Web Editor NEW
7.0 1.0 0.0 73 KB

A simple yet powerful role based authorization plugin for ktor server

License: The Unlicense

Kotlin 100.00%
jwt-auth ktor ktor-auth ktor-plugin ktor-server

ktor-role-based-auth's Introduction

UPDATE: Read official announcement for role based auth in Ktor 2023 roadmap
Simplifying support for authorization and authentication. Providing end-to-end support for database authentication and session management, as well as role-based authorization

Ktor Role based Auth

ktor-role-based-auth is an easy to use and intuitive role-based access control library for Ktor Server

It works with the official ktor-server-auth library and adds role based authorization on top of it

Supported methods

  • HTTP authentication (Basic/Digest/Bearer)
  • Form-based authentication
  • JWT
  • Session
  • OAuth
  • LDAP
  • Custom authentication

Installation

Step 1. Add the JitPack repository in build.gradle.kts

repositories {
    mavenCentral()
    maven { url = uri("https://jitpack.io") }
}

Step 2. Add the dependency

dependencies {
    implementation("com.github.omkar-tenkale:ktor-role-based-auth:0.2.0")
}

Usage

Initialize the plugin when configuring authentication

fun Application.configureSecurity(){
    authentication {
        jwt {
            // Configure jwt authentication
        }
        roleBased {
            extractRoles { principal ->
                //Extract roles from JWT payload
                (principal as JWTPrincipal).payload.claims?.get("roles")?.asList(String::class.java)?.toSet() ?: emptySet()
            }
        }
    }
}
fun Application.routing() {
    route("/") {
        
        //No authentication required to access this route
        get {
            call.respondText("Welcome!")
        }

        authenticate {

            //JWT authenticated route
            route("/profile") {
                get {
                    call.respondText("Joined: 2 years ago")
                }
            }

            //JWT authenticated + role authorized route
            route("/dashboard") {
                withAnyRole("ADMIN", "SUPER_ADMIN") {
                    get {
                        call.respondText("Total users: 2443")
                    }
                }
            }
            
            //JWT authenticated + role authorized route
            route("/system-stats") {
                withRole("SUPER_ADMIN") {
                    get {
                        call.respondText("CPU: 34%")
                    }
                }
            }
        }
    }
}

The plugin responds with 403 (Forbidden) by default if roles don't match Optionally, follow these steps to send a custom response

  1. Set throwErrorOnUnauthorizedResponse to true
fun Application.configureSecurity(){
    authentication {
        jwt {
            // Configure jwt authentication
        }
        roleBased {
            extractRoles { principal ->
                //Extract roles from JWT payload
                (principal as JWTPrincipal).payload.claims?.get("roles")?.asList(String::class.java)?.toSet() ?: emptySet()
            }
            throwErrorOnUnauthorizedResponse = true
        }
    }
}
  1. Catch the UnauthorizedAccessException exception globally with help of StatusPages plugin
fun Application.configureSecurity() {
    install(StatusPages) {
        exception<Throwable> { call, cause ->
            if (cause is UnauthorizedAccessException) {
                call.respondText(text = "You don't have enough permissions to access this route", status = HttpStatusCode.Forbidden)
            }
        }
    }
}

For complete example, Check out tests

Thanks

ktor-role-based-auth's People

Contributors

omkar-tenkale avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ktor-role-based-auth's Issues

create a new pipeline

I have a big problem, maybe you can help.
I have an api, with Ktor, that receives an encrypted JWT token.
I need to create a pipeline to decrypt it before entering the authentication phase.
my method is
String.decrypt()
it accepts an encrypted string and returns a string
As an example, I get

MIAGCSqGSIb3DQEHA6CAMIACAQAxggLIMIICxAIBADCBqzCBkjELMAkGA1UEBhMCQlIxETAPBgNVBAgMCE1hcmFuaGFvMREwDwYDVQQHDAhTYW8gTHVpczEVMBMGA1UECgwMVFIgU29sdXRpb25zMRowGAYDVQQDDBEqLnRyc29sdXRpb25zLmNvbTEqMCgGCSqGSIb3DQEJARYbcm9kcmlnb19kZXZlbG1zQGhvdG1haWwuY29tAhRRj2k/Y1nMRD9Ywg3SorVzgT2UCTANBgkqhkiG9w0BAQEFAASCAgAlKpNm335GymToookeZS7SIbgzja2otRt+pGg1lFZCkcqk783apxy7DKorQBKwKuFanq5Y+SUuZKBMXGIbPF5fayXwU+UreGihswR30Ugup7i09nG6lw+l6//nn2dZWIoLL5zcCbrUXdMrHwuMst1wD5OOPjrJ2/08JVsqGbscDP+IRrfpLunOdjC7i+N9HieTyriVqUSxL9RMoTWxJXClxkbdexthngZp7kF4+pSHXKVCima7v9AIU/4+C3Ws2ixbrFQDuyll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l/fW9+RdYDcikXxyewkS8OPzSbEzgzpvlK0w/J90eVyFMYHkRxQGwerOFzTItDn31TGgFIUkq54Hr9vIhi00cmvkVixdfHjOepOLZ10Nsf5aRTrYpWJeR487iZrNxi5gMA0FS6aNek+EPgY+HNpgKHh1T9IyZglRildvWTyq7/t254KzjUB15xqirtjB/kcBSIROFZ047/e6nLJhRWvqzMLPozNwEb0R7pcazES5WOLeFIeOgH62klQAzJ36icmAJmpXJ24uprONLlpNH3AAAAAAAAAAA=

and have to return
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

io.ktor.server.application.DuplicatePluginException when using an RBAC route

whenever i add the rbac functions to a route, i get a DuplicatePluginException, when i check the code, it is trying to install the plugin on every request, why is this and how to solve it?

i.e.

fun Route.withAnyRole(roles: Set<Role>, build: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit) {
    install(RoleBasedAuthPlugin) {
        any = roles.toSet()
    }
    handle { build() }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.