权限校验
在主启动类或配置类上添加 @EnableGlobalMethodSecurity(prePostEnabled = true)
注解,开启权限校验功能
然后就可以按照如下方式校验当前登录人是否有权限访问方法
@RequestMapping("/hello")
@PreAuthorize("hasAuthority('test')")
public String hello(){
return "hello";
}
除了hasAuthority()
之外,还有 hasAnyAuthority()
,hasRole()
,hasAnyRole()
等
hasAnyAuthority()
方法可以传入多个权限,只有用户有其中任意一个权限都可以访问对应资源。
@RequestMapping("/hello")
@PreAuthorize("hasAnyAuthority('hello1','hello2','hello3')")
public String hello(){
return "hello";
}
hasRole()
要求有对应的角色才可以访问,但是它内部会把传入的参数拼接上 ROLE_
后再去比较。所以这种情况下要用用户对应的权限也要有 ROLE_ 这个前缀才可以。
@RequestMapping("/hello")
@PreAuthorize("hasRole('hello')")
public String hello(){
return "hello";
}
hasAnyRole 有任意的角色就可以访问。它内部也会把我们传入的参数拼接上 ROLE_
后再去比较。所以这种情况下要用用户对应的权限也要有 ROLE_
这个前缀才可以。
@RequestMapping("/hello")
@PreAuthorize("hasAnyRole('hello1','hello2','hello3')")
public String hello(){
return "hello";
}
自定义权限校验
import com.mahe666.domain.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("MyExpressionRoot")
public class MyExpressionRoot {
public boolean hasAuthority(String authority){
//获取当前用户的权限
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
List<String> permissions = loginUser.getPermissions();
//判断用户权限集合中是否存在authority
return permissions.contains(authority);
}
}
在SPEL表达式中使用 @MyExpressionRoot
相当于获取容器中bean的名字为 MyExpressionRoot
的对象。然后再调用这个对象的 hasAuthority()
方法
@RequestMapping("/hello")
@PreAuthorize("@MyExpressionRoot.hasAuthority('test')")
public String hello(){
return "hello";
}