Spring Security6 教程

基于表达式的访问控制

Spring Security 使用 SpEL(Spring Expression Language)来支持表达式,如果你有兴趣更深入地了解这个话题,你应该看看它是如何工作的。

SpEL 表达式是以 "根对象" (root object)作为评估上下文的一部分进行评估。Spring Security 使用用于 Web 和方法安全的特定类作为根对象,以提供内置的表达式和对值的访问。

注意,Spring Security 的 SpEL 表达式根对象的基类是 SecurityExpressionRoot。根对象提供了一些常见的表达式,在 web 和方法安全中都可以使用,如下表:

表达式说明

hasRole(String role)

如果当前的principal 有指定的角色,则返回 true。

例如: hasRole('admin')

默认情况下,如果提供的角色不是以 ROLE_ 开头,就会被添加。你可以通过修改 DefaultWebSecurityExpressionHandler 的 defaultRolePrefix 来定制这一行为。

hasAnyRole(String… roles)

如果当前的 principal 有任何提供的角色(以逗号分隔的字符串列表形式给出),则返回 true。

例如: hasAnyRole('admin', 'user').

默认情况下,如果提供的角色不是以 ROLE_ 开头,它就会被添加。你可以通过修改 DefaultWebSecurityExpressionHandler 的 defaultRolePrefix 来定制这一行为。

hasAuthority(String authority)

如果当前 principal 有指定的权限,则返回 true。

例如: hasAuthority('read')

hasAnyAuthority(String… authorities)

如果当前 principal 有任何提供的授权(以逗号分隔的字符串列表形式给出),则返回 true。

例如: hasAnyAuthority('read', 'write').

principal

允许直接访问代表当前用户的 principal 对象。

authentication

允许直接访问从`SecurityContext`获得的当前`Authentication`对象。

permitAll

结果总是为 true。

denyAll

结果总是为 false。

isAnonymous()

如果当前 principal 是匿名用户,返回 true。

isRememberMe()

如果当前 principal 是一个记住我(remember-me)的用户,返回`true`。

isAuthenticated()

如果用户不是匿名的,返回 true。

isFullyAuthenticated()

如果该用户不是匿名用户,也不是remember-me用户,则返回 true。

hasPermission(Object target, Object permission)

如果用户对所提供的目标有访问权限,返回 true。 例如, hasPermission(domainObject, 'read').

hasPermission(Object targetId, String targetType, Object permission)

如果用户对所提供的目标有访问权限,返回 true。 例如, hasPermission(1, 'com.example.domain.Message', 'read').

点击查看 SecurityExpressionRoot (spring-security-docs 6.5.0 API) 类的 JavaDoc。

参考资料地址:基于表达式的访问控制 :: Spring Security Reference

 

说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号