gpt4 book ai didi

scala - 将未经身份验证的请求发送到不同的操作路由

转载 作者:行者123 更新时间:2023-12-02 04:52:33 24 4
gpt4 key购买 nike

我正在对所有请求实现全局过滤器,以识别发出请求的用户是否已通过身份验证,如果未通过身份验证,则将其发送到登录屏幕。

我的全局对象扩展了使用身份验证过滤器的 WithFilters 类:

object Global extends WithFilters(AuthenticationFilter()) { }

我的身份验证过滤器:

class AuthenticationFilter  extends Filter {
def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
println("this is the request that will be filtered: " + request)
if (!authenticated)
// How do i send the request to the login Action?
else
next(request)
}
}

object AuthenticationFilter {
def apply(actionNames: String*) = new AuthenticationFilter()
}

我的问题是如何将未经身份验证的用户发送到登录操作/路由?

最佳答案

为安全路由创建特征。在未经身份验证的请求进入时重定向它们的特征:

trait Secured {

/**
* Retrieve the connected user name from the request header.
*/
private def username(request: RequestHeader) = request.session.get("username")

/**
* Redirect to login if the user in not authorized.
*/
private def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)


/**
* Action for authenticated users.
*/
def IsAuthenticated(f: => String => Request[AnyContent] => Result) = Security.Authenticated(username, onUnauthorized) { user =>
Action(request => f(user)(request))
}


}

现在定义任何您想要保护的 Controller 以扩展该特征,未经身份验证的请求将被发送出去:

object Index extends Controller with Secured

关于scala - 将未经身份验证的请求发送到不同的操作路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26635043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com