4

Play2 Framework アプリ用のカスタム認証方法を作成したいと考えています。私は Scala と Play で試していますが、どちらも初めてです。

zentask の例では、Trait Secured に IsAuthenticated という関数があります。

  def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
  }

この定義はかなり複雑です。stackoverflow でこの定義の構文に関する多くの質問を見つけましたが、これを変更する方法がまだわかりません。

データベース ルックアップを介して、User.authenticate で認証チェックが行われていることがわかります。しかし、私がやりたい認証はデータベースを使用しません。異なるタイプの認証をどこにどのように配線するかわかりません。Security.Authenticated() は User クラス/オブジェクトの使用に組み込まれていますか?

4

1 に答える 1

5

Security.Authenticated just checks if session contains "username" key. If it does, user supposed to be authenticated.

You should authenticate your users yourself, by doing database lookup, or any other way. Then, store user id(or email, or just name) in the session:

val user = // fetch user info
Redirect("/").withSession("userId" → user.id.toString)

Then wrap actions in Security.Authenticated call:

def someAction = Security.Authenticated(
  req => req.session.get("userId"),
  _ => Redirect(views.html.login())) { userId =>
    Action {
      Ok(html.index())
    }
}

The first argument to Authenticated is a function that retrieves user id from the session. It returns an Option[String], i.e. Some[String] if there is id in the session or None if there isn't.

req => req.session.get("userId")

The second argument is a function that returns Result to use, if session isn't contains user id. You will typically want a redirect to a login page.

_ => Redirect(views.html.login())

The final argument is a function returning Action. It is used if user is authenticated.

userId => Action {
  Ok(html.index())
}

You are not forced to use play implementation, feel free to wrap it in handy helper, or write it from scratch to fit your needs:

def myAuth(f: String => Result) = Security.Authenticated(
  req => req.session.get("userId"),
  _ => Redirect(views.html.login())) { userId =>
  Action {
    f(userId)
  }
}

def someAction = myAuth { userId =>
  Ok(html.index())
}
于 2013-01-05T05:42:13.520 に答える