【问题标题】:How to intercept requests by handler method in Spring WebFlux如何通过 Spring WebFlux 中的处理程序方法拦截请求
【发布时间】:2018-10-31 13:47:19
【问题描述】:

我在 Spring MVC 中有以下拦截器,用于检查用户是否可以访问处理程序方法:

class AccessInterceptor : HandlerInterceptorAdapter() {

override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any?): Boolean {
    val auth: Auth =
        (if (method.getAnnotation(Auth::class.java) != null) {
            method.getAnnotation(Auth::class.java)
        } else {
            method.declaringClass.getAnnotation(Auth::class.java)
        }) ?: return true
    if (auth.value == AuthType.ALLOW) {
        return true
    }

    val user = getUserFromRequest(request) // checks request for auth token
    // and checking auth for out user in future.
    return renderError(403, response)

在我的控制器中,我会注释方法,如下所示:

@GetMapping("/foo")
@Auth(AuthType.ALLOW)
fun doesntNeedAuth(...) { ... }

@GetMapping("/bar")
@Auth(AuthType.ADMIN)
fun adminMethod(...) { ... }

如果用户的令牌错误或没有权限,则会返回错误。
是否可以在 Spring WebFlux 中使用注释样式的控制器来执行此操作?

【问题讨论】:

标签: spring spring-mvc spring-webflux


【解决方案1】:

为了解决这个问题,我很可能会使用:

  • 来自WebHandler API 的Spring Reactive Web WebFilter 用于拦截传入的请求

  • RequestMappingHandlerMapping 检索处理当前请求的方法

@Autowired
RequestMappingHandlerMapping requestMappingHandlerMapping;

...
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ...
    HandlerMethod handler = (HandlerMethod) requestMappingHandlerMapping.getHandler(exchange).toProcessor().peek();
    //your logic
}

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    相关资源
    最近更新 更多