接着上一篇的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"))
}
}