shiro身份验证实验

shiro身份验证

1. 验证程序

Apache Shiro官网:http://shiro.apache.org/

我们可以通过源代码中例子来学习Shiro

1)pom.xml依赖

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.2</version>
</dependency>

 

(2)编辑shiro的静态数据shiro.ini文件

#   这个文件是设置用户、角色、权限    [users]描述下方是用户信息
[users]
# 设置用户及角色信息    格式:用户名=密码,角色,角色[可以有多个角色]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# 用户: 'lonestarr' 密码: 'vespa' and 角色 :'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

[roles]             # 设置角色 和 权限
# 'admin' role has all permissions, indicated by the wildcard '*'  【拥有全部权限,用*表示】

admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)

goodguy = winnebago:drive:eagle5

3)演示测试类

shiro身份验证实验

shiro身份验证实验

shiro身份验证实验

2. 身份认证流程

shiro身份验证实验

shiro身份验证实验

流程如下:

  • 首先调用 Subject.login(token) 进行登录,其会自动委托给 Security Manager,调用之前必须通过 SecurityUtils.setSecurityManager() 设置;
  • SecurityManager 负责真正的身份验证逻辑;它会委托给 Authenticator 进行身份验证;
  • Authenticator 才是真正的身份验证者,Shiro API 中核心的身份认证入口点,此处可以自定义插入自己的实现;
  • Authenticator 可能会委托给相应的 AuthenticationStrategy 进行多 Realm 身份验证,默认 ModularRealmAuthenticator 会调用 AuthenticationStrategy 进行多 Realm 身份验证;
  • Authenticator 会把相应的 token 传入 Realm,从 Realm 获取身份验证信息,如果没有返回 / 抛出异常表示身份验证失败了。此处可以配置多个 Realm,将按照相应的顺序及策略进行访问。