shiro简单入门

什么是shiro


   shiro是apache的一个开源框架的权限管理框架,实现 用户认证、用户授权。
   shiro不依赖于spring,shiro不仅可以实现 web应用的权限管理,还可以实现c/s系统,分布式系统权限管理,shiro属于轻量框架。

Shiro核心名词


   Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject 都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者


   SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager 交互;且它管理着所有Subject;可以看出它是Shiro 的核心,它负责与后边介绍的其他组件进行交互,可以把它看成SpringMVC 的DispatcherServlet前端控制器;


   Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。


shiro架构


  1 subject:主体,可以是用户也可以是程序,主体要访问系统,系统需要对主体进行认证、授权。
  2 securityManager:安全管理器,主体进行认证和授权都是通过securityManager进行。securityManager是一个集合,  真正做事的不是securityManager而是它里面的东西。
  3 authenticator:认证器,主体进行认证最终通过authenticator进行的。
  4 authorizer:授权器,主体进行授权最终通过authorizer进行的。
  5 sessionManager:web应用中一般是用web容器(中间件tomcat)对session进行管理,shiro也提供一套session管理的方式。
                      shiro不仅仅可以用于web管理也可以用于cs管理,所以他不用web容器的session管理
  6 SessionDao:  通过SessionDao管理session数据,针对个性化的session数据存储需要使用sessionDao
                    (如果用tomcat管理session就不用SessionDao,如果要分布式的统一管理session就要用到SessionDao)。
  7 cache Manager:缓存管理器,主要对session和授权数据进行缓存(权限管理框架主要就是对认证和授权进行管理,
                     session是在服务器缓存中的),比如将授权数据通过cacheManager进行缓存管理,
                     和ehcache整合对缓存数据进行管理(redis是缓存框架)。
  8 realm:域,领域,相当于数据源,通过realm存取认证、授权相关数据(原来是通过数据库取的)。
             注意:authenticator认证器和authorizer授权器调用realm中存储授权和认证的数据和逻辑。
  9 cryptography:密码管理,比如md5加密,提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。比如 md5散列算法(md5只有加密没有解密)。

shiro简单入门代码(基于ini文件)

java端代码
public static void main(String[] args) {
//        读取文件realm文件,得到securityManager工厂
        IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");
//        通过securityManager工厂生产securityManager
        SecurityManager instance = securityManagerFactory.getInstance();
//        将securityManager交给securityUtil工具包管理
        SecurityUtils.setSecurityManager(instance);
//        从securityUtil工具包中拿到当前登录的suject主体
        Subject subject = SecurityUtils.getSubject();
//        通过用户名密码生成shiro框架的唯一身份标识token
        UsernamePasswordToken token = new UsernamePasswordToken("zs","123");
//        登录主体通过token进行登录
        try {
            subject.login(token);
            System.out.println("登陆成功!!!");
        }catch (Exception e){
            System.out.println("登陆失败!!!"+e);
        }

        subject.logout();

    }
web应用实现(shiro集成web(shiro-web.ini))

基本步骤: 配置shiro-web.ini文件

[main]
#定义身份认证失败后的请求url映射,loginUrl是身份认证过滤器中的一个属性
authc.loginUrl=/login
#定义角色认证失败后的请求url映射,unauthorizedUrl是角色认证过滤器中的一个属性
roles.unauthorizedUrl=/unauthorized.jsp
#定义权限认证失败后请求url映射,unauthorizedUrl是角色认证过滤器中的一个属性
perms.unauthorizedUrl=/unauthorized.jsp

[users]
zs=123,role1
ls=123,role2
ww=123,role3
zdm=123,admin


[roles]
role1=user:create
role2=user:create,user:update
role3=user:create,user:update,user:delete,user:view,user:load
admin=user:*



#定义请求的地址需要做什么验证
[urls]
#请求login的时候不需要权限,游客身份即可(anon)
/login.do=anon

#请求/user/updatePwd.jsp的时候,需要身份认证(authc)
/user/updatePwd.jsp=authc

#请求/admin的时候,需要角色认证,必须是拥有admin角色的用户才行
/admin/*.jsp=roles[admin]

#请求/teacher的时候,需要权限认证,必须是拥有user:create权限的角色的用户才行
/user/teacher.jsp=perms["user:update"]

 导入pom依赖

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>

    <!-- 添加相关依赖 -->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <log4j2.version>2.9.1</log4j2.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>

    <shiro.version>1.2.5</shiro.version>
  </properties>

  <dependencies>
    <!-- shiro核心包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <!-- 添加shiro web支持 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <!--**********junit**********-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <!--**********servlet**********-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <!-- **********************  日志配置  ********************** -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
      <scope>runtime</scope>
      <exclusions>
        <exclusion>
          <artifactId>slf4j-api</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <!--2) 用于与slf4j保持桥接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>slf4j-api</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <!--3) 核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--4) web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>
    <!--5) 需要使用log4j2的AsyncLogger需要包含disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>
  </dependencies>

通过监听器EnvironmentLoaderListener读取配置文件,来创建相应的WebEnvironment

    <context-param>
        <param-name>shiroConfigLocations</param-name>
        <param-value>classpath:shiro-web.ini</param-value>
    </context-param>
    <listener>
        <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>ShiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ShiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

      :1、可通过shiroConfigLocations参数,指定shiro的配置文件
              2、shiroConfigLocations 默认是“/WEB-INF/shiro.ini”,IniWebEnvironment默认是先从/ WEB-INF/shiro.ini加载,
           如果没有就默认加载 classpath:shiro.ini。

servlet的测试代码

 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            req.getSession().setAttribute("username",username);
            resp.sendRedirect(req.getContextPath()+"/main.jsp");
        }catch (Exception e){
            req.setAttribute("message","用户名或者密码错误!!");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }


    }

猜你喜欢

转载自blog.csdn.net/qq_41277773/article/details/85327200