使用Scala Play Framework和Silhouette进行验证时,可以通过以下步骤记录用户凭据的验证失败:
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import com.mohiva.play.silhouette.api.{ Logger, RequestProvider }
import com.mohiva.play.silhouette.impl.exceptions.{ IdentityNotFoundException, InvalidPasswordException }
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import play.api.mvc.{ RequestHeader, Result }
import scala.concurrent.Future
class CustomSecuredErrorHandler extends SecuredErrorHandler with Logger {
override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] = {
// 记录用户凭据验证失败的日志
logger.error(s"Authentication failed for ${request.remoteAddress}")
Future.successful(Results.Unauthorized)
}
override def onNotAuthorized(implicit request: RequestHeader): Future[Result] = {
// 记录用户凭据验证失败的日志
logger.error(s"Authorization failed for ${request.remoteAddress}")
Future.successful(Results.Forbidden)
}
}
silhouette {
errorHandler = "com.example.CustomSecuredErrorHandler"
}
GET /login controllers.AuthenticationController.login
POST /authenticate controllers.AuthenticationController.authenticate
import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.util.Credentials
import com.mohiva.play.silhouette.impl.providers.CredentialsProvider
import javax.inject.Inject
import play.api.mvc.{ AbstractController, ControllerComponents }
import scala.concurrent.{ ExecutionContext, Future }
class AuthenticationController @Inject()(
cc: ControllerComponents,
silhouette: Silhouette[UserEnv],
credentialsProvider: CredentialsProvider
)(implicit ec: ExecutionContext) extends AbstractController(cc) {
def login = Action.async { implicit request =>
Future.successful(Ok(views.html.login()))
}
def authenticate = Action.async { implicit request =>
val credentials = Credentials(
request.body.asFormUrlEncoded.get("email").head,
request.body.asFormUrlEncoded.get("password").head
)
credentialsProvider.authenticate(credentials).flatMap { loginInfo =>
silhouette.env.userService.retrieve(loginInfo).flatMap {
case Some(user) => silhouette.env.authenticatorService.create(loginInfo).map {
case authenticator if credentialsProvider.authenticatorIdleTimeout.isDefined =>
authenticator.copy(
idleTimeout = credentialsProvider.authenticatorIdleTimeout,
expirationDateTime = credentialsProvider.authenticatorExpiry.toDateTime
)
case authenticator => authenticator
}.flatMap { authenticator =>
silhouette.env.eventBus.publish(LoginEvent(user, request))
silhouette.env.authenticatorService.init(authenticator).flatMap { token =>
silhouette.env.authenticatorService.embed(token, Ok("Authentication successful"))
}
}
case None => Future.failed(new IdentityNotFoundException("Couldn't find user"))
}
}.recover {
case _: InvalidPasswordException => Unauthorized("Invalid credentials")
}
}
}
通过以上步骤,当用户凭据验证失败时,会记录相应的日志信息。你可以根据实际需求自定义日志的格式和存储方式。
领取专属 10元无门槛券
手把手带您无忧上云