playframework - jwt

接着上一篇的play framework cors跨域、继续讲jwt在play framework中怎么使用的、什么是jwt?JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为JSON对象在各方之间安全地传输信息。该信息可以被验证和信任,因为它是数字签名的。

简单来说、用了它、你就再也不用在程序中管理全局session会话了。

使用教程

application.conf添加配置

play.http.secret.key = "hello"
# 线上记得修改、默认是changeme
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"
  }
}

使用、例如用户登录成功就可以像下面一样使用

Ok(Json.obj(
                "code" -> "success",
                "msg" -> "登录成功",
                "data" -> Json.obj(
                  "id" -> resultSet.getString("id"),
                  "nickName" -> resultSet.getString("nickName")
                )
              )).withSession(
                "authorId" -> resultSet.getString("id")
              )

验证的时候就可以像下面一样使用

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" -> "你好")
        Ok(result)
      } else BadRequest(Json.obj("code" -> "failed", "msg" -> "请登录后再操作"))

  }

还可以自定义解析如加密数据、用于ajax请求

@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" -> "用户失效"))
      } else {
        TimeUnit.SECONDS.sleep(1)
        Ok(Json.obj("code" -> "success"))
      }
  }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • JWT 介绍 (https://jwt.io/) JSON Web Token(JWT)是一个开放标准(RFC 7...
    匆匆岁月阅读 5,895评论 1赞 41
  • 官方英文原文在这里https://jwt.io/introduction/,我只是顺手翻译一下,如有不对的地方欢迎...
    WilliamQian阅读 4,015评论 0赞 3
  • 在前后端分离开发时为什么需要用户认证呢?原因是由于HTTP协定是不储存状态的(stateless),这意味着当我们...
    NewForMe阅读 7,068评论 0赞 5
  • Json web token(JWT)是为了网络应用环境间传递声明而执行的一种基于JSON的开发标准(RFC 75...
    YU_XI阅读 7,627评论 0赞 4
  • 概述 JSON Web令牌(JWT)是一个紧凑的采用URL安全表示方法的声明,用于在两方之间传输。JWT的声明被编...
    御浅永夜阅读 5,616评论 0赞 0

友情链接更多精彩内容