Shiro权限使用

首先什么是shiro?

shiro是apache下面的一个开源项目,下面是其网站上对其的一段说明:

Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.

弱弱的翻译一下:apache shiro是一个强大且易于使用的java安全框架,使用它可以进行

1:认证

2:鉴权

3:加密

4:会话管理

通过shiro简单易懂的api,可以简单快速的为任何应用程序提供安全保护。

什么是认证?

认证就是登陆一个系统之前,认证就是系统通过用户的输入去辨别登陆的用户是谁,认证过程中,用户需要提供一些输入让系统辨别且信任你。

The Shiro framework is designed to make authentication
as clean and intuitive as possible while providing a rich set of
features. Below is a highlight of the Shiro authentication features.

shiro框架在提供丰富功能的同时提供了直观简单的使用方式,下面是shiro提供的几种认证功能。

  • Subject Based - Almost everything you
    do in Shiro is based on the currently executing user, called a Subject.
    And you can easily retrieve the Subject anywhere in your code. This
    makes it easier for you to understand and work
    with Shiro in your applications.

Subjecet-在shiro中几乎所有的操作都是基于当前指定的用户,也称为subject,在代码的任何位置都可以轻易的访问到subject,这使在你的项目中使用shiro变得更易于理解

  • Single Method call - The authentication
    process is a single method call. Needing only one method call keeps the
    API simple and your application code clean, saving you time and effort.

单个方法调用-认证过程仅仅是一个方法的调用,这让你应用的代码更加简洁,给你节省了时间

  • Rich Exception Hierarchy -
    Shiro offers a rich exception hierarchy to offered detailed
    explanations for why a login failed. The hierarchy can help you more
    easily diagnose code bugs or customer services
    issues related to authentication. In addition, the richness can help
    you create more complex authentication functionality if needed.

丰富的异常体系-shiro提供了丰富的异常以便于更加详细的了解登陆失败的原因,这些异常让我们方便定位以及修改bug

  • ‘Remember Me’ built in -
    Standard in the Shiro API is the ability to remember your users if they
    return to your application. You can offer a better user experience to
    your them with minimal
    development effort

remember me功能内置的支持:shiro中remember me功能的api可以给你应用更好的用户体验。

  • Pluggable data sources -
    Shiro uses pluggable data access objects (DAOs), called Realms, to
    connect to security data sources like LDAP and Active Directory. To help
    you avoid
    building and maintaining integrations yourself, Shiro provides
    out-of-the-box realms for popular data sources like LDAP, Active
    Directory, Kerberos, and JDBC. If needed, you can also create your own
    realms to support specific functionality not included in
    the basic realms.


插拔的数据源-shiro使用被称为Reamls的可插拔的数据连接对象来连接你的数据源,例如:LDAP,避免你自己去构建以及维护这些交
互,shiro内置提供了几种常用的数据源接入机制,如果有必要,你可以自己创建特殊的Reaml来提供基础Reamls所不支持的功能。

  • Login with one or more realms -
    Using Shiro, you can easily authenticate a user against one or more
    realms and return one unified view of their identity. In addition, you
    can
    customize the authentication process with Shiro’s notion of an
    authentication strategy. The strategies can be setup in configuration
    files so changes don’t require source code modifications– reducing
    complexity and maintenance effort.

通过一个或者多个realms进行登录认证-使用shiro可以轻易的认证一个用户并提供一个统一的试图,此外我们还可以定制化认   证的策略,我们可以在配置文件中进行配置而不必修改代码。

什么是鉴权?

鉴权也被成为权限控制,判断是否有权限访问某个资源,shiro对鉴权提供的支持:

  • Checks based on roles or permissions -
    Since the complexity of authorization differs greatly between
    applications, Shiro is designed to be flexible, supporting both
    role-based security and permission-based security based on
    your projects needs.

提供基于角色和权限的方式进行鉴权

  • Powerful and intuitive permission syntax -
    As an option, Shiro provides an out-of-the-box permission syntax,
    called Wildcard Permissions, that help you model the fine grained access
    policies your application may have. By using
    Shiro’s Wildcard Permissions you get an easy-to-process and human
    readable syntax. Moreoever, you don’t have to go through the
    time-consuming effort and complexity of creating your own method for
    representing your access policies.

