簡體   English   中英

從HttpServletRequest獲取目標控制器

[英]Get destination controller from a HttpServletRequest

我已經設置了spring安全性來認證和授權進入我的應用程序的請求。 我已經將配置設置為:

 public class OAuth2ServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {

            // ...set up token store here

            resources.authenticationEntryPoint(new AuthenticationEntryPoint() {
                @Override
                public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

                 //QUESTION
                 // How do I get the destination controller that this request was going to go to?
                 // Really, I'd like to get some information about the annotations that were on the destination controller.

                    response.setStatus(401);
                }
            });
        }

我想獲取有關此請求將要到達的目標控制器的一些信息。 在這種情況下,控制器實際上並不會受到攻擊,因為Spring Security在到達控制器之前就加入了響應並拋出了響應。

有小費嗎? 謝謝!

假設OAuth2ServerConfiguration是Spring托管的bean,那么它應該對您有用。

...

@Autowired
private List<HandlerMapping> handlerMappings;

for (HandlerMapping handlerMapping : handlerMappings) {
  HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
  if (handlerExecutionChain != null) {
     // handlerExecutionChain.getHandler() is your handler for this request
  }
}

如果無法自動裝配HandlerMapping列表,請自動裝配ApplicationContext並進行如下調整。

for (HandlerMapping handlerMapping : applicationContext.getBeansOfType(HandlerMapping.class).values()) {
  HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
  if (handlerExecutionChain != null) {
     // handlerExecutionChain.getHandler() is your handler for this request
  }
}

您可以嘗試以下方法:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                // handler is the controller
                MyAnnotation annotation = ((HandlerMethod) handler).getMethod().getAnnotation(MyAnnotation.class)
                // do stuff with the annotation
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM