Play Silhouette 使用教程
1、项目介绍
Play Silhouette 是一个用于 Play Framework 应用程序的身份验证库,支持多种身份验证方法,包括 OAuth1、OAuth2、OpenID、CAS、2FA TOTP、凭证、基本身份验证或自定义身份验证方案。该项目旨在为开发人员提供一个灵活且强大的身份验证解决方案。
2、项目快速启动
安装依赖
首先,在你的 Play Framework 项目中添加 Play Silhouette 依赖。在你的 build.sbt
文件中添加以下内容:
libraryDependencies ++= Seq(
"com.mohiva" %% "play-silhouette" % "7.0.0",
"com.mohiva" %% "play-silhouette-password-bcrypt" % "7.0.0",
"com.mohiva" %% "play-silhouette-persistence" % "7.0.0",
"com.mohiva" %% "play-silhouette-crypto-jca" % "7.0.0",
"com.mohiva" %% "play-silhouette-testkit" % "7.0.0" % Test
)
配置 Silhouette
在 conf/application.conf
文件中添加以下配置:
play.modules.enabled += "com.mohiva.play.silhouette.api.actions.SecuredErrorHandler"
play.modules.enabled += "com.mohiva.play.silhouette.api.actions.UnsecuredErrorHandler"
play.modules.enabled += "com.mohiva.play.silhouette.api.actions.UserAwareAction"
play.modules.enabled += "com.mohiva.play.silhouette.api.actions.SecuredAction"
play.modules.enabled += "com.mohiva.play.silhouette.api.actions.UnsecuredAction"
创建用户模型
创建一个用户模型类 app/models/User.scala
:
case class User(
id: Option[Long],
email: String,
password: String
)
创建身份验证控制器
创建一个身份验证控制器 app/controllers/AuthController.scala
:
package controllers
import javax.inject._
import play.api.mvc._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.impl.providers._
@Singleton
class AuthController @Inject() (
components: ControllerComponents,
silhouette: Silhouette[DefaultEnv]
) extends AbstractController(components) {
def signIn = Action { implicit request =>
Ok("Sign in page")
}
def authenticate = Action.async { implicit request =>
val credentials = Credentials("user@example.com", "password")
silhouette.env.credentialsProvider.authenticate(credentials).map { loginInfo =>
Redirect(routes.HomeController.index())
}.recover {
case _ => Redirect(routes.AuthController.signIn()).flashing("error" -> "Invalid credentials")
}
}
}
3、应用案例和最佳实践
应用案例
Play Silhouette 可以用于构建各种需要身份验证的应用程序,例如:
- 社交网络平台
- 企业内部管理系统
- 电子商务网站
最佳实践
- 安全性:确保使用强密码哈希算法(如 bcrypt)来存储用户密码。
- 模块化:根据需要选择合适的 Silhouette 模块,避免引入不必要的依赖。
- 测试:编写单元测试和集成测试,确保身份验证逻辑的正确性。
4、典型生态项目
Play Silhouette 可以与其他 Play Framework 生态项目结合使用,例如:
- Play Framework:核心框架,提供 Web 应用程序的基础设施。
- Slick:用于数据库访问和 ORM。
- Play JSON:用于 JSON 处理。
- Akka:用于并发和消息传递。
通过结合这些项目,可以构建出功能丰富且高效的应用程序。