@Secured 和 @PreAuthorize 注释使用哪些方法起作用?

Ass*_*sis 2 java spring spring-security

我有以下示例:

无论如何控制器:

@Controller
@RequestMapping(value = "api/whatever")
public class WhateverController {

    @Autowired private WhateverService whateverService;

    @RequestMapping(value = "/list", method = GET)
    @Secured({ "ROLE_WHATEVER_CANSEARCH" })
    @ResponseBody
    public List<WhateverDTO> findList(@RequestParam(value = "values") String[] values) {
        return whateverService.findThings(values);
    }

}
Run Code Online (Sandbox Code Playgroud)

任何服务:

@Service
public class WhateverService {

    @Autowired private WhateverDAO whateverDAO;

    public List<WhateverDTO> findThings(String[] values) {
        //...
        validate();
        return whateverDAO.findThings(values);
    }

    @Secured({ "ROLE_SPECIFICPERMISSION" }) // Throws AccessDeniedException
    private void validate() {
        if(thing) throw new RuntimeException("You can't...");
    }

}
Run Code Online (Sandbox Code Playgroud)
  1. 注释 @Secured 可以在“WhateverService”的“validate”方法中工作吗?
  2. 如果不会,那为什么呢?
  3. 相同的行为适用于注释@PreAuthorize?

Ore*_*ron 7

不,不是因为它是私有的,而是因为 Spring-Security 是基于 Spring-AOP 的。在Spring-AOP上,同一类中的方法之间的调用不会调用方面。

使用@Secured注解,在方法之前进行测试。如果用户没有正确的角色,则会引发异常。

@PreAuthorize 实际上是相同的,只是它允许更高级的行为。

您还可以使用 WebSecurityConfigurerAdapter 配置安全性。并且不要忘记启用前/后注释@EnableGlobalMethodSecurity(prePostEnabled = true)