Java Play! 2 - 用户管理与饼干

Java Play! 2 - 用户管理与饼干

问题描述:

我想通过cookie管理我的用户。这并不容易,因为这个主题绝对没有文档。Java Play! 2 - 用户管理与饼干

随着样本的帮助 “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不是deidypted,总是看起来一样。例如bdb7f592f9d54837995f816498c0474031d44c1a-username%3Akantaki

  • 2.)Security.Authenticator类是做什么的?

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

的re也是由Joscha Feth的authenticationauthorization-Play Authenticate的完整栈。 (可在GitHub

它采用准备使用的样品的Java,它使用的securesocial +全Deadbolt 2概念(由史蒂夫·查洛纳)的支持。它具有:

  • 内置可能性registerlog in用户提供电子邮件,谷歌,Facebook,Foursquare的,微博OpenID和自定义提供。
  • 多语言支持(目前为:英语,德语,波兰语)
  • 定制的模板(也可用于信息的电子邮件)
  • 支持rolespermissions(通过Deadbolt 2
  • 密码恢复支持

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

+0

这看起来很神奇,谢谢! – 2012-08-05 13:39:53

+0

只是好奇,你能给我一个非常简短的概述,我需要改变,以使它适用于Mongodb?我想我将不得不删除每个SQL方法,如 - play.find等,并用吗啡取而代之?我只是问,因为我需要改变很多。不想在开始时犯一个大错误 – 2012-08-05 14:55:14

+1

对不起,主题'MongoDB'和'Morphia'我不能帮你。我认为开始一个新问题是最好的想法,正确地解决它的范围。 – biesior 2012-08-05 15:12:50

正如Zentask sample所示,您Secured类应该扩展Security.Authenticator

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

工作流程如下:

  1. Check authorization
  2. Add an unique identifier in the client cookies
  3. Check if authenticated
  4. Secure a controller or an action
  5. If not authorized, redirect the client to another page
+0

是的,谢谢我已经读过zentask的例子。但在zentask的例子中,onUnauthorized()或getUsername()永远不会被使用,所以我猜想playframework正在调用它们。玩家如何知道用户何时被授权/未经授权? – 2012-08-05 13:19:14

+0

通过getUsername()方法:如果用户未通过身份验证,则返回null http://www.playframework.org/documentation/api/2.0.2/java/play/mvc/Security.Authenticator.html#getUsername(play。 mvc.Http.Context) – 2012-08-05 13:29:15

+0

啊好吧谢谢。 :) – 2012-08-05 13:44:44