简体   繁体   中英

How do I store a cookie in Play Framework?

I want to store an authentication token with Play Framework that outlives the current session, perhaps for days or even weeks - so that users don't have to login every time.

What is the recommended way to do this?

The response object has a method setCookie, which does exactly what you want

response.setCookie("playlonglivecookie", yourData, "14d");

Remember, that the data stored in the cookie is not encrypted, so if you want to encrypt it, then use the Crypto.sign method. Which signs your code using the play framework secret key.

http://www.playframework.org/documentation/api/1.1.1/play/mvc/Http.Response.html#setCookie(java.lang.String,%20java.lang.String)

I would also advise you to have a look at the secure module provided in play-1.x/modules/secure and the file Secure.java... it provides a checkbox "remember me" in the login form which allows keeping you logged for eternity.

and the code of this function (specially the response.setCookie at the end):

public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
    // Check tokens
    Boolean allowed = false;
    try {
        // This is the deprecated method name
        allowed = (Boolean)Security.invoke("authentify", username, password);
    } catch (UnsupportedOperationException e ) {
        // This is the official method name
        allowed = (Boolean)Security.invoke("authenticate", username, password);
    }
    if(validation.hasErrors() || !allowed) {
        flash.keep("url");
        flash.error("secure.error");
        params.flash();
        login();
    }
    // Mark user as connected
    session.put("username", username);
    // Remember if needed
    if(remember) {
        response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
    }
    // Redirect to the original URL (or /)
    redirectToOriginalURL();
}

Pascal

With play > 2.5 setCookie is deprecated.

you can use instead:

Http.Response.setCookie(Http.Cookie cookie)

You can create a new cookie with the builder:

Http.Cookie.builder("name", "value").withMaxAge(15).build();

15 days is the expiration date

Reference: https://www.playframework.com/documentation/2.5.x/api/java/play/mvc/Http.Response.html#setCookie-play.mvc.Http.Cookie-

Example: https://github.com/playframework/playframework/blob/master/framework/src/play/src/test/java/play/mvc/CookieBuilderTest.java

The response-object has some methods to help you. See javadoc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM