如何将身份验证指令仅应用于几条路线
How to apply authenticate directive to only a few routes
我通过~
方法构建路由。我的一些路线被 authenticate
指令包围,在某些情况下 returns 拒绝。我在 runRoute
方法的范围内有一个隐式拒绝处理程序。
如何将此指令仅应用于此指令包围的路由?在 rejectionHandler 中,我执行重定向到未被 authenticate 指令包围的路径。在调试中我发现第二个请求(重定向后)也通过我的 contextAuthenticator
编辑
使用 authenticate
指令的示例
val securedRoutes = authenticate(myContextAuthenticator) { implicit user =>
route1 ~
route2
}
这里myContextAuthenticator
的类型是ContextAuthenticator[User]
和receive
方法是
def receive = runRoute {
otherRoutes ~ securedRoutes
}
隐式拒绝处理程序适用于不可恢复的全局拒绝,应将其转换为相应的 HTTP 响应,如 400 或 404。
但是,如果您需要处理特定于路由的拒绝,在您的情况下经过身份验证的路由,spray 具有 handleRejections 指令。
简单的用法是这样的:
val authenticatedRoute = handleRejections(myAuthenticatorRejectionHandler) &
authenticate(myContextAuthenticator)
val securedRoutes = authenticatedRoute { implicit user =>
route1 ~
route2
}
我通过~
方法构建路由。我的一些路线被 authenticate
指令包围,在某些情况下 returns 拒绝。我在 runRoute
方法的范围内有一个隐式拒绝处理程序。
如何将此指令仅应用于此指令包围的路由?在 rejectionHandler 中,我执行重定向到未被 authenticate 指令包围的路径。在调试中我发现第二个请求(重定向后)也通过我的 contextAuthenticator
编辑
使用 authenticate
指令的示例
val securedRoutes = authenticate(myContextAuthenticator) { implicit user =>
route1 ~
route2
}
这里myContextAuthenticator
的类型是ContextAuthenticator[User]
和receive
方法是
def receive = runRoute {
otherRoutes ~ securedRoutes
}
隐式拒绝处理程序适用于不可恢复的全局拒绝,应将其转换为相应的 HTTP 响应,如 400 或 404。
但是,如果您需要处理特定于路由的拒绝,在您的情况下经过身份验证的路由,spray 具有 handleRejections 指令。
简单的用法是这样的:
val authenticatedRoute = handleRejections(myAuthenticatorRejectionHandler) &
authenticate(myContextAuthenticator)
val securedRoutes = authenticatedRoute { implicit user =>
route1 ~
route2
}