playframework - jwt session

Next to the previous one play framework cors cross domain , continue to talk about how jwt is used in play framework and what is jwt? JSON Web Token (JWT) is an open standard (RFC 7519), which defines a compact, self-contained way to securely transfer information between parties as JSON objects. This information can be verified and trusted because it is digitally signed.

Simply put, with it, you no longer have to manage global session sessions in your program.

Using tutorials

application.conf add configuration

play.http.secret.key = "hello"
# Remember to modify online. The default is change
session = {

  # The cookie name
  cookieName = "PLAY_SESSION"

  # Whether the secure attribute of the cookie should be set to true
  secure = false

  # The max age to set on the cookie.
  # If null, the cookie expires when the user closes their browser.
  # An important thing to note, this only sets when the browser will discard the cookie.
  maxAge = null

  # Whether the HTTP only attribute of the cookie should be set to true
  httpOnly = true

  # The value of the SameSite attribute of the cookie. Set to null for no SameSite attribute.
  # Possible values are "lax" and "strict". If misconfigured it's set to null.
  sameSite = "lax"

  # The domain to set on the session cookie
  # If null, does not set a domain on the session cookie.
  domain = null

  # The session path
  # Must start with /.
  path = ${play.http.context}

  jwt {
    # The JWT signature algorithm to use on the session cookie
    # uses 'alg' https://tools.ietf.org/html/rfc7515#section-4.1.1
    signatureAlgorithm = "HS256"

    # The time after which the session is automatically invalidated.
    # Use 'exp' https://tools.ietf.org/html/rfc7519#section-4.1.4
    expiresAfter = ${play.http.session.maxAge}

    # The amount of clock skew to accept between servers when performing date checks
    # If you have NTP or roughtime synchronizing between servers, you can enhance
    # security by tightening this value.
    clockSkew = 5 minutes

    # The claim key under which all user data is stored in the JWT.
    dataClaim = "data"
  }
}

Use, for example, if the user logs in successfully, it can be used as follows

Ok(Json.obj(
                "code" -> "success",
                "msg" -> "Login successfully",
                "data" -> Json.obj(
                  "id" -> resultSet.getString("id"),
                  "nickName" -> resultSet.getString("nickName")
                )
              )).withSession(
                "authorId" -> resultSet.getString("id")
              )

It can be used as follows when verifying

def create: Action[AnyContent] = Action {
    request =>
      val authorId = request.session.get("authorId")
      if (authorId.isDefined) {
        val data = request.body.asJson
        val result = Json.obj("name" -> "Hello")
        Ok(result)
      } else BadRequest(Json.obj("code" -> "failed", "msg" -> "Please log in and then operate"))

  }

You can also customize parsing such as encrypting data for ajax requests

@Singleton
class UserController @Inject()(jwt: SessionCookieBaker


def validToken: Action[AnyContent] = Action {
    request =>
      val tokenOption = request.headers.get("token")
      val infos = jwt.decode(tokenOption.get)
      if (infos.isEmpty) {
        BadRequest(Json.obj("code" -> "failed", "msg" -> "User failure"))
      } else {
        TimeUnit.SECONDS.sleep(1)
        Ok(Json.obj("code" -> "success"))
      }
  }

Tags: Session JSON Attribute

Posted on Sun, 10 Nov 2019 08:59:03 -0800 by velanzia