playframework - jwt会话

本文详细介绍了如何在PlayFramework中使用JSON Web Token (JWT)进行用户认证,包括配置、登录流程及验证方法,使开发者能够更好地理解JWT的原理与实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接着上一篇的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"))
      }
  }
### 如何在 Django REST Framework JWT 中实现 Token 刷新 为了实现在 `Django REST Framework` 使用 JWT 认证时刷新令牌的功能,需按照如下方法设置: #### 安装依赖包 首先安装必要的 Python 包来支持 JWT 功能: ```bash pip install djangorestframework-jwt ``` #### 配置URL路由 接着,在项目的 `urls.py` 文件里加入用于获取新访问令牌的路径。这允许客户端通过发送旧的刷新令牌来换取新的访问令牌。 ```python from django.urls import path, re_path from rest_framework_jwt.views import ObtainJSONWebToken, RefreshJSONWebToken urlpatterns = [ ... re_path(r'^api-token-refresh/', RefreshJSONWebToken.as_view(), name='token_refresh'), ... ] ``` 上述代码定义了一个名为 `token_refresh` 的 URL 模式[^2]。 #### 设置全局认证方式 为了让整个 API 接口能够识别并验证 JWT 令牌,还需要修改项目配置文件 (`settings.py`) 来指定默认的身份验证类为 `JWTAuthentication`: ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } ``` 这样就完成了基本的 JWT 刷新机制搭建工作。当用户的访问令牌过期后,可以向 `/api-token-refresh/` 发送 POST 请求携带有效的刷新令牌以获得一个新的访问令牌。 需要注意的是,默认情况下,`djangorestframework-jwt` 并不提供真正的长期有效刷新令牌的支持;每次调用刷新接口都会生成一对全新的访问和刷新令牌,并且之前的刷新令牌会被认为失效[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值