1.Shiro简介
我们可以理解为跟SpringSecurity框架差不多的框架只不过更加的完美:
Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。
Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。
记住一点,Shiro 不会去维护用户、维护权限;这些需要我们自己去设计 / 提供;然后通过相应的接口注入给 Shiro 即可。


可以看到:应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject;其每个 API 的含义:
Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;
SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,你可以把它看成 DispatcherServlet 前端控制器;
Realm:域,Shiro 从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。
也就是说对于我们而言,最简单的一个 Shiro 应用:
应用代码通过 Subject 来进行认证和授权,而 Subject 又委托给 SecurityManager;
我们需要给 Shiro 的 SecurityManager 注入 Realm,从而让 SecurityManager 能得到合法的用户及其权限进行判断。
从以上也可以看出,Shiro 不提供维护用户 / 权限,而是通过 Realm 让开发人员自己注入。
2.快速开始
老规矩去官网查看,然后下载代码看能不能运行。
项目结构:

pom.xml
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- <version>1.4.1</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.21</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>jcl-over-slf4j</artifactId>
- <version>1.7.21</version>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.1.1</version>
- </dependency>
复制代码
log4j
- log4j.rootLogger=INFO, stdout
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
- # General Apache libraries
- log4j.logger.org.apache=WARN
- # Spring
- log4j.logger.org.springframework=WARN
- # Default Shiro logging
- log4j.logger.org.apache.shiro=INFO
- # Disable verbose logging
- log4j.logger.org.apache.shiro.util.ThreadContext=WARN
- log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
复制代码
shiro.ini
- [users]
- # user 'root' with password 'secret' and the 'admin' role
- root = secret, admin
- # user 'guest' with the password 'guest' and the 'guest' role
- guest = guest, guest
- # user 'presidentskroob' with password '12345' ("That's the same combination on
- # my luggage!!!" ;)), and role 'president'
- presidentskroob = 12345, president
- # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
- darkhelmet = ludicrousspeed, darklord, schwartz
- # user 'lonestarr' with password 'vespa' and roles '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
复制代码
Quickstart.java
- 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;
- /**
- * @author lee
- * @date 2020/8/11 - 6:24 下午
- */
- 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
- Subject currentUser = SecurityUtils.getSubject();
- // 通过当前用户拿到Session
- Session session = currentUser.getSession();
- session.setAttribute("someKey", "aValue");
- String value = (String) session.getAttribute("someKey");
- if (value.equals("aValue")) {
- log.info("Subject=>session[" + value + "]");
- }
- //判断当前用户是否被认证
- if (!currentUser.isAuthenticated()) {
- //Token: 令牌
- UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
- token.setRememberMe(true);//设置记住我
- try {
- currentUser.login(token);//执行登陆操作
- } catch (UnknownAccountException uae) {
- log.info("There is no user with username of " + token.getPrincipal());
- } catch (IncorrectCredentialsException ice) {
- log.info("Password for account " + 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 more exceptions here (maybe custom ones specific to your application?
- catch (AuthenticationException ae) {
- //unexpected condition? error?
- }
- }
- //say who they are:
- //print their identifying principal (in this case, a username):
- log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
- //test a role:
- if (currentUser.hasRole("schwartz")) {
- log.info("May the Schwartz be with you!");
- } else {
- log.info("Hello, mere mortal.");
- }
- //test a typed permission (not instance-level)
- if (currentUser.isPermitted("lightsaber:wield")) {
- log.info("You may use a lightsaber ring. Use it wisely.");
- } else {
- log.info("Sorry, lightsaber rings are for schwartz masters only.");
- }
- //a (very powerful) Instance Level permission:
- 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);
- }
- }
复制代码
主要的方法就是这些
SpringSecurity框架也都是有的:
- Subject currentUser = SecurityUtils.getSubject();
- Session session = currentUser.getSession();
- currentUser.isAuthenticated()
- currentUser.getPrincipal()
- currentUser.hasRole("schwartz")
- currentUser.isPermitted("lightsaber:wield")
- currentUser.logout();
复制代码
3.运行结果

来源:https://blog.caogenba.net/aaa123_456aaa/article/details/122411808
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |