Java Play! 2 – 使用cookie进行用户管理

我试图通过cookie管理我的用户。 这并不容易,因为绝对没有关于这个主题的文档。

在样本“zentask”的帮助下,我做了这个:

session("username", filledForm.field("username").value()); public class Secured{ public static Session getSession() { return Context.current().session(); } public static String getUsername() { return getSession().get("username"); } public static boolean isAuthorized() throws Exception { String username = getUsername(); if (username == null) return false; long userCount = DatabaseConnect.getInstance().getDatastore() .createQuery(User.class).field("username").equal(username) .countAll(); if (userCount == 1) return true; return false; } 

我这样使用它:

 public static Result blank() throws Exception { if (Secured.isAuthorized()) return ok(Secured.getUsername()); else return ok(views.html.login.form.render(loginForm)); } 

现在我有几个问题/问题:

  • 1.)Cookie不是dectypted,看起来总是一样的。 例如bdb7f592f9d54837995f816498c0474031d44c1a-username%3Akantaki

  • 2.)Security.Authenticator类有什么作用?

  • 3.)我认为通过cookie进行用户管理是一个非常普遍的问题,确实可以玩!2.0为我提供了完整的解决方案吗? 或者至少有一些文件?

还有用于authenticationauthorization完整堆栈 – 由Joscha Feth 播放身份validation 。 (可在GitHub获得 )

它结合了Java的即用型样本,它使用了securesocial +完整Deadbolt 2 (由Steve Chaloner)支持的概念。 它有:

  • 通过电子邮件,Google,Facebook,Foursquare,Twitter,OpenId和自定义提供商registerlog in用户。
  • 多语言支持(目前:英语,德语,波兰语)
  • 可自定义的模板(也用于信息电子邮件)
  • 支持rolespermissions (通过Deadbolt 2 )
  • 密码恢复支持

其中有Java示例应用程序。 您可以将其合并到您的应用中。

如Zentask示例所示,您的Secured类应该扩展Security.Authenticator

有了这个,它将允许在Controller或Action上放置@Security.Authenticated注释。 如果未正确授权用户(通过覆盖Security.Authenticator.onUnauthorized()方法),此批注允许将客户端重定向到另一个页面。

工作流程如下:

  1. 检查授权 :
  2. 在客户端cookie中添加唯一标识符
  3. 检查是否经过validation
  4. 保护控制器或操作
  5. 如果未获得授权,请将客户端重定向到另一个页面