Play 2 Scala

Community maintained

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Scala 2.11.7
  • Typesafe Activator 1.3.7
  • Play framework 2.4.6
Show requirements

Before you start

This guide walks you through setting up authentication and authorization in your Node.js apps with Auth0. If you are new to Auth0 we suggest you check our Overview. For a complete picture of authentication and authorization for regular web apps, check our Single Sign-On for Regular Web Apps documentation.

Auth0 uses OAuth. If you want to learn more about the OAuth flows used by regular web apps, read about Authentication for Server-side Web Apps.

Get Your Application Keys

When you signed up for Auth0, you created a new client.

Your application needs some details about this client to communicate with Auth0. You can get these details from the Settings section for your client in the Auth0 dashboard.

You need the following information:

  • Client ID
  • Domain

If you download the sample from the top of this page, these details are filled out for you. If you have more than one client in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated.

You need to whitelist the callback URL for your app in the Allowed Callback URLs field in your Client Settings. If you do not set any callback URL, your users will see a mismatch error when they log in.

If you are following along with the sample project you downloaded from the top of this page, Callback URL should be set to http://localhost:3000/callback.

Add the Auth0 Callback Handler

Add the handler for the Auth0 callback so you can authenticate the user and retrieve their information:

// controllers/Callback.scala
package controllers

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import javax.inject.Inject
import play.api.cache._
import play.api.http.HeaderNames
import play.api.http.MimeTypes
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import play.api.libs.json.Json.toJsFieldJsValueWrapper
import play.api.libs.ws._
import play.api.mvc.Action
import play.api.mvc.Controller
import helpers.Auth0Config

class Callback @Inject() (cache: CacheApi, ws: WSClient) extends Controller {
  
  def callback(codeOpt: Option[String] = None, stateOpt: Option[String] = None) = Action.async {
    if (stateOpt == cache.get("state")) {
      (for {
        code <- codeOpt
      } yield {
        getToken(code).flatMap { case (idToken, accessToken) =>
          getUser(accessToken).map { user =>
            cache.set(idToken + "profile", user)
            Redirect(routes.User.index())
              .withSession(
                "idToken" -> idToken,
                "accessToken" -> accessToken
              )
          }

        }.recover {
          case ex: IllegalStateException => Unauthorized(ex.getMessage)
        }
      }).getOrElse(Future.successful(BadRequest("No parameters supplied")))
    } else {
      Future.successful(BadRequest("Invalid state parameter"))
    }
  }

  def getToken(code: String): Future[(String, String)] = {
    val config = Auth0Config.get()
    var audience = config.audience
    if (config.audience == ""){
      audience = String.format("https://%s/userinfo",config.domain)
    }
    val tokenResponse = ws.url(String.format("https://%s/oauth/token", config.domain)).
      withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON).
      post(
        Json.obj(
          "client_id" -> config.clientId,
          "client_secret" -> config.secret,
          "redirect_uri" -> config.callbackURL,
          "code" -> code,
          "grant_type"-> "authorization_code",
          "audience" -> audience
        )
      )
      
    tokenResponse.flatMap { response =>
      (for {
        idToken <- (response.json \ "id_token").asOpt[String]
        accessToken <- (response.json \ "access_token").asOpt[String]
      } yield {
        Future.successful((idToken, accessToken)) 
      }).getOrElse(Future.failed[(String, String)](new IllegalStateException("Tokens not sent")))
    }
    
  }
  
  def getUser(accessToken: String): Future[JsValue] = {
    val config = Auth0Config.get()
    val userResponse = ws.url(String.format("https://%s/userinfo", config.domain))
      .withQueryString("access_token" -> accessToken)
      .get()

    userResponse.flatMap(response => Future.successful(response.json))
  }
}

Trigger Authentication

In the Application controller add login action to log the user in.

// controllers/Application.scala
package controllers

import javax.inject.Inject
import play.api.cache._
import play.api.mvc.Action
import play.api.mvc.Controller
import helpers.Auth0Config
import java.security.SecureRandom
import java.math.BigInteger

class Application @Inject() (cache: CacheApi) extends Controller {

  def index = Action {
    Ok(views.html.index())
  }

  def login = Action {
    val config = Auth0Config.get()
    // Generate random state parameter
    object RandomUtil {
      private val random = new SecureRandom()

      def alphanumeric(nrChars: Int = 24): String = {
        new BigInteger(nrChars * 5, random).toString(32)
      }
    }
    val state = RandomUtil.alphanumeric()
    var audience = config.audience
    cache.set("state", state)
    if (config.audience == ""){
      audience = String.format("https://%s/userinfo",config.domain)
    }

    val query = String.format(
      "authorize?client_id=%s&redirect_uri=%s&response_type=code&scope=openid profile&audience=%s&state=%s",
      config.clientId,
      config.callbackURL,
      audience,
      state
    )
    Redirect(String.format("https://%s/%s",config.domain,query))
  }
}

In the index view add a link to login route.

<!-- views/index.scala.html -->
<div class="login-box auth0-box before">
  <img src="https://i.cloudup.com/StzWWrY34s.png" />
  <h3>Auth0 Example</h3>
  <p>Zero friction identity infrastructure, built for developers</p>
  <a class="btn btn-primary btn-lg btn-block" href="/login">SignIn</a>
</div>

Access User Information

You can access the user information from the cache.

// controllers/User.scala
package controllers

import javax.inject.Inject
import play.api._
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.http.{MimeTypes, HeaderNames}
import play.api.libs.ws.WS
import play.api.mvc.{Results, Action, Controller}
import play.api.libs.json._
import play.api.cache._
import play.api.Play.current


class User @Inject() (cache: CacheApi) extends Controller {
  def AuthenticatedAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
    Action { request =>
      (request.session.get("idToken").flatMap { idToken =>
        cache.get[JsValue](idToken + "profile")
      } map { profile =>
        f(request)
      }).orElse {
        Some(Redirect(routes.Application.index()))
      }.get
    }
  }
  
  def index = AuthenticatedAction { request =>
    val idToken = request.session.get("idToken").get
    val profile = cache.get[JsValue](idToken + "profile").get
    Ok(views.html.user(profile))
  }
}

Display the user information in the user view.

// views/user.html.scala
@(profile: JsValue)

@main("Auth0 Play2 Scala Sample","home") {
  <img class="avatar" src='@((profile \ "picture").as[String])'/>
  <h2>Welcome @((profile \ "name").as[String])</h2>
}

Logout

To log the user out, you have to clear the data from the session, and redirect the user to the Auth0 logout endpoint. You can find more information about this in our documentation logout documentation.

Add the logout action in the Application controller.

// controllers/Application.scala

class Application @Inject() (cache: CacheApi) extends Controller {
  
  //...
  
  def logout = Action {
    val config = Auth0Config.get()
    Redirect(String.format(
      "https://%s/v2/logout?client_id=%s&returnTo=http://localhost:9000",
      config.domain,
      config.clientId)
    ).withNewSession
  }
}

Please take into consideration that the return to URL needs to be in the list of Allowed Logout URLs in the settings section of the client as explained in our documentation

In the user view add a link to logout route.

<!-- views/user.scala.html -->
<a href="/logout" class="btn btn-lg">Logout</a>

Optional Steps

You can add the following Action to check if the user is authenticated. If not, redirect them to the login page:

// controllers/User.scala
def AuthenticatedAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
  Action { request =>
    (request.session.get("idToken").flatMap { idToken =>
      cache.getAs[JsValue](idToken + "profile")
    } map { profile =>
      f(request)
    }).orElse {
      Some(Redirect(routes.Application.index()))
    }.get
  }
}

def index = AuthenticatedAction { request =>
  val idToken = request.session.get("idToken").get
  val profile = cache.getAs[JsValue](idToken + "profile").get
  Ok(views.html.user(profile))
}
Use Auth0 for FREECreate free Account