2012-08-05 31 views
6

我想通過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爲我提供了一個完整的解決方案嗎?或者至少有一些文檔?

回答

12

的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

12

正如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