浅谈Shiro

什么是Shiro

简单介绍
  对于Shiro来说不仅可以使用到JavaSE的开发中,还可以使用到JavaEE的开发中,Shiro可以完成的工作有。认证、授权、加密、会话管理、与Web的集成、缓存等等操作,shiro 应用实例 www.1b23.com,在SpringBoot使用前端框架的时候就整合了Shiro并且与Thymeleaf整合的也是非常好。
  下面就是关于Shiro简单的功能架构图
  在这里插入图片描述
Apache Shiro作用

Apache Shiro作用

 Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理,令行应用程序。

Shiro提供了应用程序安全API来执行以下几个方面(我喜欢称这些为应用程序安全的四个基石):

      (1)身份验证 - 验证用户身份,通常称为用户“登录”。

      (2)授权 - 访问控制

      (3)加密 - 保护或隐藏窥探数据

      (4)会话管理 - 即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;

Shiro使用步骤

导入jar

<dependencies>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

准备资源

这个资源可以到shiro的源码文件中拷备
/shiro-root-1.4.0-RC2/samples/quickstart/src/main/resources
shiro.ini

resources下面创建一个shiro.ini文件

[users]
# 用户是root 密码是secret admin这个用户的角色
root = secret, admin
# 用户名是guest 密码guest,角色是guest
guest = guest, guest
presidentskroob = 12345, president

测试代码

public class TestShiro {
    public static void main(String[] args) {
        //得到SecutiryManagerFactory功能 -- IniRealm
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //得到SecutiryManager 核心对象
        SecurityManager securityManager = factory.getInstance();
        //设置到shiro的环境里面 才能运行
        SecurityUtils.setSecurityManager(securityManager);
        //拿到当前用户【Subject:操作当前系统的一个用户】
        Subject subject = SecurityUtils.getSubject();
        //创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("root","secret");
        try {
            subject.login(token);
            System.out.println("登陆成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("账号不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码出问题..");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("其他认证错误");
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值