Shiro 简单介绍和快速入门。

一、shiro是啥?

/*
* Shiro ?
  安全框架是一个
  1.功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理,并可用于保护任何应用程序 - 从命令行应用程序,移动应用程序到最大的Web和企业应用程序。
  2.Shiro提供了应用程序安全API来执行以下方面(我喜欢将这些称为应用程序安全性的4个基石):

1.身份验证  Authentication  证明用户的部分,称为用户的“登录”。
2.授权      Authorization   访问控制
3.密码学    Cryptography    保护或隐藏窥探数据的数据
4.会话管理  Session Message  每个用户时间敏感状态。

工作流程?
Application Code.
1.subject  封装信息。
    抽象的用户;登录系统的用户
    将用户交给SecurityManager 管理。处理

2.SecurityManager: 安全管理器。
    核心。

    2.1门面模式?
    用户-----代理-----具体的功能。(根据需要找具体的功能呢)

3.Realms :领域。  相等于shiro和应用程序安全数据之间的  连接器。


流程梳理?
1.获取用户名和密码
2.通过subject封装 将用户交给SecurityManager 管理。处理
3.SecurityManager  安全管理器----->不同的子项管理器
4.通过Realm 实现shiro和数据源的联系
            ini   保存数据的配置文件  不用连接数据库  模拟用户存储数据库信息。

* */

二、创建一个java工程的maven项目。 导入相关jar包

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.aaa</groupId>
  <artifactId>DemoShiro</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>DemoShiro</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>
    <spring.version>5.1.1.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--引入shiro-->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>1.3.2</version>
    </dependency>

    <!--解决Spring使用slf4j输出日志与log4j冲突的问题-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.6</version>
    </dependency>
    <!-- log4j的包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.6</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

三,在SRC下新建资源目录resources ,添加两个配置文件。

1.log4j.properties 外部配置文件

2.ini   常用的一种保存数据的配置文件 

这两份文件可以在shiro的官网上下载。

 四、测试效果。   Quickstart  这个类文件也是直接在官网上下载以后,直接拿过来用的。 

package com.zxf;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Quickstart {
    //获取日志对象
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
    
    public static void main(String[] args) {
//        加载配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        
        //获取安全管理器对象
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        
        //获取当前的用户信息  工具类获取  直接调用
        Subject currentUser = SecurityUtils.getSubject();
        
        //模拟会话管理
        Session session = currentUser.getSession();
        session.setAttribute("user", "张三");

        //取出值
        String value = (String) session.getAttribute("user");
        if (value.equals("张三")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }
        
//        判断当前用户是否已经认证
        if (!currentUser.isAuthenticated()) {

            //用户名密码令牌     UserNamePasswordToken  令牌
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");

            //记住我   是否记住
            token.setRememberMe(true);
            try {
                //调用登录方法   然后交给管理器
                //调用Suject.login方法 ---》安全管理器--->认证器 ,授权器
                currentUser.login(token);
            } catch (UnknownAccountException uae) {//账号不存在
                log.info("账号不存在" + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {//密码错误
                log.info("密码错误 " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {//账号锁死
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            catch (AuthenticationException ae) {
            }
        }
        //都正确 就提示登录成功。
        log.info("用户登录 [" + currentUser.getPrincipal() + "] logged in successfully.");

        //授权验证:  模拟角色
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
    }
        //模拟权限
        if (currentUser.isPermitted("lightsaber:weild")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //模拟注销
        //all done - log out!
        currentUser.logout();

        System.exit(0);
    }
}
原文地址:https://www.cnblogs.com/ZXF6/p/11341420.html