Geo*_*ndo 4 scala playframework
我想为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))
}
Run Code Online (Sandbox Code Playgroud)
这个定义相当复杂.我在stackoverflow上找到了一些关于这个定义语法的问题,但是我还是不确定如何改变它.
我可以通过数据库查找看到User.authenticate中发生的身份验证检查.但我想要做的身份验证不使用数据库.我不确定如何或在哪里连接不同类型的身份验证.Security.Authenticated()是否连接到使用User类/对象?
Security.Authenticated只检查会话是否包含"用户名"密钥.如果是,用户应该进行身份验证.
您应该通过数据库查找或任何其他方式自行验证您的用户.然后,在会话中存储用户ID(或电子邮件,或只是名称):
val user = // fetch user info
Redirect("/").withSession("userId" ? user.id.toString)
Run Code Online (Sandbox Code Playgroud)
然后在Security.Authenticatedcall中包装动作:
def someAction = Security.Authenticated(
req => req.session.get("userId"),
_ => Redirect(views.html.login())) { userId =>
Action {
Ok(html.index())
}
}
Run Code Online (Sandbox Code Playgroud)
第一个参数Authenticated是一个从会话中检索用户ID的函数.它返回一个Option[String],即Some[String]如果会话中有id或者None没有.
req => req.session.get("userId")
Run Code Online (Sandbox Code Playgroud)
Result如果session不包含用户id,则第二个参数是返回使用的函数.您通常需要重定向到登录页面.
_ => Redirect(views.html.login())
Run Code Online (Sandbox Code Playgroud)
最后一个参数是一个返回的函数Action.如果用户通过身份验证,则使用它.
userId => Action {
Ok(html.index())
}
Run Code Online (Sandbox Code Playgroud)
您不必使用Play实现,随意将其包装在方便帮助器中,或者从头开始编写以满足您的需求:
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())
}
Run Code Online (Sandbox Code Playgroud)