SpringBoot之----了解Shiro安全框架

2022年01月14日 阅读数:1
这篇文章主要向大家介绍SpringBoot之----了解Shiro安全框架,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

1.Shiro简介

咱们能够理解为跟SpringSecurity框架差很少的框架只不过更加的完美:
Shiro 能够很是容易的开发出足够好的应用,其不只能够用在 JavaSE 环境,也能够用在 JavaEE 环境。
Shiro 能够帮助咱们完成:认证、受权、加密、会话管理、与 Web 集成、缓存等。
记住一点,Shiro 不会去维护用户、维护权限;这些须要咱们本身去设计 / 提供;而后经过相应的接口注入给 Shiro 便可。
在这里插入图片描述
在这里插入图片描述前端

能够看到:应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject;其每一个 API 的含义:java

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

SecurityManager:安全管理器;即全部与安全有关的操做都会与 SecurityManager 交互;且它管理着全部 Subject;能够看出它是 Shiro 的核心,它负责与后边介绍的其余组件进行交互,若是学习过 SpringMVC,你能够把它当作 DispatcherServlet 前端控制器;spring

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

也就是说对于咱们而言,最简单的一个 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框架也都是有的:session

Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.getPrincipal()
currentUser.hasRole("schwartz")
currentUser.isPermitted("lightsaber:wield")
currentUser.logout();

3.运行结果

在这里插入图片描述