scala – 在Play IsAuthenticated中更改身份验证方法
我想为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类/对象? 解决方法
Security.Authenticated只检查会话是否包含“用户名”密钥.如果是,用户应该进行身份验证.
您应该通过数据库查找或任何其他方式自行验证您的用户.然后,在会话中存储用户ID(或电子邮件,或只是名称): val user = // fetch user info Redirect("/").withSession("userId" → user.id.toString) 然后在Security.Authenticated调用中包装操作: def someAction = Security.Authenticated( req => req.session.get("userId"),_ => Redirect(views.html.login())) { userId => Action { Ok(html.index()) } } Authenticated的第一个参数是一个从会话中检索用户ID的函数.如果会话中有id,则返回Option [String],即Some [String];如果不存在,则返回None. req => req.session.get("userId") 如果session不包含用户id,则第二个参数是返回Result使用的函数.您通常需要重定向到登录页面. _ => Redirect(views.html.login()) 最后一个参数是一个返回Action的函数.如果用户通过身份验证,则使用它. userId => Action { Ok(html.index()) } 您不必使用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()) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |