从 HttpServletRequest 获取目标控制器

Jef*_*eff 2 java spring spring-security spring-security-oauth2

我已经设置了 spring security 来验证和授权进入我的应用程序的请求。我已将配置设置如下:

 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);
                }
            });
        }
Run Code Online (Sandbox Code Playgroud)

我想获取有关该请求将要发送到的目标控制器的一些信息。在这种情况下,控制器实际上不会受到攻击,因为 spring 安全性在响应到达控制器之前启动并丢弃了响应。

有小费吗?谢谢!

lan*_*ell 5

假设 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
  }
}
Run Code Online (Sandbox Code Playgroud)

如果无法自动装配 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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Jeff,请参阅我的修正案 (2认同)