2016-11-28 103 views
2

我有一個Spring MVC控制器,並希望通過Spring Method Security來保護它。

在下面的例子它的工作原理 - @RequestMapping@PreAuthorize註釋相同的方法:Spring Security:@PreAuthorize僅與@RequestMapping一起使用

@Controller 
public class MyController { 

    @RequestMapping(value = "/test", method = {RequestMethod.POST, RequestMethod.GET}) 
    @PreAuthorize("isAuthenticated()") 
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     return test(request, response); 
    } 

    public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     ... 
    } 

在這個例子中它不工作 - @RequestMapping@PreAuthorize註釋不同的方法:

@Controller 
public class MyController { 

    @RequestMapping(value = "/test", method = {RequestMethod.POST, RequestMethod.GET}) 
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     return test(request, response); 
    } 

    @PreAuthorize("isAuthenticated()") 
    public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     ... 
    } 


什麼可能是這個奇怪的原因b ehaviour?

+1

http://stackoverflow.com/a/19421786/1291150 –

+0

謝謝你 - 這有助於! – olivmir

回答

2

在第二個示例中,test方法直接從handleRequest方法中調用。 Spring沒有機制在同一個類中攔截方法調用。因此,@PreAutorize開始的代理/ AOP方法從不被調用。

More on the topic of Spring Proxy

+0

謝謝 - 偉大的答案,這有助於!我只想知道,爲什麼在描述'@ PreAuthorize'時,這在教程的任何地方都沒有提及。 :|多好,在stackoverflow上有專家。 – olivmir

+2

@olivmir對Spring在大多數Spring文檔中的工作方式有一定程度的假定知識。如果文檔試圖用這種假定的知識來描述一個特性,或者在Spring如何工作的情況下,那麼這些文檔將非常混亂和重複。 – MarkOfHall

相關問題