spring security @Secured()、 @PreAuthorize() 、 @RolesAllowed()

在Spring security的使用中,为了对方法进行权限控制,通常采用的三个注解,就是@Secured()、@PreAuthorize()、@RolesAllowed()。

示例,修改用户密码必须是ADMIN权限,可以用三种方法:

@Secured({"ROLE_ADMIN"})
public void changePassword(String username, String password);

@RolesAllowed({"ROLE_ADMIN"})
public void changePassword(String username, String password);

@PreAuthorize("hasRole(‘ROLE_ADMIN‘)")
public void changePassword(String username, String password);

1. @Secured(): secured_annotation

使用前配置Spring Security (无论是xml方式,还是Spring boot注解方式,都需要指定secured-annotations)

XML: <global-method-security secured-annotations="enabled"/>

Spring boot: @EnableGlobalMethodSecurity(securedEnabled = true)

2. @RolesAllowed(): jsr250-annotations

使用前配置Spring Security (无论是xml方式,还是Spring boot注解方式,都需要指定jsr250-annotations)

XML: <global-method-security jsr250-annotations="enabled"/>

Spring boot: @EnableGlobalMethodSecurity(jsr250Enabled = true)

3. @PreAuthorize(): pre-post-annotations

使用前配置Spring Security (无论是xml方式,还是Spring boot注解方式,都需要指定pre-post-annotations)

XML: <global-method-security pre-post-annotations="enabled"/>

Spring boot: @EnableGlobalMethodSecurity(prePostEnabled = true)
原文地址:https://www.cnblogs.com/Mike_Chang/p/10548861.html