@RolesAllowed vs. @PreAuthorize vs. @Secured

前端 未结 3 879
挽巷
挽巷 2021-02-04 01:29

I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

I want to secure a controller

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 02:09

    @Secured and @RolesAllowed perform identical functionality in Spring. The difference is that @Secured is a Spring specific annotaiton while @RolesAllowed is a Java standard annotation (JSR250). Neither one of these annotation support SpEL.

    @PreAuthorize is another Spring specific annotation. You can perform a lot more powerful operations with @PreAuthorize using SpEL. You can write expressions the limit method invocation based on the roles/permissions, the current authenticated user, and the arguments passed into the method.

    @PreAuthorize("hasRole('ADMIN') or #user.id == authentication.name")
    public void deleteUser(User user) {
        ...
    }
    

    http://docs.spring.io/autorepo/docs/spring-security/4.0.x/reference/html/el-access.html#el-common-built-in


    As for which to use, it's really up to you. @Secure and @PreAuthorize will tie your code to Spring. If being tied to Spring is not an issue or you need to perform more powerful operations, use @PreAuthorize.

提交回复
热议问题