kotlin,

Code with Ktor and Auth0

Cui Cui Follow Aug 15, 2021 · 2 mins read
Code with Ktor and Auth0
Share this

This is the article trying to study:

Setup API app

  1. Setup Auth0 account.

  2. Install Ktor Authentication plugin
     val jwkProvider = JwkProviderBuilder(System.getenv("ISSUER"))
     .cached(10, 24, TimeUnit.HOURS)
     .rateLimited(10, 1, TimeUnit.MINUTES)
     .build()
    
     install(Authentication) {
         jwt("auth0") {
             verifier(jwkProvider, System.getenv("ISSUER"))
             validate { credential -> validateCreds(credential) }
         }
     }
    
  3. Add validate Credentials method
    fun validateCreds(credential: JWTCredential): JWTPrincipal? {
     val containsAudience = credential.payload.audience.contains(System.getenv("AUDIENCE"))
    
     if (containsAudience) {
         return JWTPrincipal(credential.payload)
     }
    
     return null
    }
    
  4. Add authenticate layer to the routes
    routing {
     authenticate("auth0") {
         get("/api/messages/protected") {
             call.respondText(
                 """{"message": "The API successfully validated your access token."}""",
                 contentType = ContentType.Application.Json
             )
         }
     }
    }
    
  5. Environment security variables for API app
     export ISSUER=https://<yourdomain>.auth0.com
     export AUDIENCE=<api audience>
    
  6. Run the API app

Setup Frontend app

  1. Environment security variables for UI app
     export REACT_APP_AUTH0_DOMAIN=yourdomain.auth0.com
     export REACT_APP_AUTH0_CLIENT_ID=abcdefghigklmnop
     export REACT_APP_AUTH0_AUDIENCE=ktordemo
     export REACT_APP_API_SERVER_URL=http://localhost:6060
    
  2. Run the API and UI apps
    npm install
    npm start
    

Bullet points to take away:

Join Newsletter
Get the latest news right in your inbox. We never spam!
Cui
Written by Cui Follow
Hi, I am Cui, the colourful coder for colourful.codes!