我正在用Scala重构Java中的Play 2.3应用程序。现有的Java控制器就像这样进行了装饰以进行身份验证。
@Security.Authenticated(Secured.class)
public class Application extends Controller { ... }
Secured.java的签名是:
public class Secured extends Security.Authenticator { ... }
我如何使用相同的Secured.java装饰我的Scala控制器?
我尝试不通过编写第二个Secured2.scala作为特征并在Play中对Scala方式进行身份验证,但许多现有模板依赖于Secured.java来获取当前用户,这就是我为什么试图让我的Scala控制器与Java Secured类兼容。
答案 0 :(得分:2)
我认为您无法使用相同的Java类进行使用scala API的身份验证。但是这里是你使用scala API的方法,你可以用你的安全类代码填补空白:
trait Authentication {
// Define what you want your auth header to be
val AUTH_TOKEN_HEADER = "X-AUTH-TOKEN"
object Authenticated extends Security.AuthenticatedBuilder(checkHeader(_), onUnauthorized(_))
def checkHeader(request: RequestHeader): Option[String] = {
request.headers.get(AUTH_TOKEN_HEADER) flatMap { token =>
// do a check to see if there is a user and get their name
}
}
def onUnauthorized(request: RequestHeader) = {
// Do something when the user isn't authorized to access a route
Results.Unauthorized
}
}
trait SecuredController extends Controller with Authentication
以下是它在实际控制器中的外观:
object SomeController extends SecuredController {
def someApi = Authenticated { req =>
// do something
// The username is available in the request
val username: String = req.user
Ok
}
}