从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
  }
}

如果无法自动生成HandlerMap列表,请自动生成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
  }
}

相关文章