java - @Secured 和@PreAuthorize 注解在哪些方法中起作用?

标签 java spring spring-security

我有以下示例:

任何 Controller :

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

}

任何服务:

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

}
  1. 注释@Secured 是否可以在“WhateverService”的“验证”方法中起作用?
  2. 如果不会,那是为什么?
  3. 同样的行为适用于注解@PreAuthorize?

最佳答案

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

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

@PreAuthorize 实际上是一样的,除了它允许更高级的行为。

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

启用 Pre/post 注释

关于java - @Secured 和@PreAuthorize 注解在哪些方法中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421785/

相关文章:

java - 为什么 saveStateInstance 在屏幕方向上不起作用?

java - 从 spring-boot-starter-parent 继承依赖项的 Maven pom.xml 不起作用

java - Maven如何设置java中可见的属性

java - Spring Boot 自定义身份验证提供程序登录后重定向不起作用

java - Spring Security认证简单登录

java - Spring Security 默认登录表单无法加载 CSS 文件(ERR_CONNECTION_TIMED_OUT)

java - 返回上一个 Activity 时结果不一致

java - 在 OSGI 4.2 包中使用 JAX-WS 时出现 NoClassDefFoundError

java - 星火 2.0.1 java.lang.NegativeArraySizeException

java - 如何将Spring Web服务上线?