强大且直观的权限规则,shiro提供通配符进行权限的校验,使用通配符规则可读性较高

  • Multiple enforcement options –
    Authorization checks in Shiro can be done through in-code checks, JDK
    1.5 annotations, AOP, and JSP/GSP Taglibs. Shiro’s goal is to give you
    the choice to use the option you think are best based
    on your preferences and project needs.

多种鉴权方式可选,可以使用jdk1.5中的注解,aop或者jsp标签

  • Strong caching support - Any of the
    modern open-source and/or enterprise caching products can be plugged in
    to Shiro to provide a fast and efficient user-experience. For
    authorization, caching is crucial for performance in larger
    environments or with more complex policies using back-end security data
    sources.

高效的缓存支持

  • Supports any data model - Shiro can
    support any data model for access control– it doesn’t force a model on
    you. Your realm implementation ultimately decides how your permissions
    and roles are grouped together and whether to
    return a “yes” or a “no” answer to Shiro. This feature allows you to
    architect your application in the manner you chose and Shiro will bend
    to support you.

支持任何类型的数据模型

再来看看shiro几个关键的概念:

Subject:Subject我们在上面说过,Subject一般来说代表当前登录的用户,我们可以在自己的代码中很容易的获取到Subject对象

  1. Subject currentUser = SecurityUtils.getSubject();

获得Subject对象之后我们可以通过Subject对象进行授权检查。

  1. AuthenticationToken token = new UsernamePasswordToken(username, password);
  2. Subject.isPermitted()/checkRoles()
  3. Subject.login(token)//登录操作
  4. Subject.logout()//退出登录操作

SecurityManager:Subject
代表某一个用户,而SecurityManager就是对这些Subject进行管理的对象,在web项目中使用shiro的时候,我们通常在xml文件
中配置好SecurityManager对象,然后就不会跟它打太多的交道,而仅仅是访问Subject的api.

  1. //这里我们使用spring和shiro进行集成
  2. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  3. <property name="realm" ref="shiroDbRealm" />
  4. <property name="cacheManager" ref="shiroEhcacheManager" />
  5. </bean>

Realms:shiro中使用Realms这个概念表示与数据进行交互的那一层,封装了数据源连接的细节,我们可以实现不同的realms来连接不同的数据源,通过realms读取用户数据用于认证和鉴权。

下面我们使用shiro和spring集成,对web项目进行控制,shiro与spring的集成灰常的简单。

在已经配置好的spring项目中,我们在xml中加入:

  1. <filter>
  2. <filter-name>shiroFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. <init-param>
  5. <param-name>targetFilterLifecycle</param-name>
  6. <param-value>true</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>shiroFilter</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>


个时候我们可能想DelegatingFilterProxy是个什么东东,难道这个就是shiro的入口么?但是通过查看这个类是位于spring-
web这个jar包中的,根本就不属于shiro的一部分,那么也不可能是shiro的入口,我们跟进去发现这个类继承了抽象类
GenericFilterBean,而GenericFilterBean实现了Filter接口,应用程序启动的时候应该会调用
GenericFilterBean.init()方法:该方法设置了filter的配置,另外调用了方法initFilterBean(),这个方法在
子类中进行实现。

DelegatingFilterProxy类中对initFilterBean方法进行了实现:

  1. @Override
  2. protected void initFilterBean() throws ServletException {
  3. synchronized (this.delegateMonitor) {
  4. if (this.delegate == null) {
  5. // If no target bean name specified, use filter name.
  6. if (this.targetBeanName == null) {
  7. this.targetBeanName = getFilterName();
  8. }
  9. // Fetch Spring root application context and initialize the delegate early,
  10. // if possible. If the root application context will be started after this
  11. // filter proxy, we‘ll have to resort to lazy initialization.
  12. WebApplicationContext wac = findWebApplicationContext();
  13. if (wac != null) {
  14. this.delegate = initDelegate(wac);
  15. }
  16. }
  17. }
  18. }

