2016-12-15 70 views
2

我設置了spring安全性來驗證和授權進入我的應用程序的請求。我已經設置了這樣的配置:從HttpServletRequest獲取目的地控制器

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); 
       } 
      }); 
     } 

我想要獲取有關此請求要去的目標控制器的一些信息。在這種情況下,控制器實際上不會受到影響,因爲彈簧安全措施已經啓動並在響應到達控制器之前丟棄了響應。

任何提示? 謝謝!

回答

3

假設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,Autowire 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 
    } 
} 
+1

這是給我一個錯誤說 – Jeff

+2

@Jeff,看到我ammendements –

+0

那工作 - 很好的工作! – Jeff

1

你可以試試這個:「無法找到自動裝配的HandlerMapping或列表 無豆」

@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 
      } 
     }); 
    } 
}