Apache Shiro核心功能之Authorization(四)

152 阅读2分钟

Authorization is essentially access control - controlling what your users can access in your application, such as resources, web pages, etc.

Authorization本质上是访问控制——控制你的用户可以在你的应用程序中访问什么,比如资源、网页等等。

本系列文章目录如下:

  1. 为什么要使用Apache Shiro(一)
  2. Apache Shiro的三个重要概念(二)
  3. Apache Shiro核心功能之Authentication(三)
  4. Apache Shiro核心功能之Authorization(四)
  5. Apache Shiro核心功能之Session Management(五)
  6. Apache Shiro核心功能之Cryptography(六)
  7. Apache Shiro集成
  8. 将Apache Shiro集成到Spring-Boot应用程序中

大多数用户通过使用角色和权限等概念来执行访问控制。 也就是说,通常是根据分配给用户的角色、权限来允许用户执行或不执行某些操作。然后,应用程序可以根据对这些角色和权限的检查来控制公开哪些功能。正如您所料,Subject API允许您非常容易地执行角色和权限检查。

角色检查

角色检查有一个明显的缺陷:您不能在运行时添加或删除角色。 你的代码是用角色名硬编码的,所以如果你改变了角色名、配置,你的代码就会崩溃! 如果您需要能够在运行时更改角色的含义,或者根据需要添加或删除角色,则必须依赖其他方法。

角色检查

if ( subject.hasRole("administrator") ) {
    //show the 'Create User’ button
} else {
    //grey-out the button?
} 

权限检查

权限检查是执行授权的另一种方法。

Permission Check

if ( subject.isPermitted("user:create") ) {
    //show the ‘Create User’ button
} else {
    //grey-out the button?
} 

Shiro通过其WildcardPermission支持这种开箱即用的约定。 尽管超出了本文的介绍范围,但您将看到,WildcardPermission在创建安全策略时可以非常灵活,甚至支持实例级(instance-level)访问控制等内容。

实例级Permission Check

if ( subject.isPermitted("user:delete:jsmith") ) {
    //delete the ‘jsmith’ user
} else {
    //don’t delete ‘jsmith’
}

如果愿意,您甚至可以发明自己的权限语法。参考:shiro.apache.org/permissions…

最后

就像身份验证(authentication)一样,上述调用最终会到达SecurityManager, SecurityManager将结合一个或多个Realm来做出访问控制决策。 这允许Realm根据需要同时响应authenticationauthorization操作。