如果没有设置targetBeanName属性,那么就使用过滤器的名字作为beanName

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager" />
  3. <property name="loginUrl" value="/login" />
  4. <property name="successUrl" value="/management/index" />
  5. <property name="filters">
  6. <map>
  7. <!-- <entry key="authc" value-ref="baseFormAuthenticationFilter"/> -->
  8. <!-- 是否启用验证码检验 -->
  9. <entry key="authc" value-ref="captchaFormAuthenticationFilter" />
  10. <entry key="user" value-ref="dWZUserFilter" />
  11. </map>
  12. </property>
  13. <property name="filterChainDefinitions">
  14. <value>
  15. /Captcha.jpg = anon
  16. /styles/** = anon
  17. /login/timeout = anon
  18. /login = authc
  19. /logout = logout
  20. /** = user
  21. </value>
  22. </property>
  23. </bean>

我们在web.xml中配置的过滤器名称是shiroFilter,然后我们在spring的配置文件中以该名字配置一个bean

  1. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  2. <property name="realm" ref="shiroDbRealm" />
  3. <!--  缓存用户的授权信息  -->
  4. <property name="cacheManager" ref="shiroEhcacheManager" />
  5. </bean>
  6. <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
  7. <property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />
  8. </bean>
  9. <bean id="shiroDbRealm" class="com.mbb.ShiroDbRealm" depends-on="userDAO, userRoleDAO, moduleDAO, organizationRoleDAO,captchaService">
  10. </bean>

ShiroDbRealm是我们自定义实现的realms用于查询用户数据。

    1. public class ShiroDbRealm extends AuthorizingRealm {
    2. //实现用户的认证
    3. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    4. User user = userService.get(authcToken.getUsername());
    5. ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername(), user);
    6. <pre code_snippet_id="239402" snippet_file_name="blog_20140316_8_5493693" name="code" class="html">             return new SimpleAuthenticationInfo(shiroUser, user.getPassword(),ByteSource.Util.bytes(salt), getName());
    7. </pre> }<br>
    8. //实现用户的鉴权<br>
    9. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {<br>
    10. Collection<?> collection = principals.fromRealm(getName());<br>
    11. if (CollectionUtils.isEmpty(collection)) {<br>
    12. return null;<br>
    13. }<br>
    14. ShiroUser shiroUser = (ShiroUser) collection.iterator().next();<br>
    15. <br>
    16. List<UserRole> userRoles = userRoleService.find(shiroUser.getId());<br>
    17. List<OrganizationRole> organizationRoles = organizationRoleService<br>
    18. .find(shiroUser.getUser().getOrganization().getId());<br>
    19. <br>
    20. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();<br>
    21. info.addStringPermissions(makePermissions(userRoles, organizationRoles, shiroUser));<br>
    22. <br>
    23. return info;<br>
    24. }<br>
    25. }
    26. <pre></pre>
    27. <p></p>
    28. <pre></pre>
    29. <br>
    30. <br>
    31. <p></p>
    32. <p><br>
    33. </p>
    34. <br>
    35. <p></p>
    36. <ul style="">
    37. <br>
    38. </ul>
    39. <br>
    40. <p></p>
时间: 2024-08-06 16:06:15

Shiro权限使用的相关文章

Shiro权限控制框架入门1:Shiro的认证流程以及基本概念介绍

前言:我在最开始学习Shiro这个框架时,在网上搜索到的一个介绍比较全面的教程是:<跟我学Shiro>系列教程.但是在我看了他写的前几篇文章后,我发现虽然他在这个系列教程中把shiro的一些特性介绍地非常全面详细,但是整个教程的叙述方式还是有很大缺陷的.文章与文章之间并没有很好地串联起来,每篇文章介绍的东西都过于分散了,如果是对shiro完全不了解的新手来看的话完全是一场噩梦.就像一个网友评价的这样: 看了看这个教程,看完之后都想放弃shiro了,完全看不懂,后来百度了很多别的资料才理解了sh

(转) shiro权限框架详解06-shiro与web项目整合(上)

http://blog.csdn.net/facekbook/article/details/54947730 shiro和web项目整合,实现类似真实项目的应用 本文中使用的项目架构是springMVC+mybatis,所以我们是基于搭建好的项目进行改造的. 将shiro整合到web应用中 登录 退出 认证信息在页面展现,也就是显示菜单 shiro的过滤器 将shiro整合到web应用中 数据库脚步 sql脚步放到项目中,项目上传到共享的资源中,文章最后给出共享url. 去除项目中不使用shi

(转)shiro权限框架详解02-权限理论介绍

http://blog.csdn.net/facekbook/article/details/54893042 权限管理解决方案 本文主要介绍权限管理的解决方法: 粗颗粒度和细颗粒度 基于url拦截 使用权限管理框架 粗颗粒度和细颗粒度 什么是粗颗粒度和细颗粒度 在上一文中提到粗颗粒度和细颗粒度,但是没有细讲. 对资源类型的管理称为粗颗粒度权限管理,既只控制到菜单.按钮.方法,粗颗粒度的例子比如:用户具有用户管理的权限,具有导出订单的权限.对资源实例的控制称为细颗粒度权限管理,既控制到数据级别,

Shiro权限框架简介

http://blog.csdn.net/xiaoxian8023/article/details/17892041 Shiro权限框架简介 2014-01-05 23:51 3111人阅读 评论(37) 收藏 举报  分类: [java框架](25)  版权声明:本文为博主原创文章,未经博主允许不得转载.如需转载请声明:[转自 http://blog.csdn.net/xiaoxian8023 ] 目录(?)[+] 最近加入了gxpt项目组,被安排做权限模块,所以也有幸第一次接触到了Shiro

SpringMVC+Shiro权限管理

SpringMVC+Shiro权限管理 什么是权限呢?举个简单的例子: 我有一个论坛,注册的用户分为normal用户,manager用户.对论坛的帖子的操作有这些:添加,删除,更新,查看,回复我们规定:normal用户只能:添加,查看,回复manager用户可以:删除,更新 normal,manager对应的是角色(role)添加,删除,更新等对应的是权限(permission) 我们采用下面的逻辑创建权限表结构(不是绝对的,根据需要修改) 一个用户可以有多种角色(normal,manager,

Spring Boot Shiro 权限管理 【转】

http://blog.csdn.net/catoop/article/details/50520958 主要用于备忘 本来是打算接着写关于数据库方面,集成MyBatis的,刚好赶上朋友问到Shiro权限管理,就先总结下发出来了. 使用Shiro之前用在spring MVC中,是通过XML文件进行配置. 既然现在在写Spring Boot的帖子,就将Shiro应用到Spring Boot中,我本地已经完成了SpringBoot使用Shiro的实例,将配置方法共享一下. 先简单介绍一下Shiro,

shiro 权限验证 AuthorizingRealm doGetAuthorizationInfo

先放代码: https://git.oschina.net/alexgaoyh/alexgaoyh.git 今天在敲代码的过程中,突然发现之前整合的shiro权限框架有问题,doGetAuthorizationInfo() 方法一直没有被调用,后来发现, 1:  doGetAuthorizationInfo()方法可以理解为是权限验证, 2: doGetAuthenticationInfo(  AuthenticationToken token)  理解为登陆验证. 两者是不一样的: 登陆验证:

十、 Spring Boot Shiro 权限管理

使用Shiro之前用在spring MVC中,是通过XML文件进行配置. 将Shiro应用到Spring Boot中,本地已经完成了SpringBoot使用Shiro的实例,将配置方法共享一下. 先简单介绍一下Shiro,对于没有用过Shiro的朋友,也算是做个简介吧. Shiro是Apache下的一个开源项目,我们称之为Apache Shiro.它是一个很易用与Java项目的的安全框架,提供了认证.授权.加密.会话管理,与 Spring Security 一样都是做一个权限的安全框架,但是与S

SpringMVC整合Shiro权限框架

尊重原创:http://blog.csdn.net/donggua3694857/article/details/52157313 最近在学习Shiro,首先非常感谢开涛大神的<跟我学Shiro>系列,在我学习的过程中发挥了很大的指导作用.学习一个新的东西首先就是做一个demo,多看不如多敲,只有在实践中才能发现自己的欠缺,下面记录下来我整合shiro的过程.如果有不足之处,还望各位看官多多指出. 一.基本名词解释 Apache Shiro是一个强大易用的Java安全框架.它可以帮助我们完成:

spring boot shiro -权限管理

spring boot shiro -权限管理 定义 java最常用的框架有spring security 和Apache shiro,因为spring security 庞大和负责,一般使用都是Apache shiro. Apache shiro 是一个功能强大,灵活,开源的安全框架,它可以处理身份验证,授权,企业会话管理,加密等. shiro 易于理解和使用,一个好的框架 应该屏蔽复杂性,向外提供简单,直观的api,简化开发人员实行应用程序安全所发费的时间和精力. shiro 可以做什么: