每次用户登录时如何生成不同的会话ID

时间:2016-05-31 05:11:04

标签: scala session playframework session-cookies playframework-2.5

我正在将Play Framework 2.5用于我的网络应用程序。

在我的应用程序中,服务器端应用程序生成一个会话ID,并在提供creadentioal有效时将电子邮件地址放入其中,以便应用程序可以使用会话ID判断所请求的用户已登录的位置。

  

重定向(routes.Application.index).withSession(" email" - >" xxx")

当用户退出时,服务器端应用程序也会断开会话。

  

重定向(routes.Application.index).withSession

我检查了会话ID。即使在我关闭浏览器后,会话ID也始终相同。

  1. 登录

    PLAY_SESSION = 0b3fbd59f215c5df4dd937b508ef7cce42b65c56-电子邮件= PF%40ex

  2. 重载

    PLAY_SESSION = 0b3fbd59f215c5df4dd937b508ef7cce42b65c56-电子邮件= PF%40ex

  3. 注销

  4. 登录

    PLAY_SESSION = 0b3fbd59f215c5df4dd937b508ef7cce42b65c56-电子邮件= PF%40ex

  5. 关闭浏览器

  6. 登录

    PLAY_SESSION = 0b3fbd59f215c5df4dd937b508ef7cce42b65c56-电子邮件= PF%40ex

  7. attcher很容易猜出每个帐户的会话ID。所以我想在每次帐户登录时生成不同的会话ID。我怎么能这样做?

    感谢。

2 个答案:

答案 0 :(得分:1)

来自Docs

By default, there is no technical timeout for the Session. It expires when the user closes the web browser. 

我猜你没有关闭浏览器,再次登录后会话保持不变。

因此,在注销期间,您可以使用withNewSession丢弃旧会话,并在登录期间使用withSession

创建新会话

答案 1 :(得分:0)

redis的帮助下,您可以在用户每次登录时生成随机会话ID。

这意味着您将丢弃播放会话,而不是自己使用redis管理用户会话。

每次用户登录时,您都可以为用户生成会话ID并将其恢复为redis并设置会话过期时间。当用户请求进入时,您可以检查请求中的随机会话ID。

<强>更新 当用户登录时,后端服务器可以为用户生成randomId,并将随机ID放入会话中。当用户注销时,删除随机ID。代码如下所示

class Application extends Controller {

    def login() { implicit request =>
        val canLogin: Boolean = // check the authority,such as secret code
        if (canLogin) {
            val loginRandomId = Random.alphanumeric // just an example, generate randomID as you want
            //put key-value into redis. Maybe (loginRandomId, email) is what you want, and you can also set expiredate for the key
            redis.set(loginRandomId, email)
            Redirect(routes.Application.index).withSession("email" -> loginRandomId)
        }
    }

    def index() { implicit request =>
        val sessionValue = request.session.get("email");// sessionValue is randomId
        val isExist = redis.exit(sessionValue)
        if (isExist) {
            //handle the request   
        } else {
            // did not login, return
        }
    }
    def logout() { implicit request =>
        // when logout you should delete the key in redis
        val sessionValue = request.session.get("email");
        redis.delete(sessionValue)
    }
}
祝你好运